【问题标题】:How can I change the value of cells in a given column when selecting multiple rows?选择多行时如何更改给定列中单元格的值?
【发布时间】:2020-02-10 17:28:12
【问题描述】:

我希望能够在数据表中选择多行,然后如果它们被选中,请更改单元格中的值。 我的代码是:

private void btnSetToReceived_Click(object sender, EventArgs e)
{
    SetToReceived();
}

private void SetToReceived()
{
        this.dgvPod.CurrentCell.Value = "Yes";
}

private void dgvPod_KeyDown(object sender, KeyEventArgs e)
{
    e.Handled = true;
    dgvPod.BeginEdit(true);
    SetToReceived();
}

【问题讨论】:

标签: c# .net winforms datagridview


【解决方案1】:

我从您的问题中得到的是,您想要选择多个单元格然后开始输入,并且您希望所有选定的单元格值都会更改:

为此,您可以处理EditingControlShowing 事件并获取TextBox 编辑控件并处理其TextChanged 事件并更新选定单元格的文本。例如:

private void Form1_Load(object sender, EventArgs e)
{
    dataGridView1.ColumnCount = 4;
    dataGridView1.RowCount = 4;
    TextBox txt = null;
    dataGridView1.EditingControlShowing += (s1, e1) =>
    {
        if (dataGridView1.EditingControl is TextBox)
        {
            if (txt == null)
            {
                txt = (TextBox)dataGridView1.EditingControl;
                txt.TextChanged += (s2, e2) =>
                {
                    foreach (DataGridViewCell cell in dataGridView1.SelectedCells)
                        cell.Value = txt.Text;
                };
            }

        }
    };
}

代码不会检查所选单元格是否都在同一列中,但它在示例中显示了如何在键入的同时获取文本以及如何设置其他选定单元格的值。

【讨论】:

    猜你喜欢
    • 2020-11-14
    • 2011-10-30
    • 2020-02-17
    • 2020-07-17
    • 1970-01-01
    • 1970-01-01
    • 2020-02-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多