【问题标题】:Add new empty row to dataGridView bound to DataSet将新的空行添加到绑定到 DataSet 的 dataGridView
【发布时间】:2014-01-02 10:59:42
【问题描述】:

我不擅长这个。我有一个由数据集绑定到 SQL 的 dataGridView。所有列都由数据集生成,除了一列被编码的一列替换,它是一个组合框列。 为了避免在编辑行时生成新列,我将 allowUserToAddRows 设置为 false。现在我想通过按钮单击添加新的空行。我已经尝试了几种方法,但都没有成功。 已更新完整代码

 public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        this.affitto_saTableAdapter.Fill(this.affitto_SADataSet.affitto_sa);
        DataGridViewComboBoxColumn comboCol1 = new DataGridViewComboBoxColumn();
        comboCol1.Name = "Periodo Rif.";
        List<DateTime> periods = new List<DateTime>() { DateTime.Now.AddMonths(-2), DateTime.Now.AddMonths(-1), DateTime.Now, DateTime.Now.AddMonths(1), DateTime.Now.AddMonths(2) };
        //Dates = Dates.OrderBy(x => x).ToList();
        List<string> colSource = periods.Select(x => x.ToString("MMM/yyyy")).ToList();
        comboCol1.DataSource = colSource;
        dataGridView1.Columns.Add(comboCol1);
        comboCol1.DataPropertyName = "Periodo";
        dataGridView1.Columns["Periodo Rif."].DisplayIndex = 1;
    }

    private void button1_Click(object sender, EventArgs e)
    {
       /* DataTable dt = dataGridView1.DataSource as DataTable;
        DataRow row = dt.NewRow();
        dt.Rows.Add(row);*/

        (dataGridView1.DataSource as DataTable).Rows.Add((dataGridView1.DataSource as DataTable).NewRow());

    }
}

如何向此类 DGV 添加新的空行?

【问题讨论】:

  • 这段代码应该可以工作。你能解释一下出了什么问题吗? PS:请记住,组合框列的空白行表示组合框(以-1为selectedindex,即没有选择任何项目)。
  • @varocarbas,使用上面的代码我得到一个空引用异常,我不明白为什么。
  • 我已经尝试了您的代码(通过向 DataGridView 添加适当的数据源,您发布的内容中不存在什么),一切都很好。你能包括你设置数据源的部分吗?
  • @varocarbas我用我在这个应用程序中的完整代码更新了这个问题。
  • as DataTable 期望 DataTableDataSource,如果不是这种情况,您将转换为错误的类型。也许您更喜欢在运行时设置DataSource(使用DataTable)。不要从设计视图中填充任何内容,创建一个DataTable (dt) 变量并从您想要的源(数据库,我理解)填充它,编写DataGridView1.DataSource = dt,您的代码就可以工作了。

标签: c# datagridview


【解决方案1】:

这里解决您的问题:

dataGridView1.Rows.AddCopy(myDataGridView1.Rows.Count - 1);

由于您的 DGV 未与任何数据源绑定,因此 AddCopyDataGridViewRow 将在 DGV 末尾添加新行(Rows.Count - 1)。

【讨论】:

  • 我得到一个空引用异常,我不明白为什么!
  • @FeliceM 如果 DGV 绑定了数据源,那么这是不可能的!检查 DGV 是否有 dataSource 作为 DataTable
  • 正如我所说的,这不是很方便。我已经用表单中的所有代码更新了问题。
  • @FeliceM 我认为这里 DGV 没有与任何 DataSource 绑定,在这种情况下,编辑后的答案将起作用。
【解决方案2】:
 private void button1_Click(object sender, EventArgs e)

    {

        this.dataGridView1.Rows.Add();

    }

【讨论】:

  • 请避免仅使用代码的答案 - 为 snipes 添加一些解释。
  • 另外,在这个问题的上下文中,这个答案不起作用。您将收到以下异常:“当控件绑定数据时,无法以编程方式将行添加到 DataGridView 的行集合中。”
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-13
  • 1970-01-01
  • 2011-09-17
相关资源
最近更新 更多