Is it possible to change the DataField property of the GridBoundColumn based upon a selected value outside of the Grid?
thanks
2 Answers, 1 is accepted
0
Accepted
Attila Antal
Telerik team
answered on 29 Aug 2019, 12:11 PM
Hi John,
Yes, it can be done. You will need to familiarize yourself with the Accessing Cells and Rows article to understand how to access items in the grid.
Here is a complete example where the DataField is being changed on a Button Click (same approach could be used for other control, OnSelectedIndexChanged events, etc..)
protectedvoidRadGrid1_NeedDataSource(object sender, GridNeedDataSourceEventArgs e)
{
RadGrid1.DataSource = OrdersTable();
}
private DataTable OrdersTable()
{
DataTable dt = new DataTable();
dt.Columns.Add(new DataColumn("OrderID", typeof(int)));
dt.Columns.Add(new DataColumn("OrderDate", typeof(DateTime)));
dt.Columns.Add(new DataColumn("Freight", typeof(decimal)));
dt.Columns.Add(new DataColumn("ShipName", typeof(string)));
dt.Columns.Add(new DataColumn("ShipCountry", typeof(string)));
dt.PrimaryKey = new DataColumn[] { dt.Columns["OrderID"] };
for (int i = 0; i < 70; i++)
{
int index = i + 1;
DataRow row = dt.NewRow();
row["OrderID"] = index;
row["OrderDate"] = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 0, 0, 0).AddHours(index);
row["Freight"] = index * 0.1 + index * 0.01;
row["ShipName"] = "Name " + index;
row["ShipCountry"] = "Country " + index;
dt.Rows.Add(row);
}
return dt;
}
protectedvoidRadButton1_Click(object sender, EventArgs e)
{
RadButton btn = sender as RadButton;
// access the column
GridBoundColumn col = RadGrid1.MasterTableView.GetColumn("MyColumn") as GridBoundColumn;
// if condition metif (btn.Text == "Show Freight")
{
btn.Text = "Show ShipCountry";
// change the DataField
col.DataField = "Freight";
// optionally you can change the Column header text as well
col.HeaderText = "Freight";
}else
{
btn.Text = "Show Freight";
// change the DataField
col.DataField = "ShipCountry";
// optionally you can change the Column header text as well
col.HeaderText = "Ship Country";
}
// force Rebind() the grid for the changes to take effect
RadGrid1.Rebind();
}
Kind regards,
Attila Antal
Progress Telerik
Get quickly onboarded and successful with your Telerik and/or Kendo UI products with the Virtual Classroom free technical training, available to all active customers.Learn More.