Looping Data Grid Column

Posted by .Netlearner under ASP.NET on 1/17/2013 | Points: 10 | Views : 1006 | Status : [Member] | Replies : 1
Hello All,

Am having a datagrid which fetches data from the database.If the column is empty i want to hide that column.Can anyone please guide me how to loop through the datagrid columns and acheive this task.




Responses

Posted by: Ranjeet_8 on: 1/18/2013 [Member] [MVP] Gold | Points: 25

Up
0
Down
Before binding the Gird View you can remove the empty column from DataTable.
Try this,

DataTable dt = new DataTable();
DataRow dr;
dt.Columns.Add("Name", typeof(string));
dt.Columns.Add("Add1", typeof(string));
dt.Columns.Add("Add2", typeof(string));
dr = dt.NewRow();
dr["Name"] = "sadf";
dr["Add1"] = "rwe";
dr["Add2"] = null;
dt.Rows.Add(dr);
dr = dt.NewRow();
dr["Name"] = "sadf2";
dr["Add1"] = "rwe";
dr["Add2"] = null;
dt.Rows.Add(dr);
dr = dt.NewRow();
dr["Name"] = "sadf4";
dr["Add1"] = "rwe";
dr["Add2"] = null;
dt.Rows.Add(dr);
dr = dt.NewRow();
dr["Name"] = "sadf5";
dr["Add1"] = "rwe";
dr["Add2"] = null;
dt.Rows.Add(dr);
foreach (var column in dt.Columns.Cast<DataColumn>().ToArray())
{
if (dt.AsEnumerable().All(dr1 => dr1.IsNull(column)))
dt.Columns.Remove(column);
}
GridView1.DataSource = dt;
GridView1.DataBind();


Please Mark As Answer if this helps you

.

.Netlearner, if this helps please login to Mark As Answer. | Alert Moderator

Login to post response