简体   繁体   中英

Store checked checkbox in gridview in database ASP.NET C#

I am able to retrieve out data from database to show which is Y and N using checkbox in gridview. However now i want to to able to store which checkbox is checked back into the database after editing.

What i did so far:

.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>

CodeBehind:

     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;
                }
            }
        }

Have you tried: Checked='<%# Eval("PROCESSED")%>'

If so, what error messages have you gotten?

First of all use a foreach loop to findout which rows are checked. Then store ID of those rows in a 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;

For some reason Checkboxes do not trigger GridView RowCommand events. It probably can be done with appropriate calls to ClientScript.GetPostBackEventReference() , but thats a whole other level of complexity. So, in order to act on a CheckBox click and handle events individually:

(NB: I've stripped out much of your coding to clarify my points.)

  1. In your CheckBox set AutoPostBack="true"
  2. Add a handler for OnCheckedChanged .
  3. Make sure the DataKey contains the pk of the row you need to update with the CheckBox State

     // 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. In the RowDataBound event, find the CheckBox and add the Row Index as an attribute

     // 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. Handle the CheckChanged event:

     // 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(); } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM