Я создал для вас фиктивный проект.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace TestApplications
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public class foo
{
public foo()
{
ID = Count + 1;
}
public static int Count;
public int ID { get; set; }
public string Name { get; set; }
}
List<foo> x = new List<foo>();
foo LastSelectedItem = new foo();
public MainWindow()
{
InitializeComponent();
this.btnAdd.Click += new RoutedEventHandler(btnAdd_Click);
this.dgvItems.SelectionChanged += new SelectionChangedEventHandler(dgvItems_SelectionChanged);
}
void dgvItems_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if(((DataGrid)sender).SelectedItem != null)
LastSelectedItem = ((DataGrid)sender).SelectedItem as foo;
}
void btnAdd_Click(object sender, RoutedEventArgs e)
{
if (txtItemContent.Text.Trim().Length != 0)
{
foo item = new foo();
foo.Count = foo.Count + 1;
item.Name = txtItemContent.Text;
x.Add(item);
dgvItems.ItemsSource = null;
dgvItems.ItemsSource = x;
dgvItems.SelectedItem = LastSelectedItem;
}
}
}
}
Тогда этот код ниже для XAML, если вы используете WPF или Silverlight. (Не обращайте внимания на это, если вы используете winforms, я простопоказал вам, что идея о том, что я звоню в коде)
<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d" x:Class="TestApplications.MainWindow"
Title="MainWindow" Height="350" Width="525">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="27"/>
<RowDefinition Height="1*"/>
</Grid.RowDefinitions>
<DataGrid x:Name="dgvItems" Grid.Row="1" AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridTextColumn x:Name="ID" Binding="{Binding ID}" Header="ID"/>
<DataGridTextColumn x:Name="Name" Binding="{Binding Name}" Header="Name" Width="460"/>
</DataGrid.Columns>
</DataGrid>
<StackPanel Orientation="Horizontal" d:LayoutOverrides="Width" HorizontalAlignment="Left">
<Label Content="Item:" d:LayoutOverrides="Height"/>
<TextBox x:Name="txtItemContent" TextWrapping="Wrap" VerticalAlignment="Center" MinWidth="250"/>
<Button x:Name="btnAdd" Content="ADD" Margin="0" Width="75" VerticalAlignment="Center"/>
</StackPanel>
</Grid>