单击“设置”按钮不会更新datagridview中的所有多个选定单元格值

时间:2012-09-24 05:31:32

标签: c# winforms

    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中一次只有一个行值而不是所有其他行(所有选定的行)值。 请给我任何建议吗?

1 个答案:

答案 0 :(得分:3)

如果我正确理解你的代码,每当你运行该方法时,它只在一行上执行,因为变量[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 {  }
}