从DataGrid Winforms C#获取textBox单元格值

时间:2018-11-06 06:45:18

标签: c# winforms datagridview

我在DataGrid(由“编辑列”创建)内有一个按钮,与TextBox相同。我已经在按钮上创建了CellClick事件。现在,我想要TextBox值,该值将由用户输入。

我如何得到它?

我尝试过

private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
    if (e.ColumnIndex == 0)
    {
        //Here i will get cell value which bind from database
        dataGridView1.Rows[e.RowIndex].Cells[1].Value.ToString();
    }
}

2 个答案:

答案 0 :(得分:1)

尝试

表单加载:

private void Form1_Load(object sender, EventArgs e)
        {

            dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;

        }

CellClick事件:

 private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            DataGridViewRow row = new DataGridViewRow();
            row = dataGridView1.SelectedRows[0];
            if (row.Cells[0].Value!=null && row.Cells[1].Value != null && row.Cells[2].Value != null) {
                textBox1.Text = row.Cells[0].Value.ToString();
                textBox2.Text = row.Cells[1].Value.ToString();
                textBox3.Text = row.Cells[2].Value.ToString();
            }
        }

enter image description here

答案 1 :(得分:0)

我已经使用了CellContentClick,它运行良好。我还添加了一个带值的字符串变量。这是我的代码:

private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
    if (e.ColumnIndex == 0)
        {
            string value = dataGridView1.Rows[e.RowIndex].Cells[1].Value.ToString();
            MessageBox.Show(value);
        }
}
相关问题