我有以下代码来填充DataGridView
var results = from loc in dtLocations.AsEnumerable()
join con in dtContacts.AsEnumerable() on (int)loc["contactid"] equals (int)con["id"]
select new
{
id = con["id"],
mpoc = loc["mpoc"],
directno = loc["directno"],
extension = loc["extension"],
faxno = loc["faxno"],
billing = con["billing"],
fullname = con["fullname"],
mobno = con["mobno"],
email = con["email"]
};
dgv.AutoGenerateColumns = false;
dgv.DataSource = results.ToList<object>();
但是当我点击一个单元格时,我无法读回来
private void dgvLocations_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
DataGridView dgv = sender as DataGridView;
????? vals = ((List<object>)dgv.DataSource)[e.RowIndex];
object id = vals.id; //errors of course
}
我可以在Visual Studio的Watcher面板中看到它可以确定List中的元素,但是我无法弄清楚我需要设置vals以便再次读取它们的类型:(
答案 0 :(得分:1)
它(new { .. }
)引入anonymous type。匿名类型不能由静态已知(“编译时”)名称指定。
使用命名(非匿名)类型(其中MyRow
是已定义的具有所需属性的类):
// Put data in non-anonymous type
select new MyRow {
id = ..,
}
// Now can use a name statically
MyRow row = (MyRow)data[rowIndex];
dynamic
类型也可以与C#/。NET4 +一起使用。或者,甚至更ickier,object
和明确的反思。 (请注意,dynamic
- 类型表达式可以自动有效地处理icky反射;与object
一样,静态类型信息仍然丢失。)