3
    private void dataGridView1_CellContentClick
    (object sender,DataGridViewCellEventArgs e) 
    {
        int i,j;
        i = dataGridView1.CurrentCell.RowIndex;
        j = dataGridView1.CurrentCell.ColumnIndex;
        txtcellvalue.Text = dataGridView1.Rows[i].Cells[j].Value.ToString(); 
    }

    private void Setvaluebutton_Click(object sender, EventArgs e)
    {
        int i = 0;
        //foreach(DataGridViewRow datagridviewrow in dataGridView1.Rows)
        //{
            i = dataGridView1.SelectedCells[0].RowIndex;
            string study = dataGridView1.Rows[i].Cells[2].Value.ToString(); 
            txtcellvalue.Text = dataGridView1.Rows[i].Cells[3].Value.ToString();
            txtcellvalue1.Text = dataGridView1.Rows[i].Cells[4].Value.ToString();
            string unit = dataGridView1.Rows[i].Cells[5].Value.ToString();
            i = i + 1;
            DialogResult dr = MessageBox.Show
            ("Would like to update the click yes!!",
             "values", MessageBoxButtons.YesNo);
            if (dr == DialogResult.Yes)
            {
                db.OpenDB();
                string query = "Update [table] set [status]=" + study + ",
                [limit]='" + txtcellvalue.Text + "' ,[limit2]='" + txtcellvalue1.Text
                 + "',[unit]='" + unit + "' where [tno]=" + i + ";";
                db.Update(query);
                DatagridviewMethod();
                db.CloseDB();

            }
            else
            {
                DatagridviewMethod();
            }
      // }                         

    }

在这里,我试图在datagridview中显示所有数据库表值。在datagridview中显示所有值后,尝试替换datagridview中的单元格值,我可以编辑和替换另一个值,但在更新时它只会更新一行值而不是所有其他行(所有选定的行)在 datagridview 中一次的值。请给我任何建议吗?

4

1 回答 1

4

如果我正确理解了您的代码,那么每当您运行该方法时,它只会在一行上执行,因为变量 [i] 永远不会更新。即使您选择了多行,它也会保持不变,因为 [i] 将始终指向您当前或“活动”行(在代码中的任何地方都不会更改)。要解决这个问题,请尝试遍历 SelectedRows 集合,例如

foreach (DataGridViewRow dgvrow in dataGridView1.SelectedRows) {
    string study = dgvrow.Cells[2].Value.ToString();
    txtcellvalue.Text = dgvrow.Cells[3].Value.ToString();
    txtcellvalue1.Text = dgvrow.Cells[4].Value.ToString();
    string unit = dgvrow.Cells[5].Value.ToString();

    if (MessageBox.Show("Would like to update the click yes!!",
        "values", MessageBoxButtons.YesNo) ==
        System.Windows.Forms.DialogResult.Yes) {
            // ETC...
    }
    else {  }
}
于 2012-09-28T19:26:19.750 回答