今天在开发时,发一个原来可以编辑的DataGridView控件突然不能编辑了,DataGridView设置了ReadOnly=false,也设置了DataGridView中的各列的ReadOnly=false,但就是不能编辑,经大神帮助,原来是因为给DataGridView控件绑定了匿名的数据集的问题,我的绑定方法如下:
this.grid.DataSource =
(from t1 in PlatDbContext.PlatDbContextInstance.Public_Report
join t2 in PlatDbContext.PlatDbContextInstance.Public_ReportSet
on t1.PID equals t2.PID
where t1.FormID == formID
select new { t1.ID, t1.PID, t1.OrderID, t2.SetName, t2.TableName }).ToList();}
select new { t1.ID, t1.PID, t1.OrderID, t2.SetName, t2.TableName }说明返回的结果集是一个匿名类型,是只读的,所以导致了整个DataGridView不能编辑,解决方法就是,将t1.ID, t1.PID, t1.OrderID, t2.SetName, t2.TableName定义为一个自定义类,然后返回该自定义类集合,再绑定到DataGridView就可以了,修改如下:
自定义类:
public class V_Public_ReportSet
{
public int ID { get; set; }
public string PID { get; set; }
public int OrderID { get; set; }
public string SetName { get; set; }
public string TableName { get; set; }
}
修改绑定数据的方法:
IList<V_Public_ReportSet> list =
(from t1 in PlatDbContext.PlatDbContextInstance.Public_Report
join t2 in PlatDbContext.PlatDbContextInstance.Public_ReportSet
on t1.PID equals t2.PID
where t1.FormID == formID
select new V_Public_ReportSet
{
ID = t1.ID,
PID = t1.PID,
OrderID = t1.OrderID,
SetName = t2.SetName,
TableName = t2.TableName
}).ToList();
this.grid.DataSource = list;
问题解决!