pancake
pancake

Reputation: 600

Insert multiple checked values from gridview into Database

I have this methode to loop through if the data in my gridview is checked or not, if they are checked they should be inserted into the database. As you can see the only data I want to insert from the gridview is the text from cell[2] in the gridview and it's in the name of @HeaderName

        using (SqlConnection con = new SqlConnection("my con string"))
        {
            con.Open();
            foreach (GridViewRow row in GridViewConsNames.Rows)
            {
                CheckBox myCheckBox = row.FindControl("myCheckBox") as CheckBox;
                if (myCheckBox.Checked)
                {
                    using (SqlCommand cmd = new SqlCommand("INSERT INTO Accounting_Consolidation_ServiceOutputs(Cusomer_Name, Service_Name, Header_Name, Sort_Postion, Rename_to, Value) Values(@CustName,@ServiceName,@HeaderName,@Sort,@Rename,@Value)", con))
                    {
                        //cmd.Parameters.AddWithValue("PersonId", Convert.ToInt32(GridViewConsNames.DataKeys[row.RowIndex].Value));
                        cmd.Parameters.AddWithValue("@CustName", TextBoxCustName.Text);
                        cmd.Parameters.AddWithValue("@ServiceName", DropDownListServicesAvailable2.SelectedItem.Text);
                        cmd.Parameters.AddWithValue("@HeaderName", "Name of the checked cells from my gridview");
                        cmd.Parameters.AddWithValue("@Sort", null);
                        cmd.Parameters.AddWithValue("@Rename", "");
                        cmd.Parameters.AddWithValue("@Value", null);
                        cmd.ExecuteNonQuery();
                    }
                }
            }
        }

I have tried with this

 GridViewRow row = GridViewConsNames.SelectedRow; 
 string headername = row.Cells[2].Text;

But this seems not working

Upvotes: 0

Views: 3347

Answers (1)

Tim Schmelter
Tim Schmelter

Reputation: 460028

Why do you use GridViewRow row = GridViewConsNames.SelectedRow when you actually want to use all rows where the checkbox is selected?

So i guess that this is what you want:

foreach (GridViewRow row in GridViewConsNames.Rows)
{
    CheckBox myCheckBox = row.FindControl("myCheckBox") as CheckBox;
    if (myCheckBox.Checked)
    {
        // ...
            string headerName = row.Cells[2].Text;
            cmd.Parameters.AddWithValue("@HeaderName", headerName);
        // ...
    } 
}

Upvotes: 1

Related Questions