2013-02-23 18 views
1

我在C#表單應用程序中有一個表(DataGridView)。對象列表是binded。 我可以從選定的行中獲取綁定對象。使用對象不按索引選擇行

但我也希望通過只有列表中的對象以編程方式在表中選擇行。我該怎麼做?

我不想通過Index(整數值)來選擇。

+0

如何你的列表看起來像? – spajce 2013-02-23 15:00:33

+0

@spajce綁定列表 maximus 2013-02-23 15:01:34

+0

但爲什麼不基於索引?你可以嘗試第一個答案。 – spajce 2013-02-23 15:14:39

回答

2

如果您BindingSource = BindList<CPatient>您可以使用此

public class CPatient 
{ 
    public int Id { get; set; } 
    public string IdNo { get; set; } 
    public string Name { get; set; } 
} 

Load事件

//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; 
} 

Click事件

private void button1_Click_1(object sender, EventArgs e) 
{ 
    bs.Position = bs.List.Cast<CPatient>().ToList().FindIndex(c => c.Id == 5); 
} 
+0

對不起,我想你想將所選行的索引設置爲bs.Position。但爲什麼我們在那裏使用價值5?我需要當前選定的索引,因爲我知道綁定到該索引的對象。 – maximus 2013-02-24 16:27:49

+0

'5'它只是個人唯一的Id。所以我們必須使用[.FindIdex](http://msdn.microsoft.com/en-us/library/x1xzf2ca.aspx)從'bindingSource'中選擇當前的那個人的索引。嘗試隨機設置「Id」,以便看到差異。 – spajce 2013-02-24 16:31:30

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有如下評論:

此屬性的值並不一定對應於帶的集合中的 當前可視位置。例如,如果用戶在運行時間 (假設AllowUserToOrderColumns屬性設置爲true)重新排列DataGridView中的列,則每列的Index屬性的 值不會更改。相反, 列DisplayIndex值更改。但是,排序行 更改它們的Index值。