Reputation: 167
I have a DataGridView that I populate by binding it to a DataTable returned from an sql query, which works as you'd expect.
Later on if a user wants to see additional information in the DataGridView by clicking a button I manually add a column to the end of the DataGridView - dgvOrders.Columns.Add("profit", "Profit");
and populate it with data based on logic determined by other DataGridColumns cells values.
It all works perfectly until you click one of the column headers to sort the data, at which point the data is sorted correctly BUT every cell in my new column loses it's value and shows as empty. On top of that I don't seem to be able to filter by my new column at all either. Is it a no-no to manually add columns to a databound DataGridView or am I missing something else here?
Upvotes: 0
Views: 1593
Reputation:
Firstly, I would urge you to share your code, its much easier to look than guessing.. Sounds like your problem is with the data binding. Personally I don't like working directly with the data grid. Its much easier to work on your model or adapter and then rebind:
..your model container or adapter, e.g. SqlDataAdapter gets updated here...
DataTable dt = new DataTable();
adapter.Fill(dt);
dgvOrders.DataSource = dt;
dgvOrders.Columns.Add("yourcolumn", "yourcolumn");
otherwise if you prefer to work directly on the dgvOrders, do something like that:
dgvOrders.Columns.Add(new BoundField { DataField = "yourcolumn"})
dgvOrders.DataSource = yourdatasource;
dgvOrders.DataBind(); //dont forget to databind again!
Upvotes: 1