【问题标题】:Store checked checkbox in gridview in database ASP.NET C#在数据库 ASP.NET C# 中的 gridview 中存储选中的复选框
【发布时间】:2016-04-29 04:23:25
【问题描述】:

我可以使用 gridview 中的复选框从数据库中检索数据以显示 Y 和 N。但是现在我希望能够在编辑后将选中的复选框存储回数据库中。

到目前为止我做了什么:

.aspx

    <asp:GridView ID="SiteGridView" runat="server" CssClass="datagrid" 
                  GridLines="Vertical" AutoGenerateColumns="False"
                  Width="100%" 
                  AllowPaging="True" AllowSorting="True" 
                  DataKeyNames="promoID"  OnRowCommand="GvPage_RowCommand" 
                  OnPageIndexChanging="GvPage_PageIndexChanging" 
                  OnSorting="GvPage_Sorting" 
                  OnRowDatabound="SiteGridView_RowDataBound"
                  OnRowEditing="SiteGridView_RowEditing">
      <Columns>       
        <asp:TemplateField HeaderText="Default">
          <ItemTemplate>
            <asp:CheckBox ID="process_flag" runat="server" 
              Checked='<%# bool.Parse(Eval("PROCESSED").ToString()) %>'
              Enable='<%# !bool.Parse(Eval("PROCESSED").ToString()) %>' />
          </ItemTemplate>
          <ItemStyle Width="20%" />
        </asp:TemplateField>
       </Columns>
     </asp:GridView>

代码隐藏:

     SqlCommand cmd = new SqlCommand("SELECT * , CAST(CASE defaults WHEN 'Y' THEN 1 ELSE 0 END AS BIT) AS PROCESSED FROM Promotions"); 
                SqlDataAdapter da = new SqlDataAdapter(); 
                DataTable dt = new DataTable(); 
                da.SelectCommand = cmd; 

                // Save results of select statement into a datatable 
                da.Fill(dt);

                SiteGridView.DataSource = dt;
                SiteGridView.DataBind(); 

        protected void SiteGridView_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                //check userrole & display accrodingly
                if (Session["ROLE"].ToString() != "SA")
                {
                    //ImageButton btnEdit = (ImageButton)e.Row.FindControl("btnDelete");
                    //btnEdit.Visible = false;
                    SiteGridView.Columns[4].Visible = false;
                }
            }
        }

【问题讨论】:

  • 您想在每次点击时保存复选框状态吗?还是仅在用户对多行进行操作后执行一次?
  • 每次点击保存复选框状态

标签: c# asp.net gridview checkbox


【解决方案1】:

您是否尝试过: Checked=''

如果是这样,您收到了哪些错误消息?

【讨论】:

    【解决方案2】:

    由于某些原因,复选框不会触发 GridView RowCommand 事件。它可能可以通过对ClientScript.GetPostBackEventReference() 的适当调用来完成,但这完全是另一个级别的复杂性。因此,为了对 CheckBox 进行单击并单独处理事件:

    (注意:为了澄清我的观点,我已经删除了你的大部分代码。)

    1. 在您的复选框中设置AutoPostBack="true"
    2. OnCheckedChanged 添加一个处理程序。
    3. 确保 DataKey 包含您需要使用 CheckBox State 更新的行的 pk

      // Simplified version of your markup
      <asp:GridView ID="SiteGridView" runat="server" 
                    DataKeyNames="promoID" 
                    OnRowDataBound="SiteGridView_RowDataBound">
        <Columns>
          <asp:TemplateField HeaderText="Default">
            <ItemTemplate>
              <asp:CheckBox ID="process_flag" runat="server" 
                Checked='<%# bool.Parse(Eval("PROCESSED").ToString()) %>'
                Enable='<%# !bool.Parse(Eval("PROCESSED").ToString()) %>'
                OnCheckedChanged="process_flag_CheckedChanged" />
            </ItemTemplate>
          </asp:TemplateField>
        </Columns>
      </asp:GridView>
      
    4. RowDataBound事件中,找到CheckBox并添加Row Index作为属性

      // Merge this with your `RowDataBound` event
      protected void SiteGridView_RowDataBound( object sender, GridViewRowEventArgs e ) {
          if ( e.Row.RowType == DataControlRowType.DataRow ) {
              CheckBox cbx = ( CheckBox ) e.Row.FindControl( "CheckBox1" );
              cbx.Attributes[ "data-row-idx" ] = e.Row.RowIndex.ToString();
          }
      }
      
    5. 处理 CheckChanged 事件:

      // Add this handler to your code
      protected void process_flag_CheckedChanged( object sender, EventArgs e ) 
      {
          CheckBox cbx = ( CheckBox ) sender;
          Int32 rowidx = Convert.ToInt32(cbx.Attributes["data-row-idx"]);
          Int32 pk = (Int32) GridView4.DataKeys[rowidx].Value;
      
          // simple way to see event arguments before actually touching the database
          GridView4.Caption = string.Format(
              "CheckChanged: Row {0}, State: {1}, RowPK: {2} ", rowidx , (cbx.Checked ? "Checked" : "Unchecked"), pk );
      
          // Save Data and rebind the gridview to reflect changes
          // Verify your parameters before attempting an actual update
          // YourDatabaseCallWithAppropriateParamaters( ... );
          GridView1.DataBind();
      }
      

    【讨论】:

      【解决方案3】:

      首先使用 foreach 循环找出检查了哪些行。然后将这些行的 ID 存储在 List 中。

      foreach (GridViewRow row in SiteGridView.Rows)
              {
                  if (row.RowType == DataControlRowType.DataRow)
                  {
                      CheckBox chkRow = (row.Cells[0].FindControl("process_flag") as CheckBox);
                      if (chkRow.Checked)
                      {
                          string ID = row.Cells[columnID].Text;
      

      【讨论】:

      • 抱歉,columnID 是?因为我的另一列是绑定到数据库的。
      • 显示您的 SiteGridView_RowDataBound 事件
      • 我将 SiteGridView_RowDataBound 事件粘贴到代码隐藏中
      • 请分享您的保存方法到数据库
      猜你喜欢
      • 2020-12-23
      • 2018-04-29
      • 2016-06-14
      • 1970-01-01
      • 2018-03-29
      • 1970-01-01
      • 1970-01-01
      • 2012-02-04
      • 1970-01-01
      相关资源
      最近更新 更多