如何在datagridview中添加绑定到数据源的New Row

Ami*_*mar 10 c# datagridview winforms

我有一个绑定到数据源的datagridview.当我单击"编辑"按钮或"新建"按钮时,我必须在datagridview中添加一个新行.我尝试了一些代码,但它给了我错误,代码如下

DataGridView grdview = new DataGridView();
grdview.Rows.Add();
grdview.Rows[grdview.Rows.Count - 1].Cells[0].Selected = true;
grdview.BeginEdit(false);
Run Code Online (Sandbox Code Playgroud)

我还尝试将数据源类型转换为数据表但没有解决方案.

Kur*_*ran 8

看来你正在使用的DataSource属性DataGridView.当此属性用于绑定到数据时,您无法直接向DataGridView显式添加行.您必须直接向数据源添加行.

If you are binding a List

//Assume Student list is bound as Dtaasource
List<Student> student = new List<Student>();

//Add a new student object to the list
student .Add(new Student());

//Reset the Datasource
dataGridView1.DataSource = null;
dataGridView1.DataSource = student;
Run Code Online (Sandbox Code Playgroud)

If you are binding DataTable

DataTable table = new DataTable();

 DataRow newRow = table.NewRow();

// Add the row to the rows collection.
table.Rows.Add(newRow);
Run Code Online (Sandbox Code Playgroud)


Moo*_*ght 7

不,如果DataGridView数据绑定到某些数据源,则无法添加新的行/列.您将不得不DataTable使用所需的列创建一个新的数据集(或其他),然后重新绑定DataGridView到该数据集.

我希望这有帮助.


Mau*_*tro 6

绑定到 aBindingSource而您将保留 NewRow