C# 使用对象而不是索引选择行

C# 使用对象而不是索引选择行,c#,winforms,datagridview,C#,Winforms,Datagridview,我在C窗体应用程序中有一个表DataGridView。对象列表绑定到它。 我可以从所选行获取绑定对象 但我还希望通过仅从列表中选择对象,以编程方式选择表中的行。我怎么做 我不想按索引整数值进行选择。我会尝试这样做: var row = dataGrid.Rows .Cast<DataGridViewRow>() .FirstOrDefault(r => (CPatient)r.DataBoundItem =

我在C窗体应用程序中有一个表DataGridView。对象列表绑定到它。 我可以从所选行获取绑定对象

但我还希望通过仅从列表中选择对象,以编程方式选择表中的行。我怎么做


我不想按索引整数值进行选择。

我会尝试这样做:

var row = dataGrid.Rows
                  .Cast<DataGridViewRow>()
                  .FirstOrDefault(r => (CPatient)r.DataBoundItem = myItem);

var rowIndex = row != null ? row.Index : -1;
如果网格不包含使用该对象绑定的行,则应返回行索引或-1

如果用户能够在运行时对数据网格重新排序,则可以使用row.DisplayIndex而不是row.Index。这是因为DataGridViewBand.Index有以下注释:

此属性的值不一定与 带区在集合中的当前可视位置。对于 例如,如果用户在运行时对DataGridView中的列重新排序 假设AllowUserToOrderColumns属性设置为true,则 每列的Index属性值不会更改。相反 列DisplayIndex值将更改。但是,对行进行排序会产生影响 更改它们的索引值

如果BindingSource=BindList,则可以使用

public class CPatient
{
    public int Id { get; set; }
    public string IdNo { get; set; }
    public string Name { get; set; }
}
加载事件

点击事件


您的列表看起来怎么样?@spajce BindingList但为什么不基于索引?您可以尝试第一个答案。是否使用bindingSource.DataSource=yourBindingList?是的。我不想为得到正确的索引而担心。对不起,我想您应该将所选行的索引设置为bs.Position。但是为什么我们在这里使用值5呢?我需要当前选定的索引,因为我知道绑定到该索引的对象。5它只是个人的唯一Id。因此,我们必须使用从bindingSource中选择此人的当前索引。尝试随机设置Id,以便看到差异。
//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);
 }