Gridview未检测到正在检查的复选框

时间:2015-11-29 18:20:59

标签: c# asp.net gridview checkbox

我想要做的是在检查gridview中的复选框时执行一些代码,并逐行执行代码。我调试了代码,每次都返回false,尽管选中了复选框。如果删除条件语句,我试图执行的代码是有效的。

protected void ShoppingCartButton_Click(object sender, EventArgs e)
{
    Label1.Text = "HIH0HI";

    OleDbConnection myconn = new OleDbConnection();
        myconn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|ProjectDatabase.accdb";

    string UserID = Session["UserID"].ToString();
    StringBuilder sb3 = new StringBuilder();
    foreach (GridViewRow row in GridView1.Rows)
    {
        string unpredictable = "";
        bool hi = true;
        unpredictable = row.Cells[1].Text;
        CheckBox chk = row.Cells[0].Controls[1] as CheckBox;
        hi = chk.Checked;
        sb3.Append(hi.ToString());
        if (hi==true)
        {
            string command1 = "insert into Cart ([Username],[GameID]) values (@Username, @GameID)";

            OleDbCommand cmd = new OleDbCommand(command1, myconn);
            cmd.Parameters.AddWithValue("@Username", UserID);
            cmd.Parameters.AddWithValue("@GameID", unpredictable);
            myconn.Open();
            cmd.ExecuteNonQuery();
            myconn.Close();
        }
    }
    Label1.Text =  sb3.ToString();
}

按钮和gridview的标记

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="True" EmptyDataText ="Data Entry Error">
    <Columns>
         <asp:TemplateField HeaderText ="Add to Cart?">
             <ItemTemplate>
                 <asp:CheckBox ID="checkbx" runat="server" />
             </ItemTemplate>
          </asp:TemplateField>
    </Columns>
</asp:GridView>
<asp:Button runat="server" id="ShoppingCartButton" Text="Add to     shopping cart" OnClick="ShoppingCartButton_Click" />  

1 个答案:

答案 0 :(得分:0)

这很简单。必须包含任何数据绑定逻辑     if(!IsPostBack)