mardi 10 mai 2016

C# asp.net - Update specific row on SQL Server

I currently have an asp.net gridview with a checkbox column and button. I am trying to update the database table where the checkbox has been checked.

My SQL table has the following fields

row_id(int), MagazineCode(varchar), Dimensions(varchar) and Obselete(int).

WEBFORM.aspx

 <div id="effortGridHolder" style="width: 888px; height: 270px; overflow: auto;">
        <asp:GridView ID="GridView1" runat="server" DataSourceID="SqlDataSource1"
            AutoGenerateColumns="False" AlternatingRowStyle-CssClass="alt"
            OnSelectedIndexChanged="GridView1_SelectedIndexChanged" CellPadding="4"
            ForeColor="#333333" GridLines="None" Width="100%"
            DataKeyNames="MagazineCode" >

            <Columns>

                <asp:BoundField DataField="MagazineCode"
                    HeaderText="MagazineCode" SortExpression="MagazineCode" />

                <asp:BoundField DataField="Profile_ID"
                    HeaderText="Profile_ID" SortExpression="Profile_ID" />

                <asp:BoundField DataField="Dimensions"
                    HeaderText="Dimensions" SortExpression="Dimensions" />

    <asp:templatefield HeaderText="Obselete">
    <itemtemplate>
    <asp:checkbox ID="cbSelect"    runat="server"></asp:checkbox>
    </itemtemplate>
    </asp:templatefield>
            </Columns> 

<asp:Button ID="obselete_btn" OnClick="obselete_submit" runat="server" Text="Update" />

The C# code

 protected void obselete_submit(object sender, EventArgs e)
    {
    //GET CHECKED VALUES
    foreach(GridViewRow row in GridView1.Rows)
    {
        if(row.RowType == DataControlRowType.DataRow)
        {
            CheckBox chkRow = (row.Cells[2].FindControl("cbSelect") as CheckBox);
            if (chkRow.Checked)
            {
                //update 
                SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ApplicationData"].ConnectionString);
                SqlCommand cmd = conn.CreateCommand();
                cmd.CommandText = "UPDATE table SET Obselete = '1' WHERE MagazineCode = '" + tbMagCode_GAD.Value + "'";
                conn.Open();
                cmd.ExecuteNonQuery();
                conn.Close();
            }

At the moment I am able to get the checked values from checkboxes and when the update button is pressed, it is able to update the Obselete and set it to 1.

The current SQL query for this is:

 "UPDATE table SET Obselete = '1' WHERE MagazineCode = '" + tbMagCode_GAD.Value + "'";

But this isnt great as the database table can have the same MagazineCode and will update the Obselete field for all of them. I have created a new field called row_id and want update the table where row_id = "gridview row clicked"

Thanks

Aucun commentaire:

Enregistrer un commentaire