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

如何在C#中实现DataGridView的无限行添加功能

DataGridView 点击按钮添加文本框内容为新行的实现方案

推荐:绑定数据源方式(适合大量数据,性能更稳定)

  • 先定义一个实体类用来存储数据:
public class DataItem
{
    public string InputContent { get; set; }
    // 有其他字段的话直接加在这里
}
  • 在窗体类里声明全局数据源集合:
private List<DataItem> dataSource = new List<DataItem>();
  • 窗体初始化时完成数据源绑定:
// 假设你的DataGridView控件名为dataGridView1
dataGridView1.DataSource = new BindingSource(dataSource, null);
  • 按钮点击事件里实现添加逻辑:
private void btnAdd_Click(object sender, EventArgs e)
{
    // 先判断文本框内容不为空
    if (!string.IsNullOrWhiteSpace(txtInput.Text))
    {
        dataSource.Add(new DataItem { InputContent = txtInput.Text });
        // 刷新DataGridView显示
        ((BindingSource)dataGridView1.DataSource).ResetBindings(false);
        // 清空文本框方便下次输入
        txtInput.Clear();
    }
}

简易方案:直接添加行(适合少量数据,操作简单)

如果不想用数据源绑定,直接操作DataGridView的Rows集合:

private void btnAdd_Click(object sender, EventArgs e)
{
    if (!string.IsNullOrWhiteSpace(txtInput.Text))
    {
        // 单列的话直接传文本框内容;多列就按顺序传对应列的值,比如Rows.Add("值1", "值2")
        dataGridView1.Rows.Add(txtInput.Text);
        txtInput.Clear();
    }
}

注意事项

  • 添加前一定要判断文本框内容,避免插入空行
  • 大量数据添加时优先用绑定数据源的方式,频繁直接操作Rows会导致界面卡顿
  • 如果DataGridView设为ReadOnly,不影响添加行;要是用数据源绑定,AllowUserToAddRows可以设为false,避免用户手动添加空行

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 22:45:37