【问题标题】:How to get rowindex of dataGrid WPF?如何获取dataGrid WPF的rowindex?
【发布时间】:2014-12-02 23:37:50
【问题描述】:

这里我使用datagridview中的代码,它工作正常。但是如何在不选择wpf中datagrid中的行的情况下获取datagrid中的rowindex。请帮我做。 下面的代码我试过了:

private int GetRowIndex(string ID)
{
  int num = -1;
  //Get the row based on ID
  foreach (DataGridViewRow dataGridVV in (IEnumerable)this.dataGridView.Cells)
  {
    if (dataGridVV.Cells[0].Value.Equals((object)ID))
        num = dataGridVV.Index;
  }
  return num;
}

【问题讨论】:

  • 为什么在 wpf 中需要行索引?
  • 使用 SelectedItem 和/或 SelectedIndex 属性有什么问题?
  • 您不应该使用 WinForms 样式的 WPF。使用绑定集合,而不是 DataGrid
  • 你的 ItemsSource 应该指向一个 ObservableCollection,然后你所要做的就是在那里删除它。
  • 正如@HenkHolterman 已经说过的,从ItemsSource 中删除该项目。

标签: c# .net wpf datagridview datagrid


【解决方案1】:

@RajnathKumar,您需要正确使用 WPF...正如您的 cmets 所说,您不应该尝试像 WinForms 一样使用它...它是 not WinForms 并尝试使用那样只会给你带来麻烦。这就是我将如何满足您的要求:

首先,数据将数据集合绑定到DataGrid.ItemsSource 属性(DataGrid):

<DataGrid ItemsSource="{Binding YourCollection}" ... />

请注意,此YourCollection 属性应该是您想要的任何类型的ObservableCollection...无论类型如何,我都知道它将具有唯一的Id 属性。因此,可以从数据绑定集合中直接使用一些基本的LinQ找到您需要的项目:

var itemToRemove = YourCollection.FirstOrDefault(i => i.Id == someIdValue);
if (itemToRemove != null) YourCollection.Remove(itemToRemove);

【讨论】:

  • First 如果没有任何匹配项将抛出异常。不会返回任何null 值。你应该使用FirstOrDefault
  • +1 哦,我的错...谢谢,我忘记了 OrDefault... 正在更新。
  • 为了公正起见,只有在集合更改时需要更新ItemsControl时,绑定集合才应为ObservableCollection。否则它可能是List&lt;T&gt;Collection&lt;T&gt;...
  • @Dennis... 比抱歉更安全。以我的经验,经常会有一个跟进的问题,所以现在我只建议一直使用它们。
  • 实际上,我使用了一个数据表作为“datatableobject”,基于你的例子,我给出了
猜你喜欢
  • 2012-06-02
  • 1970-01-01
  • 2010-11-09
  • 1970-01-01
  • 2021-12-26
  • 2013-06-15
  • 1970-01-01
  • 2017-10-03
  • 2013-03-21
相关资源
最近更新 更多