This post will guide you how to remove and add column in gridview in asp.net. In
this example, I have a RadioButtonList and gridview with four columns. When I click on Remove Column Tel radio button, Tel column will remove from gridview. And when I click on Add Column Tel radio button, Tel column will add in gridview. Please examine code below:
Code Design :
<asp:RadioButtonList ID="Rdbshow" runat="server" AutoPostBack="true" onselectedindexchanged="Rdbshow_SelectedIndexChanged">
<asp:ListItem Value="1" >Remove Column Tel</asp:ListItem>
<asp:ListItem Value="2"> Add Column Tel </asp:ListItem>
</asp:RadioButtonList>
Code Design :
<asp:RadioButtonList ID="Rdbshow" runat="server" AutoPostBack="true" onselectedindexchanged="Rdbshow_SelectedIndexChanged">
<asp:ListItem Value="1" >Remove Column Tel</asp:ListItem>
<asp:ListItem Value="2"> Add Column Tel </asp:ListItem>
</asp:RadioButtonList>
<asp:GridView ID="GridView1"
runat="server"
AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="ID"
HeaderText="ID"
SortExpression="ID"
/>
<asp:BoundField DataField="Name"
HeaderText="Name"
SortExpression="Name"
/>
<asp:BoundField DataField="Gender"
HeaderText="Gender" SortExpression="Gender" />
<asp:BoundField DataField="Tel" HeaderText="Tel" SortExpression="Tel" />
</Columns>
</asp:GridView>
Code Behind :
protected void Rdbshow_SelectedIndexChanged(object sender, EventArgs
e)
{
if
(Rdbinvoice.SelectedValue.ToString() == "1")
{
// column Tel’s index is 3rd
of Gridview1
// remove column Tel
GridView1.Columns.RemoveAt(3);
}else if (Rdbinvoice.SelectedValue.ToString() == "2")
{
BoundField colname = new BoundField();
//Tell is
the name of table field in database
colname.DataField = "Tel";
// Tell is the name of Gridview
header
colname.HeaderText = "Tel";
//add
column Tel
GridView1.Columns.Add(colname);
}
}
Done...:) :) . Now you can remove or add a Tel column in gridview by click on radiobuttonlist.
How to remove and add specific column in gridview in ASP.Net using C#
Reviewed by BeiLover
on
4:21 PM
Rating:
No comments: