這裏一個完整的示例來隱藏基於一個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