[英]Rows cannot be programmatically added to the DataGridView's rows collection when the control is data-bound
[英]Rows cannot be added programmatically in the DataGridView when the control data-bound
在我的 DatagridView 中已經有數據,然后我想在 Windows 窗體中單擊添加按鈕時添加新行我得到“當在控件數據綁定中時,行無法以編程方式添加到 datagridview 行集合。
然后我谷歌它我得到了一些答案,比如你可以使用 DataTable 添加一個新行,下面是我使用的代碼
然后,我試着跑,
在我的數據網格中顯示添加的行,但所有行的值都為空值,如空行
請告訴我我錯在哪里我是 Windows 應用程序 datagridview 的新手,使用 c#
DataTable dataTable=new DataTable();
foreach (DataGridViewColumn col in dataGridView.Columns)
{
dataTable.Column.add(col.Name);
}
foreach (dataGridViewRow row in dataGridView.Rows)
{
DataRow drow=dataTable.NewRow();
foreach (DataGridViewCell cell in row.cells)
{
drow[cell.ColumnIndes]=cell.value;
dataTable.Rows.add(drow);
}
}
//then,
//i assigned dataTable values to dataGridView
dataGridView.DataSource=dataTable;
}
我不明白你為什么要做所有這些事情。 您說您的 dataGridView 中有數據,這意味着您已經設置了 dataGridView 的標題,並且您只想在單擊按鈕時添加新行。 如果我的看法是正確的,那么您只需對按鈕單擊事件執行以下操作即可。
dataGridView1.Rows.Add("Column1", "Column2",..);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.