网格中的显示/隐藏列。 该例子只是显示/隐藏单列的例子。
扩展出来的例子就是:网格中所有字段都放在一个表单里,通过选择checkbox设置显示/隐藏列。
源代码:
<%@ Import Namespace="System.Data" %>
<html>
<script language="C#" runat="server">
ICollection CreateDataSource() {
DataTable dt = new DataTable();
DataRow dr;
dt.Columns.Add(new DataColumn("IntegerValue", typeof(Int32)));
dt.Columns.Add(new DataColumn("StringValue", typeof(string)));
dt.Columns.Add(new DataColumn("DateTimeValue", typeof(DateTime)));
dt.Columns.Add(new DataColumn("BoolValue", typeof(bool)));
dt.Columns.Add(new DataColumn("CurrencyValue", typeof(double)));
for (int i = 0; i < 9; i++) {
dr = dt.NewRow();
dr[0] = i;
dr[1] = "项 " + i.ToString();
dr[2] = DateTime.Now;
dr[3] = (i % 2 != 0) ? true : false;
dr[4] = 1.23 * (i+1);
dt.Rows.Add(dr);
}
DataView dv = new DataView(dt);
return dv;
}
void Page_Load(Object sender, EventArgs e) {
if (!IsPostBack) {
MyDataGrid.DataSource= CreateDataSource();
MyDataGrid.DataBind();
Label1.Text = "列 1 的可见属性设置为 " + MyDataGrid.Columns[1].Visible.ToString();
}
}
void Button1_Col1Vis(Object sender, EventArgs e) {
MyDataGrid.Columns[1].Visible = !MyDataGrid.Columns[1].Visible;
Label1.Text = "列 1 的可见属性设置为 " + MyDataGrid.Columns[1].Visible.ToString();
}
</script>
<body>
<h3><font face="宋体">在 DataGrid 中隐藏列</font></h3>
<form runat=server>
<ASP:DataGrid id="MyDataGrid" runat="server"
BorderColor="black"
BorderWidth="1"
GridLines="Both"
CellPadding="3"
CellSpacing="0"
Font-Name="宋体"
Font-Size="8pt"
HeaderStyle-BackColor="#aaaadd"
AutoGenerateColumns="false"
>
<Columns>
<asp:BoundColumn HeaderText="整数" DataField="IntegerValue" />
<asp:BoundColumn HeaderText="日期/时间 (Column1)" DataField="DateTimeValue"/>
<asp:BoundColumn HeaderText="字符串" DataField="StringValue"/>
<asp:BoundColumn HeaderText="真/假" DataField="BoolValue"/>
<asp:BoundColumn HeaderText="价格" DataField="CurrencyValue" DataFormatString="{0:c}" ItemStyle-HorizontalAlign="right" />
</Columns>
</asp:DataGrid>
<br>
<asp:Button id="Button1" Text="切换列 1 的可见性" OnClick="Button1_Col1Vis" runat="server" />
<br>
<asp:Label id="Label1" runat="server" />
</form>
</body>
</html>
效果:
参考:http://chs.gotdotnet.com/quickstart/aspplus/samples/webforms/ctrlref/webctrl/datagrid/doc_datagrid.aspx#hiding