You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#实现点击DataGridView整行后将数据库数据填充至文本框

在C# WinForm中实现点击DataGridView整行填充文本框

1. 配置DataGridView并绑定事件

首先确保DataGridView的选中模式为整行选中,然后绑定合适的触发事件(推荐RowEnter或SelectionChanged,前者在选中行切换时触发,逻辑更直接):

// 在窗体构造函数或Load事件中初始化
private void Form1_Load(object sender, EventArgs e)
{
    // 设置整行选中,禁止多选
    dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
    dataGridView1.MultiSelect = false;
    // 绑定行选中事件
    dataGridView1.RowEnter += DataGridView1_RowEnter;
}

2. 实现数据填充逻辑

根据DataGridView的数据源类型,选择两种常见的取值方式:

方式一:直接从DataGridView行单元格取值

适用于未绑定数据源或需要直接操作UI控件的场景:

private void DataGridView1_RowEnter(object sender, DataGridViewCellEventArgs e)
{
    // 排除表头行,确保行索引有效
    if (e.RowIndex >= 0)
    {
        DataGridViewRow selectedRow = dataGridView1.Rows[e.RowIndex];
        // 将单元格值赋值给对应文本框,空值处理避免报错
        txtId.Text = selectedRow.Cells["Id"].Value?.ToString() ?? string.Empty;
        txtUsername.Text = selectedRow.Cells["Username"].Value?.ToString() ?? string.Empty;
        txtEmail.Text = selectedRow.Cells["Email"].Value?.ToString() ?? string.Empty;
    }
}

方式二:从绑定的数据源(如DataTable)取值

如果DataGridView已绑定DataTable,直接从数据源取值更高效:

private void DataGridView1_RowEnter(object sender, DataGridViewCellEventArgs e)
{
    if (e.RowIndex >= 0)
    {
        DataTable dataTable = dataGridView1.DataSource as DataTable;
        if (dataTable != null)
        {
            DataRow row = dataTable.Rows[e.RowIndex];
            txtId.Text = row["Id"].ToString();
            txtUsername.Text = row["Username"].ToString();
            txtEmail.Text = row["Email"].ToString();
        }
    }
}

3. 关键注意事项

  • 确保DataGridView的列名/索引与文本框要填充的数据对应一致;
  • 使用?.ToString() ?? string.Empty处理空值,避免NullReferenceException;
  • 若需响应行头点击,可替换为RowHeaderMouseClick事件,逻辑与上述一致。

内容的提问来源于stack exchange,提问作者dkkunp

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 19:25:10