2012-10-28 100 views
1

我有一個datagridview與一些列和行。其中一列是字符串類型(DataGridViewTextBoxColumn)。我想遍歷這個DataGridViewTextBoxColumn的所有行找到與特定字符串匹配的第一個元素的索引(行索引),所以我做的:獲取與模式匹配的第一行的索引

int rowIndex = this.dataGridView1.Rows 
    .Cast<DataGridViewRow>() 
    .ToArray() 
    .First(row => row.Cells[this.colDesired.Index].Value == stringToSearch) 
    .Index; 

,但將引發一個錯誤。

我想使用Linq和lambdas。

+1

,如果你說的錯誤消息是它會有所幫助。 –

+0

拋出的錯誤消息是:System.InvalidOperationException'在System.Core.dll中 – user1624552

回答

0

您的解決方案適合我。幾件事情要注意:

  1. 您不必對IEnumberable CastToArray
  2. 確保this.colDesired.Index具有有效值。否則會引發運行時異常。
  3. 默認值DatagridViewCell.Value將爲空,因此您應該獲得適當的格式化值(DatagridViewCell.FormattedValue),具體取決於您的單元的FormatType(這裏是文本類型),以處理空情況。
  4. DatagridViewCell.FormattedValue是一個對象,所以你必須先將它轉換爲字符串。

這樣做:

int rowIndex = dataGridView1.Rows.Cast<DataGridViewRow>().First(row => row.Cells[this.colDesired.Index].FormattedValue.ToString() == stringToSearch).Index; 
+0

您是對的,出現了錯誤:在特殊情況下找不到stringToSearch。所以,這是現在工作。無需做ToArray。 – user1624552

0

這應該工作:

​​
+0

您可以通過在其周圍添加反引號(')來格式化您的答案,使其看起來像代碼。 – alestanis

相關問題