Saturday, July 15, 2006

DataGridViewColumn DataPropertyName

This is an important property in every DataGridViewColumn. If you are binding to a DataTable, you must set this property to the name of the column in the DataTable that you want to bind this DataGridColumn to.

For example: Open a new Windows Form project. Add a DataGridView control to the main form. Right click on the DataGridView, select edit columns, add a DataGridViewTextBoxColumn (just call it Column1).

Now put this code in the constructor:


public partial class Form1 : Form
{
private DataTable dt;
private DataSet ds;

public Form1()
{
InitializeComponent();
dt = new DataTable("mytable");
dt.Columns.Add("Name");
dt.Rows.Add(new object[]{"michelle"});
ds = new DataSet();
ds.Tables.Add(dt);
this.dataGridView1.DataSource = ds;
this.dataGridView1.DataMember = "mytable";
}
}

Run the project - two columns will show up - Column1 and Name, the one row, will be blank for Column1 and Michelle for Name. This is probably not what we want.

Now go back to the Designer View - right click on the DataGridView and select edit columns, select Column1 and set DataPropertyName to Name.

Now run it again. This time you should get one column titled Name, with one row, michelle. Much better!

No comments: