编辑datagridview单元格不工作

本文关键字:工作 单元格 datagridview 编辑 | 更新日期: 2023-09-27 18:16:48

我填我的datagridview,但现在我不能编辑我的数据。

有我的代码:

BindingSource b = new BindingSource();
string cus1 = getCustomers.getCustomersApi();
RootObject cus = JsonConvert.DeserializeObject<RootObject>(cus1);
dataGridView2.Columns.Clear();
AddCheckBoxForDataGridViewCustomer();
//  DataGridViewButtonColumn bc = new DataGridViewButtonColumn();
// dataGridView2.Columns.Add(bc);
var result = cus.Rows.Select(r => new
    {
        CustomerId = r.CustomerId,
        Name = r.Name,
        Code = r.Code,
        Address = r.Address,
        PostalCode = r.PostalCode,
        City = r.City,
        Country = r.Country.Name,
        TaxNumber = r.TaxNumber,
    }).ToList();
// dataGridView2.DataSource = result;
// dataGridView2.EditMode = DataGridViewEditMode.EditOnEnter;
b.DataSource = result;
dataGridView2.DataSource = b;
dataGridView2.ReadOnly = false;

如果我填写我的数据从数据库在相同的datagridview,它的工作良好..

dbConnect.connection.Open();
adapter = new MySqlDataAdapter("select * from " + dbConnect.tableCustomer + "", dbConnect.connection);
ds = new System.Data.DataSet();
adapter.Fill(ds);
dataGridView2.DataSource = ds.Tables[0];
有人能帮我吗?

编辑datagridview单元格不工作

您正在将grid绑定到匿名类型的对象列表

但是匿名对象是不可变的

绑定工作正常,不能编辑单元格

中的值

创建具有相同属性(不是字段!)(CustomerId, Name等)的类(例如CustomerGridModel)并将网格绑定到List<CustomerGridModel>

BindingSource b = new BindingSource();
string cus1 = getCustomers.getCustomersApi();
RootObject cus = JsonConvert.DeserializeObject<RootObject>(cus1);
dataGridView2.Columns.Clear();
AddCheckBoxForDataGridViewCustomer();
var result = cus.Rows.Select(r => new
    CustomerGridModel
    {
        CustomerId = r.CustomerId,
        Name = r.Name,
        Code = r.Code,
        Address = r.Address,
        PostalCode = r.PostalCode,
        City = r.City,
        Country = r.Country.Name,
        TaxNumber = r.TaxNumber,
    }).ToList();
b.DataSource = result;
dataGridView2.DataSource = b;
dataGridView2.ReadOnly = false;

where CustomerGridModel:

public class CustomerGridModel
{
    public int CustomerId { get; set; }
    public string Name    { get; set; }
    // etc
    public string TaxNumber { get; set; }
}