Wednesday, April 13, 2011

Combobox in datagridviews binding classes and structures

Hi, my problem today is how to show the list of data from an structure into a datagridview using combobox in some columns.

First of all I was surfing on the internet and I found this for enums:

//CF: set to null before setting it to the current to
//clear out previous results
this.bindingSource1.DataSource = null;

this.bindingSource1.DataSource = MyDal.GetDataTable();

void _formatStatusColumn()
{
DataTable dt = new DataTable("Status");

//CF: actually how it's stored in the db.
dt.Columns.Add("Status", typeof(int));
dt.Columns.Add("Status_Name", typeof(string));

//CF: this way I can add or remove enum values, and
//the combo will always reflect the correct values.
foreach(int index in Enum.GetValues(typeof(Status)){
dt.Rows.Add(index, Enum.GetName(typeof(Status), index));
}

//CF: now for the UI column
DataGridViewComboBoxColumn statusColumn =
new DataGridViewComboBoxColumn();

//CF: seems to control where the column is placed.
statusColumn.DisplayIndex = 3;
statusColumn.HeaderText = "Status";

statusColumn.DataPropertyName = "Status";
statusColumn.DataSource = dt;
statusColumn.DisplayMember = "Status_Name";
statusColumn.ValueMember = "Status";

this.dataGridView1.Columns.Add(statusColumn);
}


This was very useful but I need something easier. I have to read a list and show the field in the combobox, so I've changed the code like that:

public void FormatResidenceColumn()
{
if (this.dataGridView1.Columns.Count > 0)
{
DataTable dt = new DataTable("Residence");

dt.Columns.Add("Residence", typeof(int));
dt.Columns.Add("Residence_Name", typeof(string));

this.dataGridView1.Columns.Remove("Residence");

if (Globals.ListOfResidences.Count > 0)
{
foreach (Residence obj in Globals.ListOfResidences)
{
dt.Rows.Add(obj.Id - 1, obj.Alias);
}
}
else
{
// Empty
dt.Rows.Add(0, "Empty");
}

//CF: now for the UI column
DataGridViewComboBoxColumn combColumn =
new DataGridViewComboBoxColumn();

//CF: seems to control where the column is placed.
combColumn.DisplayIndex = 4;
combColumn.HeaderText = "Residencia";

combColumn.DataPropertyName = "Residence";
combColumn.DataSource = dt;
combColumn.DisplayMember = "Residence_Name";
combColumn.ValueMember = "Residence";

this.dataGridView1.Columns.Add(combColumn);
}
}


where I use an global variable named ListOfResidence in this example.

Hope help!!

No comments:

Post a Comment