Now I would like to share how to hide specific column that you want to
hide a column within gridview in ASP.Net using C#. I have a gridview
with two columns. Now I want to hide a column when I click on a radio button. Please examine code below:
Form Design :
<asp:RadioButtonList ID="Rdbshow" runat="server" AutoPostBack="true" onselectedindexchanged="Rdbshow_SelectedIndexChanged">
<asp:ListItem Value="1" Selected="true"> Hide TOV_ID</asp:ListItem>
<asp:ListItem Value="2">show TOV_ID </asp:ListItem> </asp:RadioButtonList>
<asp:GridView ID="GridView1" runat="server" AllowSorting="True" AutoGenerateColumns="False" DataKeyNames="TOV_ID" >
<Columns>
<asp:BoundField DataField="TOV_ID" HeaderText="TOV_ID" SortExpression="TOV_ID" />
<asp:BoundField DataField="TOV_Description" HeaderText="Visitor Type" SortExpression="TOV_Description" />
</Columns>
</asp:GridView>
Code Behind:
protected void Rdbshow_SelectedIndexChanged(object sender, EventArgs e)
{
if (Rdbshow.SelectedValue.ToString() == "1")
{
GridViewdata.Columns[0].HeaderText = "TOV_ID";
// hide column
GridViewdata.Columns[0].Visible = False;
}else if (Rdbshow.SelectedValue.ToString() == "2") {
GridViewdata.Columns[0].HeaderText = "TOV_ID";
// show column
GridViewdata.Columns[0].Visible = True;
}
}
Note: TOV_ID is HeaderText that you want to hide , 0 is Column's index of TOV_ID column.
Let's debug your code. So when you click on Hide TOV_ID radiobutton, the TOV_ID column will hide and It will show it if you click on Show TOV_ID radiobutton.
Form Design :
<asp:RadioButtonList ID="Rdbshow" runat="server" AutoPostBack="true" onselectedindexchanged="Rdbshow_SelectedIndexChanged">
<asp:ListItem Value="1" Selected="true"> Hide TOV_ID</asp:ListItem>
<asp:ListItem Value="2">show TOV_ID </asp:ListItem> </asp:RadioButtonList>
<asp:GridView ID="GridView1" runat="server" AllowSorting="True" AutoGenerateColumns="False" DataKeyNames="TOV_ID" >
<Columns>
<asp:BoundField DataField="TOV_ID" HeaderText="TOV_ID" SortExpression="TOV_ID" />
<asp:BoundField DataField="TOV_Description" HeaderText="Visitor Type" SortExpression="TOV_Description" />
</Columns>
</asp:GridView>
Code Behind:
protected void Rdbshow_SelectedIndexChanged(object sender, EventArgs e)
{
if (Rdbshow.SelectedValue.ToString() == "1")
{
GridViewdata.Columns[0].HeaderText = "TOV_ID";
// hide column
GridViewdata.Columns[0].Visible = False;
}else if (Rdbshow.SelectedValue.ToString() == "2") {
GridViewdata.Columns[0].HeaderText = "TOV_ID";
// show column
GridViewdata.Columns[0].Visible = True;
}
}
Note: TOV_ID is HeaderText that you want to hide , 0 is Column's index of TOV_ID column.
Let's debug your code. So when you click on Hide TOV_ID radiobutton, the TOV_ID column will hide and It will show it if you click on Show TOV_ID radiobutton.
How to hide specific column in gridview in ASP.Net using C#
Reviewed by BeiLover
on
11:49 AM
Rating:
No comments: