Hi,
I have a textbox which, when typing in it, selects the Item in my WPF datagrid with the matching item, however, it changes the first item as well to what is typed in the textbox before going to the matching item in the grid. I'm not sure how that is possible? Can someone help find what's wrong?
The search is only performed on the first column of the datagrid. (firstname)
Code:
private void textBox1_TextChanged( object sender, TextChangedEventArgs e )
{
if ( sender is TextBox )
{
if (!dataGrid1.IsReadOnly)
dataGrid1.IsReadOnly = true;
for (int i = 0; i < dataGrid1.Items.Count; i++)
{
Microsoft.Windows.Controls.DataGridRow row = (Microsoft.Windows.Controls.DataGridRow)dataGrid1.ItemContainerGenerator.ContainerFromIndex(i);
TextBlock cellcontent = dataGrid1.Columns[0].GetCellContent(row) as TextBlock;
if (cellcontent != null && cellcontent.Text.Equals(textBox1.Text))
{
object item = dataGrid1.Items[i];
dataGrid1.SelectedItem = item;
dataGrid1.ScrollIntoView(item);
row.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
break;
}
}
}
}
WPF Datagrid XAML:
<my:DataGrid AutoGenerateColumns="False" CanUserAddRows="True" Margin="12,0,12,12" IsSynchronizedWithCurrentItem="True" Name="dataGrid1" Height="267" VerticalAlignment="Bottom" CanUserDeleteRows="True" BeginningEdit="dataGrid1_BeginningEdit">
<my:DataGrid.Columns>
<my:DataGridTextColumn Binding="{Binding Path=FirstName, Mode=OneWay}" Header="Firstname"></my:DataGridTextColumn>
<my:DataGridTextColumn Binding="{Binding Path=LastName, Mode=TwoWay}" Header="Lastname"></my:DataGridTextColumn>
<my:DataGridTextColumn Binding="{Binding Path=PersonType, Mode=TwoWay}" Header="PersonType"></my:DataGridTextColumn>
<my:DataGridTemplateColumn Width="100" Header="Change">
<my:DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Button Content="Edit" Click="DetailsButton_Click"></Button>
</DataTemplate>
</my:DataGridTemplateColumn.CellTemplate>
</my:DataGridTemplateColumn>
</my:DataGrid.Columns>
</my:DataGrid>
EDIT:
textbox XAML:
<TextBox Height="23" TextChanged="textBox1_TextChanged" HorizontalAlignment="Left" Margin="12,37,0,0" Name="textBox1" VerticalAlignment="Top" Text="{Binding Path =FirstName}" Width="120" />