这里一个完整的示例来隐藏基于一个CheckBoxList的GridView的列。
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//fill the datatable from the database
DataTable dt = //fill the table here...
//bind the table to the grid
GridView1.DataSource = dt;
GridView1.DataBind();
//loop all the datatable columns to fill the checkboxlist
for (int i = 0; i < dt.Columns.Count; i++)
{
CheckBoxList1.Items.Insert(i, new ListItem(dt.Columns[i].ColumnName, dt.Columns[i].ColumnName, true));
}
}
}
protected void CheckBoxList1_TextChanged(object sender, EventArgs e)
{
//loop all checkboxlist items
foreach (ListItem item in CheckBoxList1.Items)
{
if (item.Selected == true)
{
//loop all the gridview columns
for (int i = 0; i < GridView1.Columns.Count; i++)
{
//check if the names match and hide the column
if (GridView1.HeaderRow.Cells[i].Text == item.Value)
{
GridView1.Columns[i].Visible = false;
}
}
}
}
}
而且
<asp:CheckBoxList ID="CheckBoxList1" runat="server" OnTextChanged="CheckBoxList1_TextChanged" AutoPostBack="true"></asp:CheckBoxList>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="field01" HeaderText="Column A" />
<asp:BoundField DataField="field02" HeaderText="Column B" />
<asp:BoundField DataField="field03" HeaderText="Column C" />
<asp:BoundField DataField="field04" HeaderText="Column D" />
<asp:BoundField DataField="field05" HeaderText="Column E" />
</Columns>
</asp:GridView>
注意AutoGenerateColumns
设置为false .aspx页上。如果它们是自动生成的,则这些列不是GridView Columns Collection的一部分。
当然,HeaderText="xxx"
必须与数据库中存储在DataTable中的列名称匹配。
兄弟我没有在gridview中使用boundfield ...我想将数据库表格列绑定到checkboxlist,然后在gridview中动态显示它... – Vinoth
@Vinoth请发送您的代码。 –
我正在使用VS2015创建一个网页,我从数据库中返回一个表格。我想要做的是用数据库返回的表中的列名称填充一个复选框列表。 有没有办法做到这一点? 或者我可以查询数据库,并让它返回一个列名称的表? 复选框列表将用于允许用户决定他们想要显示哪些列。 – Vinoth