我有一个带有 5 个模板列的 DataGrid,
但是,当我尝试将一些动态创建的控件添加到网格中时,它会失败,因为没有行。
- 我可以添加一个空白行并使用它吗?如何?- 或者其他方式?
我很确定您必须绑定到数据源。但是创建自己的DataTable
并用一些虚拟信息在其中插入一行是很容易的。
//pseudo code:
DataTable dt = new DataTable();
DataColumn dc = new DataColumn("column1");
dt.Columns.Add(dc);
DataRow dr = dt.NewRow();
dr["column1"] = "value1";
dt.Rows.AddNew(dr);
myDataGrid.DataSource = dt;
myDataGrid.DataBind();
如果您使用的是未绑定的 DataGridView,则可以创建新行,然后将它们添加到 DataGridView。您的问题涉及 DataGrid,但您将其标记为 DataGridView。
// Sample code to add a new row to an unbound DataGridView
DataGridViewRow YourNewRow = new DataGridViewRow();
YourNewRow.CreateCells(YourDataGridView);
YourNewRow.Cells[0].Value = "Some value";
YourNewRow.Cells[1].Value = "Another value";
YourDataGridView.Rows.Add(YourNewRow);