New to Telerik UI for WinForms? Download free 30-day trial

Accessing and Iterating through Columns

Accessing Columns

You can access any column by name or index. Generally speaking, accessing the columns by name is the preferred approach because if the user reorders the columns the indexes would also change.

For example, the code snippet below sets the width of an image column named "Picture" to 110:

Accessing RadGridView columns

((GridViewImageColumn)this.radGridView1.Columns["Picture"]).Width = 110;

Iterating through Columns

You can iterate through grid columns by using the Columns collection of GridViewColumn objects. The example below cycles through the columns of the grid, it first determines if the column is a GridViewDataColumn type, and then sets each column’s HeaderText with the number of the current column:

Iterating through RadGridView columns

int i = 0;
foreach (GridViewColumn column in radGridView1.Columns)
{
    if (column is GridViewDataColumn)
    {
        GridViewDataColumn col = column as GridViewDataColumn;
        if (col != null)
        {
            col.Width = 90;
            col.HeaderText = "Column count : " + i.ToString();
            i++;
        }
    }
}

Figure 1: Iterating columns and setting their HeaderText.

WinForms RadGridView Iterating columns and setting their HeaderText

Iterating through Hierarchical Columns

Iterating through hierarchical RadGridView is possible by iterating through the Columns’ collection of each RadGridView template (each template represents one level of hierarchy).

Iterating through hierarchical RadGridView columns

private void AccessingAndIteratingThroughColumns2_Load(object sender, EventArgs e)
{
    this.order_DetailsTableAdapter.Fill(this.nwindDataSet.Order_Details);
    this.ordersTableAdapter.Fill(this.nwindDataSet.Orders);
    this.customersTableAdapter.Fill(this.nwindDataSet.Customers);
    radGridView1.AutoGenerateHierarchy = true;
    radGridView1.DataSource = this.nwindDataSet;
    radGridView1.DataMember = "Customers";
    int count = 0;
    foreach (GridViewDataColumn dataColumn in this.GetAllColumns(this.radGridView1.MasterTemplate))
    {
        dataColumn.WrapText = true;
        dataColumn.HeaderText = "Column count: " + count++;
    }
}
public List<GridViewDataColumn> GetAllColumns(GridViewTemplate template)
{
    List<GridViewDataColumn> allColumns = new List<GridViewDataColumn>();
    allColumns.AddRange(template.Columns);
    foreach (GridViewTemplate childTemplate in template.Templates)
    {
        List<GridViewDataColumn> childColumns = this.GetAllColumns(childTemplate);
        allColumns.AddRange(childColumns);
    }
    return allColumns;
}