This is a migrated thread and some comments may be shown as answers.

Column values of a sql table as Headers in RadGrid

1 Answer 76 Views
Grid
This is a migrated thread and some comments may be shown as answers.
Naveen kumar
Top achievements
Rank 1
Naveen kumar asked on 18 Oct 2012, 08:42 AM
How to show a column values of a sql table as headers in radgrid ?

1 Answer, 1 is accepted

Sort by
0
Shinu
Top achievements
Rank 2
answered on 18 Oct 2012, 09:12 AM
Hi,

I'm not quite sure about your requirement. Please take a look into the sample code snippet I tried to show Customer id as the Header of the columns in RadGrid.

ASPX:
<telerik:RadGrid ID="RadGrid1" Width="95%" runat="server" OnItemCreated="RadGrid1_ItemCreated"
    OnNeedDataSource="RadGrid1_NeedDataSource1"></telerik:RadGrid>

C#:
public DataTable GetDataTable(string query)
{
    String ConnString = ConfigurationManager.ConnectionStrings["NorthwindConnectionString3"].ConnectionString;
    SqlConnection conn = new SqlConnection(ConnString);
    SqlDataAdapter adapter = new SqlDataAdapter();
    adapter.SelectCommand = new SqlCommand(query, conn);
 
    DataTable myDataTable = new DataTable();
 
    conn.Open();
    try
    {
        adapter.Fill(myDataTable);
    }
    finally
    {
        conn.Close();
    }
 
    return myDataTable;
}
 
public DataTable PivotTable(DataTable source)
{
    DataTable dest = new DataTable("Pivoted" + source.TableName);
 
    dest.Columns.Add(" ");
 
    foreach (DataRow r in source.Rows)
        dest.Columns.Add(r[0].ToString());
 
    for (int i = 0; i < source.Columns.Count - 1; i++)
    {
        dest.Rows.Add(dest.NewRow());
    }
 
    for (int r = 0; r < dest.Rows.Count; r++)
    {
        for (int c = 0; c < dest.Columns.Count; c++)
        {
            if (c == 0)
                dest.Rows[r][0] = source.Columns[r + 1].ColumnName;
            else
                dest.Rows[r][c] = source.Rows[c - 1][r + 1];
        }
    }
    dest.AcceptChanges();
    return dest;
}
 
protected void RadGrid1_NeedDataSource1(object source, GridNeedDataSourceEventArgs e)
{
    RadGrid1.DataSource = PivotTable(GetDataTable("SELECT TOP 5 CustomerID, CompanyName, ContactName, ContactTitle, Address, PostalCode, City, Country FROM Customers"));
}
protected void RadGrid1_ItemCreated(object sender, GridItemEventArgs e)
{
    if (e.Item is GridDataItem)
    {
        (e.Item as GridDataItem)[(RadGrid1.MasterTableView.AutoGeneratedColumns[0] as GridBoundColumn).UniqueName].Font.Bold = true;
        (e.Item as GridDataItem)[(RadGrid1.MasterTableView.AutoGeneratedColumns[0] as GridBoundColumn).UniqueName].BackColor = System.Drawing.SystemColors.Control;
        (e.Item as GridDataItem)[(RadGrid1.MasterTableView.AutoGeneratedColumns[0] as GridBoundColumn).UniqueName].BorderColor = System.Drawing.Color.White;
    }
}

Thanks,
Shinu.
Tags
Grid
Asked by
Naveen kumar
Top achievements
Rank 1
Answers by
Shinu
Top achievements
Rank 2
Share this question
or