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

时间:2015-11-27 06:44:09

标签: c# winforms datagridview

我尝试在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);
}

2 个答案:

答案 0 :(得分:0)

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

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

答案 1 :(得分:0)

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