Reputation: 1858
I have a usercontrol in Asp, that has a GridView, 'AutoGenerateColumns="False". I must hide or show a column according to a property of UC. How can I do that?
This is how I thought to do:
<asp:TemplateField HeaderText="<%=SelezionaColumnName %>" HeaderStyle-Width="80px">
Note that here the headerText is not set to the public const string SelezionaColumnName but it renders just exactly as it is( in string), not the value but the name with <%= %>
. I don't know why, is this because of binding?
code behind:
public const string SelezionaColumnName = "Seleziona";
public bool ShowSeleziona
{
set
{
grdMaterialiArt.Columns[GetColumnIndexByName(grdMaterialiArt, SelezionaColumnName)].Visible = value;
}
}
protected int GetColumnIndexByName(GridView grid, string name)
{
foreach (DataControlField col in grid.Columns)
{
if (col.HeaderText.ToLower().Trim() == name.ToLower().Trim())
{
return grid.Columns.IndexOf(col);
}
}
return -1;
}
Note: I must note use 0 index. Columns could be added before my column so I must identify uniquely the column. I went on identify by name approach as a TemplateField can not have an ID :| Hope I described the scenario well enough, I also search a lot around but did not found something similar.
Upvotes: 0
Views: 628
Reputation: 7197
protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
{
try
{
DataTable dt = (DataTable ) GridView1.DataSource;
if (!dt.Columns.Contains("COLLUMN_YOU_WANNA_HIDE")) return;
int j = dt.Columns.IndexOf("COLLUMN_YOU_WANNA_HIDE");
e.Row.Cells[j].Visible = false;
e.Row.Cells[j].Width = 0;
}
catch (Exception)
{
}
}
Upvotes: 3