RajnathKumar
RajnathKumar

Reputation: 37

How to get rowindex of dataGrid WPF?

Here am using the code in datagridview and it works fine.but how to get the rowindex in datagrid based on without selecteding the rows in datagrid in wpf.please help me to do. below the code am tried:

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

Upvotes: 0

Views: 293

Answers (1)

Sheridan
Sheridan

Reputation: 69987

@RajnathKumar, you need to use WPF properly... as your comments say, you shouldn't try to use it as if it were WinForms... it's not WinForms and trying to use it in that way will only cause you problems. This is how I would achieve your requirements:

First, data bind a data collection to the DataGrid.ItemsSource property (of a DataGrid):

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

Note that this YourCollection property should be an ObservableCollection of any type that you want... regardless of the type, I understand that it will have a unique Id property. Therefore, your required item can be found from the data bound collection directly using some basic LinQ:

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

Upvotes: 1

Related Questions