我在C#表单应用程序中有一个表(DataGridView
)。对象列表为binded
。
我可以从选定的行中获取绑定对象。
但我还想通过只有List中的对象在Table中以编程方式选择行。我该怎么做?
我不想按Index
选择(整数值)。
答案 0 :(得分: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);
}
答案 1 :(得分: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
中的列 (假设AllowUserToOrderColumns
属性设置为true), 每列Index
属性的值不会更改。代替, 列DisplayIndex
值会发生变化。但是,对行进行排序 更改其Index
值。