I have a datagrid I must fill with a mix of
- Columns dynamically created with code
- Columns dinamically created retrieving data from a query (dynamic, naturally)
DataTable table;
using (SqlDataReader dr = cmd.ExecuteReader())
{
table.Load(dr);
// Insert row number column
DataGridViewTextBoxColumn rowColumn = new DataGridViewTextBoxColumn()
{
HeaderText = "Row",
Width = 40,
ReadOnly = true,
Frozen = true
};
dgv.Columns.Insert(0, rowColumn);
// Insert grouping column
DataGridViewComboBoxColumn groupColumn = new DataGridViewComboBoxColumn()
{
HeaderText = "Grouping",
Width = 70,
DisplayStyle = DataGridViewComboBoxDisplayStyle.ComboBox,
FlatStyle = System.Windows.Forms.FlatStyle.Flat,
Frozen = true
};
groupColumn.Items.AddRange(new object[] { "-", "Group 1", "Group 2"});
dgv.Columns.Insert(1, groupColumn);
// Populate row & grouping columns
.................
dgv.DataSource = table;
}
DataGridView is filled with desired data and user can alter everything he wants.
Finally I need to sort rows according to the modified content of columns edited values (both the created ones and the databound ones): how can I do this?
Databound datagridviews cannot be sorted using Sort() nor can I use Sort method of DataTable (or DataView I could put in the middle) because I have extra data.
I’m stuck with this…
Add the columns in your table instead of your datagridview.
This will make the column databound instead of creating it “manually”.
Then to turn the column into a combobox column have a look at this SO link:
How to change a datagridview cell style from the default textbox to combobox in vb.net?