【问题标题】:adding new row to the bottom of datagridview在datagridview的底部添加新行
【发布时间】:2015-08-13 14:12:00
【问题描述】:

我的表单上有一个包含一列和一条记录的 datagridview,我想通过单击按钮将新行添加到 datagridview 的底部,并用 Rows.Count 数字填充最后一个单元格。但似乎当使用dataGridView1.Rows.Add() 方法添加新行时,它会插入到当前行的顶部。如何在 datagridview 底部插入一行?这是预期的行为吗?

谢谢。

private void button1_Click(object sender, EventArgs e)
 {

    dataGridView1.Rows[dataGridView1.Rows.Count-1].Cells[0].Value = dataGridView1.Rows.Count;
    dataGridView1.Rows.Add();

}

【问题讨论】:

  • 我刚刚使用了dataGridView1.Rows.Insert(dataGridView1.Rows.Count - 1, 1),但该行已添加到顶部。如果我错了,请纠正我?
  • 您使用的是哪种技术? WPF,Windows 窗体?数据网格是否绑定了某些东西?
  • 它是简单的Windows窗体。数据网格未绑定。
  • 我刚试过你的代码(没有dataGridView1.Rows.Add.Add()),我的代码被插入到底部。可能您的 DataGridView 是按某个列排序的。

标签: c# datagridview


【解决方案1】:

虽然问题可能是duplicate,但针对该问题提供的答案还不够充分。你会明白为什么。

您的操作理念是 dataGridView1.Rows.Add(); 在“当前行的顶部添加一个新行。”情况并非如此。使用您当前的设置,设计器中默认设置以下内容:

this.dataGridView1.AllowUserToAddRows = true;

这将导致网格的底部(未提交)行,由 * 符号表示。这是 NewRow,在代码中通过this.dataGridView1.NewRowIndex 访问表示。每当您编辑此行时,它都会被提交并添加另一个 NewRow

为什么这很重要?因为当您将此属性设置为 true 时,调用 dataGridView1.Rows.Add() 会在您的 commited 行的底部,在 NewRow 之前添加一个新行。例如:

private void button1_Click(object sender, EventArgs e)
{
    dataGridView1.Rows[dataGridView1.Rows.Count-1].Cells[0].Value = dataGridView1.Rows.Count;
    dataGridView1.Rows.Add(new object[] { "I'm new" });   
}

建议的答案:dataGridView1.Rows.Insert(dataGridView1.Rows.Count - 1, 1) 会做同样的事情。因此,为什么它不是一个解决方案。

解决方案

交换两行代码的顺序。

private void button1_Click(object sender, EventArgs e)
{
    dataGridView1.Rows.Add();
    dataGridView1.Rows[dataGridView1.Rows.Count-1].Cells[0].Value = dataGridView1.Rows.Count;   
}

【讨论】:

    【解决方案2】:

    试试这个:

    private void button1_Click(object sender, EventArgs e)
    {
        object[] rowData = new object[dataGridView1.Columns.Count];
        rowData[0] = dataGridView1.Rows.Count;
        dataGridView1.Rows.Add(rowData);          
    }
    

    【讨论】:

      【解决方案3】:

      在行中编写代码添加按钮单击事件,如下所示

      private void btnRowAdd_Click(object sender, EventArgs e)
      {
          String[] row = { "", "", "", "", "", "", "" };
          dataGridView1.Rows.Add(row);
          dataGridView1.AllowUserToAddRows = false;
      }
      

      这是行添加按钮:

      然后还在新按钮中调用该事件,如下所示:

      btnRowAdd_Click(e, e);
      

      【讨论】:

        【解决方案4】:

        我找到了答案。我调用这个方法在我的 DataGridView 底部添加一个新行。

        this.dataGridView1.NotifyCurrentCellDirty(true);

        enter image description here

        【讨论】:

        • 欢迎来到 Stack Overflow。请澄清你的问题。见How to Ask
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-01-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-02-01
        • 2013-02-04
        相关资源
        最近更新 更多