如何使用C#编程向DataGrid添加行?

7

如题所述,我正在尝试使用C#编写程序来动态添加DataGrid行,但似乎无法使其正常工作。以下是目前的代码:

// I have a DataGrid declared as dg in the XAML

foreach (string s in array) {
    int index = 0;
    DataGridRow dgRow = new DataGridRow();
    foreach (DataGridColumn dgColumn in columns)
    {
        // Trying to add Text to dgRow here but IDK how
        index++;
    }
}

我一直在谷歌上搜索,最接近的添加内容的方法是使用{column = value},但是它会抛出错误。现在真的没有任何想法了:\


使用DataGridView的最佳方式是将其绑定到一个数据源(如DataTable、DataSet等),并在数据源本身中进行更改。另外,在您的代码中,您必须在DataGridView中添加dgRow以使其在用户界面上可见。 - Rohit Prakash
我该如何将它与 DataTable “绑定”? - Lorenzo Ang
3个回答

5
这里有一个更好的方法,可以通过将源绑定到DataGridView来实现。
        // Creating DataSource here as datatable having two columns
        DataTable dt = new DataTable();
        dt.Columns.Add("ID", typeof(int));
        dt.Columns.Add("Name");

        // Adding the rows in datatable
        for (int iCount = 1; iCount < 6; iCount++)
        {
            var row = dt.NewRow();
            row["ID"] = iCount;
            row["Name"] = "Name " + iCount;
            dt.Rows.AddRow(row);
        }

        DataGridView dgv = new DataGridView();
        // Set AutoGenerateColumns true to generate columns as per datasource.
        dgv.AutoGenerateColumns = true;
        // Finally bind the datasource to datagridview.
        dgv.DataSource = dt;

如果您正在使用WPF DataGrid,可以像这样绑定它:

dgv.DataContext = employeeData.DefaultView;

在IT技术中,XAML是一种用于定义用户界面的标记语言。

<DataGrid Name="dgv" ItemsSource="{Binding}">

嗨,Rohit!有没有办法让它与“DataGrid”一起工作?在我的C#版本中好像没有DataGridView可用。 - Lorenzo Ang
嗨,Rohit,我刚意识到在WPF中没有DataGridView。我正在使用WPF。有没有办法让它在WPF中工作? - Lorenzo Ang
不是的。我刚试了一下,它甚至都无法编译:\ - Lorenzo Ang
结果证明,我在让你的代码运行时缺少的东西就是 ItemsSource="{Binding}" 哈哈哈 :| 非常感谢!!我已经为此疯狂了一段时间了。 - Lorenzo Ang
很高兴它能帮到你。. .. . - Rohit Prakash
你不需要添加行吗?NewRow默认不会添加,MSDN上说:row = table.NewRow(); row["id"] = i; table.Rows.Add(row); 另外,你不应该将它绑定到ItemSource吗? - MushyPeas

2
//create datatable and columns,
DataTable dtable = new DataTable();
dtable.Columns.Add(new DataColumn("Column 1"));
dtable.Columns.Add(new DataColumn("Column 2"));

//simple way create object for rowvalues here i have given only 2 add as per your requirement
object[] RowValues = { "", "" };

//assign values into row object
RowValues[0] = "your value 1";
RowValues[1] = "your value 2";

//create new data row
DataRow dRow;
dRow = dtable.Rows.Add(RowValues);
dtable.AcceptChanges();

//now bind datatable to gridview... 
gridview.datasource=dbtable;
gridview.databind();

敬礼


-1

你试过了吗?:

int n=5; // number of rows you want to add
dataGridView1.Rows.Add(n);

// you can add (names of the rows) if you have them in your array
//for(int i=0; i<n; i++)
//dataGridView1[0, i].Value = array[i];

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接