girdview中绑定 checkbox 的问题,送出所有分,不够以后再加

来源:百度知道 编辑:UC知道 时间:2024/06/16 02:22:09
SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=Northwind;User ID=sa;Password=;");
con.Open();

绑定一个gridview SqlCommand cmd3 = new SqlCommand("select top 5 OrderID from Orders ", con);
SqlDataAdapter sda = new SqlDataAdapter();
sda.SelectCommand = cmd3;
DataSet dsyou = new DataSet();
sda.Fill(dsyou, "youxiao");
this.GridView1.DataSource = dsyou.Tables["youxiao"];
this.GridView1.DataBind();
然后添加了一个绑定列 checkbox
<asp:GridView ID="GridView1" runat="server">
<Columns>
<asp:TemplateField HeaderText="000">
<ItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" />
</ItemTemplate>
</

出错原因:
你对Gridview的数据绑定代码没有写在if(!ispostback){}里,这样在点击按钮后页面会刷新,Gridview重新绑定数据,所有的checkbox成为无选中状态,这就是你遇到的现象.
解决办法:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=Northwind;User ID=sa;Password=;");
SqlCommand cmd3 = new SqlCommand("select top 5 OrderID from Orders ", con);
SqlDataAdapter sda = new SqlDataAdapter();
sda.SelectCommand = cmd3;
DataSet dsyou = new DataSet();
sda.Fill(dsyou, "youxiao");
this.GridView1.DataSource = dsyou.Tables["youxiao"];
this.GridView1.DataBind();

}
}
这样写就成了

CheckBox chk = (CheckBox)this.GridView1.Rows[i][列].FindControl("CheckBox1");