skip to Main Content

I tried to make a message board.

After someone leave message, manager can check message context can be show for others or not.

I use gridView to connect to my SQL Server data, and there is a checkbox in the gridview.

If I checked checkbox, and click "sent" button, SQL Server data will be updated.

If I would like to update checkbox result into SQL Server data, what should I do?

This is my aspx

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="id" OnRowDeleting="GridView1_RowDeleting">
    <Columns>
        <asp:TemplateField HeaderText="check or not" SortExpression="replyCheck">
            <EditItemTemplate>
                <asp:CheckBox ID="CheckBox1" runat="server" Checked='<%# Bind("replyCheck") %>' />
            </EditItemTemplate>
            <ItemTemplate>
                <asp:CheckBox ID="CheckBox2" runat="server" Checked='<%# Bind("replyCheck") %>' Enabled="True" />
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>
<br/>
<asp:Button ID="Button1" runat="server" Text="sent" OnClick="Button1_Click"/>

And this is my aspx.cs – if I use foreach, it can’t update into my database

protected void Button1_Click(object sender, EventArgs e)
{
    var id = GridView1.DataKeys.ToString();

    foreach (GridViewRow row in GridView1.Rows)
    {
        CheckBox reply = (row.Cells[0].FindControl("CheckBox2") as CheckBox);
                    
        if (reply.Checked)
        {
            SqlConnection sqlConnection = new SqlConnection(getsql);
            sqlConnection.Open();

            SqlCommand cmd = new SqlCommand($"UPDATE reply SET replyCheck ='1'  WHERE (id = {id})", sqlConnection);

            cmd.ExecuteNonQuery();

            sqlConnection.Close ();

            DataBind();
        }
    }
}

If I use for, it showed error about "datakey array"

protected void Button1_Click(object sender, EventArgs e)
{
    var id = GridView1.DataKeys.ToString();
    int messageCheck, displayCheck;

    SqlConnection sqlConnection = new SqlConnection(getsql);
    sqlConnection.Open();

    for (int i = 0; i < GridView1.Rows.Count; i++)
    {
        CheckBox message = (CheckBox)GridView1.Rows[i].FindControl("CheckBox2");

        if (message.Checked == true)
        {
            messageCheck = 1;

            SqlCommand cmd1 = new SqlCommand($"UPDATE reply SET replyCheck = {messageCheck} WHERE (id = {id})", sqlConnection);
            cmd1.ExecuteNonQuery();
        }
        else
        {
            messageCheck = 0;

            SqlCommand cmd2 = new SqlCommand($"UPDATE reply SET replyCheck = {messageCheck} WHERE (id = {id})", sqlConnection);

            cmd2.ExecuteNonQuery();
        }
    }

    sqlConnection.Close();
}

Without javascript, how could I do it?

Thanks for you all

2

Answers


  1. Kindly check with this code

    Protected Sub Button1_Click(sender As Object, e As EventArgs)
        For Each row In GridView1.Rows
            Dim chk As CheckBox = row.FindControl("CheckBox2")
            If chk.Checked Then
                'sql update query
            Else
            End If
        Next
    End Sub
    
    Login or Signup to reply.
  2. Ok, the way this works is that datafields (non templated columns) in the GV use the cells[] collection.

    However, for templated columns, we have to use find control.

    And also we will use the data keys feature, as that lets us have/use/work with the database PK row ID, but NOT have to display in the markup/grid for users.

    Ok, so here is a GV with both datafiles (the cells()), and also check box.

    We will select the check boxes, and then with a save button, send changes back to database.

    So, our markup:

       <div style="width:50%;padding:25px">
            <asp:GridView ID="GVHotels" runat="server" class="table borderhide" 
                AutoGenerateColumns="false" DataKeyNames="ID">
                <Columns>
                    <asp:BoundField DataField="FirstName"   HeaderText="FirstName"  />
                    <asp:BoundField DataField="LastName"    HeaderText="LastName"   />
                    <asp:BoundField DataField="City"        HeaderText="City"       />
                    <asp:BoundField DataField="HotelName"   HeaderText="HotelName" HeaderStyle-Width="200"   />
                    <asp:BoundField DataField="Description" HeaderText="Description" />
    
                    <asp:TemplateField HeaderText="Smoking"  ItemStyle-HorizontalAlign="Center"  >
                        <ItemTemplate>
                            <asp:CheckBox ID="chkSmoking" runat="server"
                                Checked='<%# Eval("Smoking") %>' />
                        </ItemTemplate>
                    </asp:TemplateField>
    
                    <asp:TemplateField HeaderText="Balcony"  ItemStyle-HorizontalAlign="Center"  >
                        <ItemTemplate>
                            <asp:CheckBox ID="chkBalcony" runat="server" 
                                Checked='<%# Eval("Balcony") %>' />
                        </ItemTemplate>
                    </asp:TemplateField>
    
                </Columns>
            </asp:GridView>
    
            <asp:Button ID="cmdSave" runat="server" Text="Save changes"  CssClass="btn"/>
        </div>
    

    And now our code to fill out above could be say this:

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
                LoadGrid();
        }
    
        void LoadGrid()
        {
            using (SqlConnection con = new SqlConnection(Properties.Settings.Default.TEST4))
            {
                using (SqlCommand cmdSQL = 
                    new SqlCommand("SELECT * from tblHotels ORDER BY HotelName ", con))
                {
                con.Open();
                GVHotels.DataSource = cmdSQL.ExecuteReader();
                GVHotels.DataBind();
                }
            }
        }
    

    And now we see this:

    enter image description here

    Now, there is two ways we can update the database. We could in fact update using a datatable, and in one whole shot upate the datbase.

    but, we just loop the GV, and execute updates. (if I have time, I’ll try and post the 2nd more cool approach).

    So, our button to update/save changes (for check boxes). Could be this:

       protected void cmdSave_Click(object sender, EventArgs e)
        {
            using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.TEST4))
            {
                conn.Open();
    
                string strSQL = "UPDATE tblHotels Set Smoking = @S, Balcony = @B " +
                                "WHERE ID = @ID";
                foreach (GridViewRow gRow in GVHotels.Rows)
                {
                    CheckBox cSmoke = (CheckBox)gRow.FindControl("chkSmoking");
                    CheckBox cBlacony = (CheckBox)gRow.FindControl("chkBalcony");
                    int PKID = (int)GVHotels.DataKeys[gRow.RowIndex]["ID"];
    
                    using (SqlCommand cmdSQL = new SqlCommand(strSQL, conn))
                    {
                        cmdSQL.Parameters.Add("@S", SqlDbType.Bit).Value = cSmoke.Checked;
                        cmdSQL.Parameters.Add("@B", SqlDbType.Bit).Value = cBlacony.Checked;
                        cmdSQL.Parameters.Add("@ID", SqlDbType.Int).Value = PKID;
                        cmdSQL.ExecuteNonQuery();
                    }
                }
            }
        }
    

    Note how we use row index to get the PK row ID. NOTE the DataKeys setting for the GV. This allows you to use/have/enjoy use of the database PK row ID (named "ID" in this code example), and NOT have to display/include the PK in the GV display.

    Note that you would continue to use cells() collection for NON templated columns. But for any templated column – you have to use FindControl on that row, pluck out the control, and then you can have at it in regards to that control value.

    We could also pull each GV row into a data table, and execute ONE datatable update into the database. But, as the above code shows – we actually keep the connection open for the update – and thus not a big deal either way.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search