编辑datagridview单元格不起作用

时间:2015-10-09 06:12:20

标签: c# data-binding datagridview

我填写了我的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;

如果我在同一个数据网格视图中填充数据库中的数据,那么效果很好..

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];

任何人都可以帮助我吗?

1 个答案:

答案 0 :(得分:0)

您将网格绑定到匿名类型的对象列表

但匿名对象是不可变的

绑定工作正常,您无法编辑单元格中的值

使用相同的属性(不是字段!)创建类(说CustomerGridModel)(CustomerIdName等)并将网格绑定到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;

其中CustomerGridModel

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