aspx 代码
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="TestButton" runat="server" OnClick="TestButton_Click"
Text="AddNewRow" />
</div>
<div>
<asp:GridView ID="MyGrid" runat="server" GridLines="Both"
AutoGenerateColumns="false" OnDataBound="MyGrid_DataBound"
EnableViewState="true">
<Columns>
<asp:BoundField DataField="Name" HeaderText="name" />
<asp:TemplateField HeaderText="CheckBox1">
<ItemTemplate>
<asp:CheckBox ID="CheckBox1" EnableViewState="true"
runat="server" AutoPostBack="true" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="CheckBox2">
<ItemTemplate>
<asp:CheckBox ID="CheckBox2" runat="server"
EnableViewState="true" AutoPostBack="true" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="CheckBox3">
<ItemTemplate>
<asp:CheckBox ID="CheckBox3" runat="server"
AutoPostBack="true" EnableViewState="true" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
</form>
</body>
</html>
背后的代码
public DataTable Dt = new DataTable();
protected void Page_Load(object sender, EventArgs e) { }
protected void TestButton_Click(object sender, EventArgs e)
{
DataRow dr = null;
if(ViewState["T"]==null)
{
Dt.Columns.Add(new DataColumn("Name", typeof(string)));
Dt.Columns.Add(new DataColumn("CheckBox1", typeof(bool)));
Dt.Columns.Add(new DataColumn("CheckBox2", typeof(bool)));
Dt.Columns.Add(new DataColumn("CheckBox3", typeof(bool)));
ViewState["T"] = Dt;
}
Dt =(DataTable) ViewState["T"];
dr = Dt.NewRow();
dr["Name"] = "Sam";
dr["CheckBox1"] = true;
dr["CheckBox2"] = false;
dr["CheckBox3"] = false;
Dt.Rows.Add(dr);
SearchGrid.DataSource = Dt;
SearchGrid.DataBind();
}
protected void MyGrid_DataBound(object sender, EventArgs e)
{
(SearchGrid.Rows[SearchGrid.Rows.Count - 1].Cells[1].FindControl("CheckBox1")
as CheckBox).Checked = true;
}
}
当我单击 Addnew 行按钮时,结果将是这样的
但是当我再次点击时
第一行复选框未选中。我已经为每个复选框启用了视图状态,但它仍然不起作用。我应该对我绑定的数据表做些什么吗?