【问题标题】:C#, How to insert a TextBox value into DataGridView current cell (Marked one)?C#,如何将 TextBox 值插入 DataGridView 当前单元格(标记为一个)?
【发布时间】:2018-06-20 07:27:30
【问题描述】:

我编写了一个代码来获取 DGV 当前单元格的值(标记为一个 - DGV 内的一个单元格,已由用户单击鼠标选择)。现在我想知道如何执行 SET 代码(将 TextBox 的值插入当前单元格)。 此代码 (GET) 工作正常:

        private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
        {
        textBxGET.Text = dataGridView1.CurrentCell.Value.ToString();
        }

问题出在此代码(SET)显示行号(不是我想要的):

        private void button1_Click(object sender, EventArgs e)
        {
        dataGridView1.CurrentCell.Value = textBoxSET.Text;
        }

【问题讨论】:

  • 不起作用不是一个有用的问题描述! - 你的代码工作得很好!也许 dataGridView1.CurrentCell 无效? - 另外:您应该始终正确标记您的问题,以便人们可以在问题页面上看到它!
  • GET 代码正常,SET 代码有问题。
  • 嗯?我刚刚告诉过你它工作得很好!你的问题一定出在其他地方。活动连上了吗??
  • 这里没有问题。它必须在您的代码中的其他地方!使用调试器!是否进入点击事件??
  • 如果它显示的是行号......它会是零 (0) 而不是 1。

标签: c# winforms datagridview


【解决方案1】:
    private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
    {
        txtselectedcellvalue.Text = dataGridView1.CurrentCell.Value.ToString();
        //txtselectedcellvalue.Text = dataGridView1.Rows[dataGridView1.CurrentRow.Index].Cells[dataGridView1.CurrentCell.ColumnIndex].Value.ToString();
    }

    private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
    {
        if(dataGridView1.SelectedCells.Count > 0)
            txtselectedcellvalue.Text = dataGridView1.CurrentCell.Value.ToString();
          //txtselectedcellvalue.Text = dataGridView1.Rows[dataGridView1.CurrentRow.Index].Cells[dataGridView1.CurrentCell.ColumnIndex].Value;
    }

    private void btnchange_Click(object sender, EventArgs e)
    {
        dataGridView1.CurrentCell.Value = txtvaluechange.Text;
        //dataGridView1.Rows[dataGridView1.CurrentRow.Index].Cells[dataGridView1.CurrentCell.ColumnIndex].Value = txtvaluechange.Text;
    }

这段代码对我来说很好用。此外,@Kaj 的代码完美无缺。请以适当的方式解释您的错误。

【讨论】:

    【解决方案2】:

    试试这个:

    dataGridView1.Rows[dataGridView1.CurrentRow.Index]
                       .Cells[dataGridView1.CurrentCell.ColumnIndex].Value = textBoxSET.Text;
    

    【讨论】:

    • 同样的问题,它给了我行序号。
    • 这应该和OP完全一样。
    • @TaW 指定行和列索引可能有效!但似乎由于某种原因它没有!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-06-20
    • 2010-10-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-30
    • 1970-01-01
    相关资源
    最近更新 更多