0

Hi,
I have taken checkboxes in datagridview....i want to insert the values of field checked into the databse......anybody can help??????????

2
Contributors
1
Reply
3
Views
4 Years
Discussion Span
Last Post by Mitja Bonca
0

Do the loop through the rows of dgv and check if row is selected:

   using(SqlConnection conn = new SqlConnection("connString"))
   {     
       foreach (DataGridViewRow dr in dataGridView2.Rows)
       {    
           DataGridViewCheckBoxCell check = row.Cells[0] as DataGridViewCheckBoxCell;
           if(check != null && (bool)check.Value) //1st parameter must not be null, 2nd parameter must me true!
           {
               string query = @"UPDATE TableName SET FieldName2 = @param1 WHERE FieldName1 = @param2"; //query
               using(SqlCommand cmd = new SqlCommand(query, conn))
               {
                   cmd.Parameters.Add("@param1", SqlDbType.VarChar, 50).Value = row.Cells["ColumnName2"].Value.ToString(); //set appropriate column name or its index
                   cmd.Parameters.Add("@param2", SqlDbType.Int).Value = int.Parse(row.Cells["ColumnName1"].Value.ToString()); //same here!! - this is some id (unique) column
                   try
                   {
                       if(conn.State != ConnectionState.Open)
                           conn.Open();
                       cmd.ExecuteNonQuery();
                   }
                   catch(Exception ex)
                   {
                       MessageBox.Show(ex.Message);
                       break; //go out of the loop when 1st error occurs! - you can remove it
                   }
               }
           }
       }
   }  
This article has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.