2

当我在行中单击时,dataGridView我喜欢用该行中的数据填充文本框?我怎样才能做到这一点 ?

示例 ID、姓名、姓氏 ... 现在在 TextBox 中显示

dataGridView(例如ID=1, Name=s...)中的此数据显示在TextboxUp ??

4

3 回答 3

8

您必须实现SelectionChanged您的事件DataGridView,然后检查选择了哪一行。

private void dataGridView_SelectionChanged(object sender, EventArgs e)
{
    DataGridViewCell cell = null;
    foreach (DataGridViewCell selectedCell in dataGridView.SelectedCells)
    {
        cell = selectedCell;
        break;
    }
    if (cell != null)
    {
        DataGridViewRow row = cell.OwningRow;
        idTextBox.Text = row.Cells["ID"].Value.ToString();
        nameTextBox.Text = row.Cells["Name"].Value.ToString();
        // etc.
    }
}
于 2013-03-14T10:30:04.207 回答
3

注册网格的 MouseClick 事件并使用以下代码。

private void dataGridView1_MouseClick(object sender, MouseEventArgs e)
{
    DataGridViewRow dr = dataGridView1.SelectedRows[0];
    textBox1.Text = dr.Cells[0].Value.ToString();
     // or simply use column name instead of index
    //dr.Cells["id"].Value.ToString();
    textBox2.Text = dr.Cells[1].Value.ToString();
    textBox3.Text = dr.Cells[2].Value.ToString();
    textBox4.Text = dr.Cells[3].Value.ToString();
}

并在您的加载事件中添加以下行

dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
于 2013-06-12T18:47:23.270 回答
0
private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
    //it checks if the row index of the cell is greater than or equal to zero
    if (e.RowIndex >= 0)
    {
        //gets a collection that contains all the rows
        DataGridViewRow row = this.dataGridView1.Rows[e.RowIndex];
        //populate the textbox from specific value of the coordinates of column and row.
        txtid.Text = row.Cells[0].Value.ToString();
        txtname.Text = row.Cells[1].Value.ToString();
        txtsurname.Text = row.Cells[2].Value.ToString();
        txtcity.Text = row.Cells[3].Value.ToString();
        txtmobile.Text = row.Cells[4].Value.ToString();

    }

}
于 2017-03-14T17:09:29.727 回答