【问题标题】:How to add row in datagridview with pre-data in c# winform?如何在 c# winform 中使用预数据在 datagridview 中添加行?
【发布时间】:2015-01-03 18:26:15
【问题描述】:

我有一个数据网格视图,其中包含来自 SQL 的数据。我在每列下添加了 2 个数据,所以如果我以这种形式查看它会是这样的..

代码是自动递增的

Code   --    Date     --     Total_Score

1         1/3/2015            20

2         1/3/2015            30

现在我想添加一个新行..如果我单击按钮,它应该添加一个带有详细信息“3”的新行(代码是从我的数据库中自动递增的),2015 年 1 月 3 日(日期应该是当前日期时间) 并且 total_score 单元格应该为空,以便我可以输入数据。但是它只显示了一个新添加的空白行,我无法在上面输入任何内容.. 这是我当前的代码..

    private void btnaddcomp_Click(object sender, EventArgs e)
    {
        DataTable ds = (DataTable)dgsetcompt.DataSource;
        int index = this.dgsetcompt.Rows.Count;
        DataRow dr = ds.NewRow();
        ds.Rows.InsertAt(dr, index + 1);

        dgsetcompt.DataSource = ds;
    }

【问题讨论】:

标签: c# winforms datagridview


【解决方案1】:

您应该以这种方式简单地将数据添加到您的行中

private void btnaddcomp_Click(object sender, EventArgs e)
{
    DataTable ds = (DataTable)dgsetcompt.DataSource;

    // Create a new row...
    DataRow dr = ds.NewRow();

    // Set the two fields
    dr["code"] = this.dgsetcompt.Rows.Count + 1;
    dr["date"] = new DateTime(2015, 1, 3);

    // Add the newly created row to the Rows collection of the datatable
    ds.Rows.Add(dr);

    // Not needed
    //dgsetcompt.DataSource = ds;
}

【讨论】:

  • 这很奇怪。我已经在像您这样的场景中对其进行了测试,并且新行按预期出现。您能否在初始化表的位置添加代码并添加前两行并将其绑定到 DataGridView?
  • 我已经编辑了我的问题并在那里添加了代码......我已经被困了一个小时。
  • 对不起,我在上面的代码中找不到任何错误。尝试查看 DataGridView 中从默认值更改的属性。
  • 哇终于修好了!你是对的,问题出在我的 DataGridView 的属性上,哈哈!傻我xD
  • 如果您告诉我们导致此行为的属性是什么,它将对本 QA 的未来读者有用
猜你喜欢
  • 2016-05-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-06
  • 1970-01-01
相关资源
最近更新 更多