正如标题所述,我正在尝试使用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}
,但它只是抛出一个错误。现在真的没有想法:\
答案 0 :(得分: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;
并在
XAML
<DataGrid Name="dgv" ItemsSource="{Binding}">
答案 1 :(得分: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();
此致
答案 2 :(得分:-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];