如何使用c#winform中的前置数据在datagridview中添加行?

时间:2015-01-03 18:26:16

标签: c# winforms datagridview

我有一个带有SQL数据的datagridview。我在每列下添加了2个数据,所以如果我在表单中查看它就会像这样......

代码自动增量

Code   --    Date     --     Total_Score

1         1/3/2015            20

2         1/3/2015            30

现在我要添加一个新行..如果我点击按钮,它应该添加一个新行,其中包含详细信息' 3'(代码是从我的数据库自动增加的),2015年1月3日( date应该是当前日期时间,而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;
    }

1 个答案:

答案 0 :(得分:0)

您只需以这种方式向行中添加数据

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;
}
相关问题