我DataGridView
在 C# 表单应用程序中有一个表 ()。对象列表就是binded
它。我可以从选定的行中获取绑定对象。
但我也想通过只有列表中的对象以编程方式在表中选择行。我该怎么做?
我不想按Index
(整数值)选择。
我DataGridView
在 C# 表单应用程序中有一个表 ()。对象列表就是binded
它。我可以从选定的行中获取绑定对象。
但我也想通过只有列表中的对象以编程方式在表中选择行。我该怎么做?
我不想按Index
(整数值)选择。
如果BindingSource = BindList<CPatient>
你可以使用这个
public class CPatient
{
public int Id { get; set; }
public string IdNo { get; set; }
public string Name { get; set; }
}
加载事件
//Global Variable
BindingList<CPatient> bind = new BindingList<CPatient>();
BindingSource bs = new BindingSource();
private void Form1_Load(object sender, EventArgs e)
{
bind.Add(new CPatient { Id = 1, IdNo = "1235", Name = "test" });
bind.Add(new CPatient { Id = 2, IdNo = "6789", Name = "let" });
bind.Add(new CPatient { Id = 3, IdNo = "1123", Name = "go" });
bind.Add(new CPatient { Id = 4, IdNo = "4444", Name = "why" });
bind.Add(new CPatient { Id = 5, IdNo = "5555", Name = "not" });
bs.DataSource = bind;
dataGridView1.DataSource = bs;
}
点击事件
private void button1_Click_1(object sender, EventArgs e)
{
bs.Position = bs.List.Cast<CPatient>().ToList().FindIndex(c => c.Id == 5);
}
我会尝试这样的事情:
var row = dataGrid.Rows
.Cast<DataGridViewRow>()
.FirstOrDefault(r => (CPatient)r.DataBoundItem = myItem);
var rowIndex = row != null ? row.Index : -1;
如果网格不包含使用该对象绑定的行,它应该返回行索引或 -1。
如果用户能够在运行时重新排序 dataGrid,您可以使用row.DisplayIndex
而不是。row.Index
那是因为DataGridViewBand.Index
有以下注释:
此属性的值不一定与集合中波段的当前视觉位置相对应。例如,如果用户
DataGridView
在运行时对 a 中的列重新排序(假设AllowUserToOrderColumns
属性设置为 true),则Index
每列的属性值不会改变。相反,列DisplayIndex
值会发生变化。然而,对行进行排序确实会改变它们的Index
值。