开发者

Datagridview Winforms Add or Delete Rows in Edit Mode with Collection Binding

开发者 https://www.devze.com 2023-02-16 21:56 出处:网络
In my datagridview, I bind a List of objects named \'ProductLine\'. But unfortunately with this approach I cannot \'Add\' or \'Delete\' rows to the datagridview in edit mode. When I create a fresh new

In my datagridview, I bind a List of objects named 'ProductLine'. But unfortunately with this approach I cannot 'Add' or 'Delete' rows to the datagridview in edit mode. When I create a fresh new order I can Add or Delete rows but once I save it and try to open it in Edit then it doesn't let me 'Add' or 'Delete' (via keyboard).

Any idea?

Here is the code for this:

If it is a fresh Order then I do something like this:

private void Save(){
   for (int i = 0; i <= dtgProdSer.RowCount - 1; i++)
   {
      if ((itemList != null) && (itemList.Count > i))
           productLine = itemList[i];
      else
           productLine = new Prod开发者_运维百科uctLine();
      productLine.Amount = Convert.ToDouble(dataGridViewTextBoxCell.Value);
    }
}

And if it is an Edit then in the Form_Load I check ProductId is NON Zero then I do the following:

private void fillScreen{
    dtgProdSer.DataSource = itemList;
}

But with this I cannot Add or Delete Rows in Edit mode.

Any advise is greatly appreciated.


You haven't shown what type itemList is, but I'm going to assume that its not an ObservableCollection. In that case, you need to wrap your list in a binding source:

        var list = new List<ProductLine>(5);
        list.Add(new ProductLine { Amount = list.Count });
        list.Add(new ProductLine { Amount = list.Count });
        list.Add(new ProductLine { Amount = list.Count });
        list.Add(new ProductLine { Amount = list.Count });
        list.Add(new ProductLine { Amount = list.Count });

        var bs = new BindingSource {DataSource = list };
        dataGridView1.DataSource = bs;

FWIW, this is a well covered issue. Most of your DataGridView questions will probably be answered qucker by skimming the Related section on the right of the screen. For new questions, searching SO is a good first step.

0

精彩评论

暂无评论...
验证码 换一张
取 消