Insert data from a DataGridView to SQL in c #, Visual Studio

0

I am making an application that records the daily information of what was done on a farm during the day.
The grid shows something like that.

Where I have to enter information from the data grid to the database. But the size of the rows varies if I change the farm's combo box. As shown in the picture.

The question would be, how do I enter data from a grid into SQL?

NOTE: Batch names are test effects

    
asked by Luis Duarte 19.09.2018 в 21:41
source

1 answer

0

You'll have to iterate the rows of the grid doing the INSERT in the table, something like this structure

using (SqlConnection conn = new SqlConnection("<connection string>")) { 
    conn.Open(); 

    string query = "INSERT INTO NombreTabla (campo1, campo2) VALUES (@aram1, @param2)"; 
    SqlCommand cmd = new SqlCommand(query, conn); 


    foreach (DataGridViewRow row in dataGridView1.Rows) { 
        cmd.Parameters.Clear(); 

        cmd.Parameters.AddWithValue("@param1", Convert.ToString(row.Cells["nombreCol1"].Value)); 
        cmd.Parameters.AddWithValue("@param2", Convert.ToInt32(row.Cells["nombrecol2"].Value)); 

        cmd.ExecuteNonQuery(); 
    } 
}

As you will see each iteration of the loop you assign parameters to the insert taking these from the rows of the grid

    
answered by 19.09.2018 / 22:07
source