我创建了一列复选框的GridView。我希望用户选择复选框,单击注册按钮(在gridview外部),并显示所选行的标题。从我读过的东西我应该把复选框检查按钮点击事件。我已经这样做了,但显然它进入该事件的唯一时间是在页面加载时,在加载页面之前,所有选中的复选框都将被擦除。因此,我检查选定的复选框从未出现过。是否有更好的时间运行此检查的事件,或者是通过页面加载保存这些值的方法?以下不是我所有的代码,只是受影响的部分。GridView复选框列与事件
protected void regButton_Click(Object sender, EventArgs e)
{
StringBuilder regClasses = new StringBuilder();
for (int i = 0; i < SQLQueryClassListings.Rows.Count; i++)
{
//Response.Write(SQLQueryClassListings.Rows[i].Cells[0].Text + " checkbox check ");
GridViewRow checkRow = SQLQueryClassListings.Rows[i];
bool reg = ((CheckBox)(checkRow.FindControl("RowCheckBox"))).Checked;
if (reg)
{
regClasses.Append(SQLQueryClassListings.Rows[i].Cells[0].Text + " ");
}
}
Response.Write(regClasses);
}
<asp:GridView ID="SQLQueryClassListings" AutoGenerateColumns="false" runat="server"
BorderWidth="1px" BackColor="White" CellPadding="5" BorderColor="Black" RowStyle-BorderColor = "Black"
HeaderStyle-BackColor="#0D69F2" HeaderStyle-ForeColor="White" AlternatingRowStyle-BackColor="#E8E8E8" HeaderStyle-BorderColor="Black" GridLines="Both">
<Columns>
<asp:BoundField HeaderText="Classes" DataField="LeafName" HeaderStyle-HorizontalAlign="Left" ItemStyle-Width="250"
ItemStyle-BorderColor="#ADADAD" HeaderStyle-BorderColor ="Black"/>
<asp:BoundField HeaderText="Teacher" DataField="TeacherName" HeaderStyle-HorizontalAlign="Left" ItemStyle-Width="200"
ItemStyle-BorderColor="#ADADAD" HeaderStyle-BorderColor ="Black"/>
<asp:BoundField HeaderText="Available" DataField="SemesterEnds" HeaderStyle-HorizontalAlign="Center"
ItemStyle-HorizontalAlign ="Center" ItemStyle-Width="150" ItemStyle-BorderColor="#ADADAD" HeaderStyle-BorderColor ="Black"/>
<asp:HyperLinkField HeaderText="Course Description & Career Tracks" DataNavigateUrlFields="ApplicableTracks"
Text="See Description" HeaderStyle-HorizontalAlign="Center" ItemStyle-HorizontalAlign ="Center" ItemStyle-BorderColor="#ADADAD" HeaderStyle-BorderColor ="Black"/>
<asp:TemplateField HeaderText="Register" HeaderStyle-BorderColor="Black" ItemStyle-BorderColor = "#ADADAD" ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:CheckBox runat="server" ID="RowCheckBox"/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<p>
<asp:Button ID="Button1" runat="server" Text="Register" OnClientClick="return confirm('You have sucessfully registered!')"
OnClick="regButton_Click" />
我的英雄!它现在完美。我再也不会犯这个错误了。 – VengefulSakhmet 2009-08-28 16:43:15
我的荣幸。 :)但这不完全是一个错误!在某些情况下,您希望在每次回发时重新绑定(例如,当您绝对需要最新的数据时)。但在这些情况下,您需要使用另一种将用户选择传递给服务器的方法(例如,将ID保存在由ViewState支持的页面上的属性中,或在表单上使用隐藏的输入控件)。 – 2009-08-28 17:52:28