Пример ниже показывает как сделать это.
using System;
using System.Collections;
using System.Windows.Forms;
namespace TestApplication
{
public class TestForm : System.Windows.Forms.Form
{
private DataGrid _booksGrid;
ArrayList _booksList;
Button _b;
public TestForm()
{
Text = "Test Form";
_booksGrid = new DataGrid();
_booksGrid.Name = "_booksGrid";
_booksGrid.Dock = DockStyle.Fill;
CreateBooksDataSource();
_booksGrid.DataSource = _booksList;
_booksGrid.TableStyles.Add(CreateBooksStyle());
_booksGrid.Height = 200;
_b = new Button();
_b.Text = "Add book";
_b.Dock = DockStyle.Bottom;
Controls.Add(_b);
Controls.Add(_booksGrid);
_b.Click += new EventHandler(OnButtonClick);
}
void OnButtonClick(object sender, EventArgs e) {
_booksList.Add(new Book(_booksList.Count));
CurrencyManager cm = _booksGrid.BindingContext[_booksList] as CurrencyManager;
if (cm != null) cm.Refresh();
}
void CreateBooksDataSource()
{
_booksList = new ArrayList();
for(int i = 0; i < 10; i++)
{
_booksList.Add(new Book(i));
}
}
DataGridTableStyle CreateBooksStyle()
{
DataGridTableStyle tableStyle = new DataGridTableStyle();
tableStyle.MappingName = "ArrayList";
tableStyle.PreferredColumnWidth = 150;
DataGridTextBoxColumn titleColumn = new DataGridTextBoxColumn();
titleColumn.HeaderText = "Название";
titleColumn.MappingName = "Title";
tableStyle.GridColumnStyles.Add(titleColumn);
DataGridTextBoxColumn authorColumn = new DataGridTextBoxColumn();
authorColumn.HeaderText = "Автор";
authorColumn.MappingName = "Author";
tableStyle.GridColumnStyles.Add(authorColumn);
return tableStyle;
}
[STAThread]
static void Main()
{
Application.Run(new TestForm());
}
}
public class Book
{
private string _title;
public string Title
{
get{ return _title; }
set{ _title = value; }
}
private string _author;
public string Author
{
get{ return _author; }
set{ _author = value; }
}
public Book(int i)
{
_title = "book #" + i.ToString();
_author = "author #" + i.ToString();
}
}
}
Так же это можно сделать с помощью этого кода, но при этом собъется текущая позиция DataGrid'а.
_booksGrid.DataSource = null;
_booksGrid.DataSource = _booksList;