First Create this class:
public class ColumnFactory
{
public static DataGridViewColumn CreateColumn(DataColumn dataColumn)
{
DataGridViewColumn column = null;
DataSet dataSet = dataColumn.Table.DataSet;
DataTable parentTable = null;
for (int i = 0; i < dataSet.Relations.Count; i++)
if (dataSet.Relations[i].ChildColumns.ToList<datacolumn>().Contains(dataColumn))
{
parentTable = dataSet.Relations[i].ChildColumns[0].Table;
break;
}
if (parentTable != null)
{
column = new DataGridViewComboBoxColumn()
{
DataSource = parentTable,
DisplayMember = "Discriptor",
ValueMember = "ID"
};
}
else
column = new DataGridViewTextBoxColumn();
column.HeaderText = column.Name = dataColumn.ColumnName;
return column;
}
}
then create your own GridView:
public class GridView: System.Windows.Forms.DataGridView
{
protected override void OnCreateControl()
{
base.OnCreateControl();
this.AutoGenerateColumns = false;
}
public void RefreshColumns(DataTable table)
{
if (table == null)
return;
this.Columns.Clear();
foreach (DataColumn dataColumn in table.Columns)
this.Columns.Add(ColumnFactory.CreateColumn(dataColumn));
}
protected override void OnDataError(bool displayErrorDialogIfNoHandler, DataGridViewDataErrorEventArgs e)
{
if (MessageBox.Show("The Entries were not valid\nDo you want to continue? ",
"Error",
MessageBoxButtons.YesNo,
MessageBoxIcon.Warning)
e.Cancel = true;
displayErrorDialogIfNoHandler = false;
base.OnDataError(displayErrorDialogIfNoHandler, e);
}
}
At your Form:
DataGridView.RefreshColumns(DataSet.Tables[this.BindingSource.DataMember]);