1

DataGridView在 C# 表单应用程序中有一个表 ()。对象列表就是binded它。我可以从选定的行中获取绑定对象。

但我也想通过只有列表中的对象以编程方式在表中选择行。我该怎么做?

我不想按Index(整数值)选择。

4

2 回答 2

2

如果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);
 }
于 2013-02-24T08:13:21.450 回答
1

我会尝试这样的事情:

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值。

于 2013-02-23T15:04:18.697 回答