C# 您可以将数据添加到没有数据源的数据网格吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/269354/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Can you add data to a datagrid with no data source?
提问by
I have a DataGrid with 5 template columns,
我有一个带有 5 个模板列的 DataGrid,
However when I try and add some dynamically created controls into the grid, it fails, as there are no rows.
但是,当我尝试将一些动态创建的控件添加到网格中时,它失败了,因为没有行。
-Can i add a blank row in and use that? and how? -Or any other way?
- 我可以添加一个空白行并使用它吗?如何?- 或者其他方式?
采纳答案by Kon
I'm pretty sure you have to bind to a data source. But it's easy enough to create your own DataTable
and insert a row into it with some dummy info.
我很确定您必须绑定到数据源。但是很容易创建自己的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();
回答by Chris Miller
If you are using an unbound DataGridView, you can create new rows and then add them to DataGridView. Your question referred to DataGrid, but you tagged it for DataGridView.
如果您使用的是未绑定的 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);