从linq查询中获取当前行详细信息 [英] Getting current row details from a linq query
问题描述
我正在使用vb.net 2012,linq,sqlserver compact。
我在左边有一个带有datagridview的表单,另一个表单包含一堆文本框和当前行详细信息的组合。
我想要做的是显示一个网格中的人员列表然后在第二个表单上显示所选的记录详细信息
我有这个linq查询:
I'm using vb.net 2012, linq, sqlserver compact .
I have a form with a datagridview on the left and another form containing a bunch of textboxes and combos for the current row's detail .
What I want to do is display a list of people in the grid then display the selected record details on the second form
I have this linq query:
Dim queryRead = (From contacts In db.Contatti _
Select contacts.Id, contacts.Nome, contacts.Comune, contacts.Provincia, contacts.Regione, contacts.DataNascita, contacts.DataMatrimonio)
bs.DataSource = queryRead
dgElenco.AutoGenerateColumns = False
dgElenco.DataSource = bs
然后在我的点击事件中:
then in my click event :
Private Sub dgElenco_Click(sender As Object, e As EventArgs) Handles dgElenco.Click
...
i = dgElenco.CurrentRow.Index
...
我在网格中获取数据。现在我的问题是如何在详细信息表单中显示所选行。通过调试器,我可以看到数据dgElenco.CurrentRow.DataBoundItem,但我似乎无法拉出单个字段。有人会指出我正确的方向,
谢谢
I get my data in the grid. Now my problem is how to display the selected row in the detail form. Looking through the debugger I can see the data dgElenco.CurrentRow.DataBoundItem but I can’t seem to pull out the individual fields . Would someone point me to the right direction please,
thanks
推荐答案
最好的方法是创建自己的数据类型类。我使用GridView控件并使用此方法获取名称属性值,如果您使用匿名类型。
Best way to do this is to create your own datatype class. I used a GridView Control and used this method to get the 'Name' property value if you are using anonymous type.
void Gridview1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
string Name = (string)DataBinder.Eval(e.Row.DataItem, "Name");
}
}
Please refer this link[^] for other approaches like using reflection.
这里我使用DataGridView Click事件
Here I used DataGridView Click event
private void dataGridView1_Click(object sender, EventArgs e)
{
//Approach -1, using column name
{
object name = dataGridView1.CurrentRow.Cells["NameCol"].Value;
}
{
object obj = dataGridView1.CurrentRow.DataBoundItem;
//Approach -2, using reflection
Type t = obj.GetType();
PropertyInfo p = t.GetProperty("Name");
object v = p.GetValue(obj, null);
//Approach -3, using new dynamic type
dynamic d = obj;
string name = d.Name;
int age = d.Age;
}
}
这篇关于从linq查询中获取当前行详细信息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!