更新按钮上的数据库按不按CheckBox检查

时间:2016-01-26 15:46:10

标签: c# asp.net checkbox

我似乎陷入隧道视觉,只看到如何根据复选框的检查/取消选中事件更新数据库。我想要做的是将事件从触发持续到按下按钮。我怎么能实现这个目标呢?

HTML

<td valign="top" style="text-align: left; width: 200px;">
<asp:GridView runat="server" ID="datagridTest" AutoGenerateColumns="false" GridLines="Both" >
    <Columns>
    <asp:BoundField DataField="thirteen" HeaderText="You" />
    <asp:BoundField DataField="seven" HeaderText="Me" />
    <asp:TemplateField>
        <ItemTemplate>
            <asp:Label runat="server" Text='<%#Eval("josemen1212") %>' ID="red" Visible="false"></asp:Label>
         </ItemTemplate>
        <ItemTemplate>
            <asp:CheckBox ID="checker" runat="server" AutoPostBack="true" OnCheckedChanged="Checker_Click" Checked='<%# Convert.ToBoolean(Eval("green")) %>' />
        </ItemTemplate>
    </asp:TemplateField>
    </Columns>
</asp:GridView>
</br>
<asp:Button runat="server" ID="btnClickMe" CssClass="Buttons" Text="Click" OnClick="btnClickMe_Click" />
</td>

C#

private void btnClickMe_Click(object sender, EventArgs e)
{
  //Here is where I want the update to run
}

protected void Checker_Click(object sender, EventArgs e)
{
foreach (GridViewRow row in dgRD.Rows)
{
    if (row.RowType == DataControlRowType.DataRow)
    {
        CheckBox chk = (CheckBox)row.FindControl("checker");
        if (chk.Checked)
        {
            string ID = ((Label)row.FindControl("josemen1212")).Text;
            //Run Sql statement to update db
        }
        else
        {
            string ID = ((Label)row.FindControl("josemen1212")).Text;
            //Run sql statement to update db
        }
    }
}
}

1 个答案:

答案 0 :(得分:1)

将代码从Checker_Click方法移至btnClickMe_Click事件? 像这样:

 private void btnClickMe_Click(object sender, EventArgs e)
    {
      foreach (GridViewRow row in dgRD.Rows)
    {
        if (row.RowType == DataControlRowType.DataRow)
        {
            CheckBox chk = (CheckBox)row.FindControl("checker");
            if (chk.Checked)
            {
                string ID = ((Label)row.FindControl("josemen1212")).Text;
                //Run Sql statement to update db
            }
            else
            {
                string ID = ((Label)row.FindControl("josemen1212")).Text;
                //Run sql statement to update db
            }
        }
    }
    }