Tim Van Wassenhove

Passionate geek, interested in Technology. Proud father of two

03 Sep 2006

Selecting custom Objects from a DataGridView

Here is a way that allows the user to select a row (custom object properties are used as column values) from a DataGridView assuming that the SelectionMode property is set FullRowSelect

private void FillDataGridViewPersons( List<person> persons ) 
{
	this.dataGridViewPersons.Rows.Clear();

	for ( int i = 0; i < persons.Count; ++i ) 
	{ 
		this.dataGridViewPersons.Rows.Add(); 
		this.dataGridViewPersons.Rows[i].Tag = persons[i]; 
		this.dataGridViewPersons.Rows[i].SetValues( new object[] { persons[i].Id, persons[i].Name } ); 
	} 
} 

private void buttonDoSomething_Click( object sender, EventArgs e ) 
{ 
	if ( this.dataGridViewPersons.SelectedRows.Count == 1 ) 
	{ 
		int selectedRowIndex = this.dataGridViewPersons.SelectedCells[0].RowIndex; 
		Person selectedPerson = (Person)this.dataGridViewPersons.Rows[selectedRowIndex].Tag; 
		MessageBox.Show( String.Format( "You selected the person with 	} 
}