c# - 不通过单击设置按钮来更新 datagridview 中的所有多个选定单元格值

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

最佳答案

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

关于c# - 不通过单击设置按钮来更新 datagridview 中的所有多个选定单元格值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12559330/

相关文章:

c# - 如何在 C# WinForms 中的 Label 上编写二次方程?

c# - 如何从 C# 中的列表框索引中检索文本值

c# - WPF:剪切并保存图像

c# - 当参数之一为 void* 时,如何在 C# 中使用 C 函数?

c# - 当屏幕分辨率更改面板及其在 WinForm 中的子控件显示时

c# - 使用 C# 在 RichTextBox 中为单词绘制下划线

c++ - Windows 窗体可视化。如何使常量。更新字段?

c# - 集中或合并 LINQ 选择

C#:选择具有包含子字符串的属性的节点的 XPath?

c# - 用 .NET 实现替换 C++ ActiveX 组件?