添加在C#中有界DataGridView中的两个现有行之间插入新行

本文关键字:两个 之间 新行 插入 DataGridView 添加 | 更新日期: 2023-09-27 18:24:45

我试图在datagridview(已经绑定到数据库)中的两个现有行之间添加插入新的空白行,但我得到了以下异常:

当控件是数据绑定时,无法以编程方式将行添加到DataGridView的行集合

我的代码

private void load()
{
    string strProvider = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:'Users'AMOL'Desktop'Maratha.accdb";
    string strSql = "Select * from Maratha";
    OleDbConnection con = new OleDbConnection(strProvider);
    OleDbCommand cmd = new OleDbCommand(strSql, con);
    con.Open();
    cmd.CommandType = CommandType.Text;
    OleDbDataAdapter da = new OleDbDataAdapter(cmd);
    DataTable scores = new DataTable();
    da.Fill(scores);
    DGMaratha.DataSource = scores;
}
public void BtnRefresh_Click(object sender, EventArgs e)
{
    try
    {
        int row = (this.DGMaratha.CurrentCell.RowIndex);
        int column = (this.DGMaratha.CurrentCell.ColumnIndex);
        load();
        this.DGMaratha.CurrentCell = this.DGMaratha[column, row];
    }
    catch (Exception ex)
    {
        Console.WriteLine("Error: Failed to retrieve the required data from the DataBase.'n{0}", ex.Message);
        return;
    }
}
private void BtnAdd_Click(object sender, EventArgs e)
{
    int row = (this.DGMaratha.CurrentCell.RowIndex);
    DGMaratha.Rows.Insert(row, 1);
}

添加在C#中有界DataGridView中的两个现有行之间插入新行

当DataGridView是数据绑定时,将项插入DataSource:

int idx = DGMaratha.CurrentCell.RowIndex;
var table = (DataTable)DGMaratha.DataSource;
var row = table.NewRow();
table.Rows.InsertAt(row, idx);

DGV在绑定到DB时,更多的是显示而不是数组。如上所述,应该通过修改数据源来完成更改。