简体   繁体   中英

Update each selected datagridview rows

I'm using this code for updating each datagridview selected rows but unfortunately it update only my first selected row.Why?

foreach (DataGridViewRow item in this.dataGridView1.SelectedRows)
{
    con.Open();
    SqlCommand cmdo = new SqlCommand(@" update inventory set category = '"+textBox1.Text+"' WHERE id='" + dataGridView1.SelectedRows[0].Cells[0].Value.ToString() + "'", con);
    cmdo.ExecuteNonQuery();
    con.Close();
}

Problem is in using first element of datagrid ( not item ) as ID in each iteration

dataGridView1.SelectedRows[0].Cells[0]

You should try this code:

int i = 0;

foreach (DataGridViewRow item in this.dataGridView1.SelectedRows)
{
    con.Open();
    SqlCommand cmdo = new SqlCommand(@" update inventory set category = '"+textBox1.Text+"' WHERE id='" + dataGridView1.SelectedRows[i].Cells[0].Value.ToString() + "'", con);
    cmdo.ExecuteNonQuery();
    con.Close();
    i++;
}

You can try something like following

int rowIndex = 0;
foreach (DataGridViewRow row in this.dataGridView1.SelectedRows)
{
    con.Open();
SqlCommand cmdo = new SqlCommand(@" update inventory set category = '"+textBox1.Text+"' WHERE id='" + row[rowIndex].Cells[0].Value.ToString() + "'", con);
cmdo.ExecuteNonQuery();
con.Close();
    rowIndex = rowIndex + 1;
}

All you need is a row index so you can use to iterate through. Also off the topic, it's not recommended to open/close database connection in the loop, as it would cause performance issues for large data set. You could consider using Bulk update or stored procedure.

You are always selecting first row 'SelectedRows[0]' . You need to iterate through each row with help of for loop.

for(int i=0;i< dataGridView1.SelectedRows.Count;i++)
{
//iterate through each row
con.Open();
SqlCommand cmdo = new SqlCommand(@" update inventory set category = '"+textBox1.Text+"' WHERE id='" + dataGridView1.SelectedRows[i].Cells[0].Value.ToString() + "'", con);
cmdo.ExecuteNonQuery();
con.Close();
}

Please check this!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM