How to insert a new row to the top of the DataGridView
I have a datagridview to store a list of inventory transactions. I listed them in descending order by having the latest entered transaction to be shown on the top. When entering data, I have a few fields appearing immediately about the DataGridView in the main form to allow user to enter transaction data. When the use click the save button, I'll insert the new data into the datatable and to the DataGriidView. However, it ALWAYS inerts to the bottom of the DataGridView. It'll shows on the top ONLy when I exit the form and then reenters.
Question. When I ran the following statement, How can I "Add" the row to the TOP of the DataGridView such that it apears as the first row (on the top) ?
Dim str As String() = {Format(Last_Inventory_Row + 1, "##"), _
Format(Inventory_Date, Date_Medium_Fmt), _
Me.cboMaterial_Select_Category.Text, _
Format(Qty, Material_Fmt), _
Format(Purchased_Price, Price_Fmt), _
"", _
Current_User_Name}
Me.dgvMaterial_Inventory.Rows.Add(str)
Another option I can think of is to reverse the order and allows the new transaction to add to the bottom but then use the sort the table immediately such that it shows up on the top without existing the form. However, I do not know programmetically how to do it.
Can someone show me a sample code as how to programmatically sort a datagrid base on a particular column of data in it ?
Regards
Re: How to insert a new row to the top of the DataGridView
You should bind your DataTable to a BindingSource and then bind the BindingSource to the DataGridView. You then set the Sort property of the BindingSource much as you do an SQL ORDER BY clause, which will keep the data in the grid ordered in that way at all times, e.g. "CreatedDate DESC" will order the data in descending order by CreatedDate, thus newest first.
Having said that, as far as I'm aware the input row in a DGV is always displayed at the bottom, so the user would add the new row at the bottom of the grid. Not until the row is validated, which generally means that focus is moved away from that row, is the data added to the underlying data source, at which point it will be placed appropriately for the current sort order. I don't think that there's any way around that.
If you don't want the user adding at the bottom of the grid then the alternative would be to not allow direct entry of new rows via the grid, but have the user press a button to pop up a dialogue to input new records. You'd then add the new data directly to the DataTable or BindingSource and data binding would take care of the rest.
Re: How to insert a new row to the top of the DataGridView
Or instead of a popup you could show a series of textboxes corresponding to your view and allow them to enter the data into them. Then click a button to insert it into your view/table and update the binding or bindingsource.