因此,正如标题所述,我正在尝试使用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来做的更好的方法
// 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;
和在
XAML
<DataGrid Name="dgv" ItemsSource="{Binding}">
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句