Hi Member,
This code you are showing is not very safe - you say the cell[0] has the index, string comparison etc. I hope you don't rely heavily on this "index" thing.
Anyway, I assume you have got reasons to use such code...
In WPF you would normally use Binding to bind a list (some enumeration whatever) to your
DataGrid
. So I'd use Linq to find the desired record (row) in your underlaying datasource, then you can just use the
IndexOf
method of the
ItemCollection
.
This code shows the idea - you can run it if you replace MainWindow in a new WPF project with the following.
<Window x:Class="WpfApplication2.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<DataGrid x:Name="m_datagrid"/>
<Button Content="Button" HorizontalAlignment="Left" Margin="422,283,0,0" VerticalAlignment="Top" Width="75" Click="Button_Click"/>
</Grid>
</Window>
public partial class MainWindow : Window
{
class Record
{
public string Key { get; set; }
public string Value { get; set; }
}
List<Record> m_list = new List<Record>
{
new Record { Key = "A", Value = "aaa"},
new Record { Key = "B", Value = "bbb"},
new Record { Key = "C", Value = "ccc"}
};
public MainWindow()
{
InitializeComponent();
m_datagrid.ItemsSource = m_list;
}
int GetRowIndex(string strKey)
{
int iIndex = -1;
Record record = m_list.FirstOrDefault(r => r.Key == strKey);
iIndex = m_datagrid.Items.IndexOf(record);
return iIndex;
}
private void Button_Click(object sender, RoutedEventArgs e)
{
MessageBox.Show(this, GetRowIndex("C").ToString());
}
Just my 2c - maybe it helps you.
Happy coding!