0

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;
                }
            }
        }
2
  • Do you want to save the checkbox state on every click? or just once after the user acts on several rows? Commented Apr 29, 2016 at 19:44
  • save the checkbox state on every click Commented May 4, 2016 at 4:34

3 Answers 3

1

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

If so, what error messages have you gotten?

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

0

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;

4 Comments

sorry but the columnID is? because my other column are boundfield connected to database.
Show me your SiteGridView_RowDataBound event
i paste the SiteGridView_RowDataBound event in codebehind
Pls share your save method to database

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.