Tuesday, 12 June 2018

DataGridView : disable the column header sorting

VB.NET
 For Each column As DataGridViewColumn In DataGridView1.Columns
            column.SortMode = DataGridViewColumnSortMode.NotSortable
 Next


C#
foreach (DataGridViewColumn column in DataGridView1.Columns)
{
    column.SortMode = DataGridViewColumnSortMode.NotSortable;
}

Sunday, 10 June 2018

Copy Datagridview data to another Datagridview

The following is for VS2008 or higher. Place the code below into a code module, not a form or class.

<System.Runtime.CompilerServices.Extension()> _
Public Sub CloneRowWithValues(ByVal SingleRow As DataGridViewRow, ByVal Target As DataGridView)
    Dim Results As DataGridViewRow = CType(SingleRow.Clone(), DataGridViewRow)
    For Row As Int32 = 0 To SingleRow.Cells.Count - 1
        Results.Cells(Row).Value = SingleRow.Cells(Row).Value
    Next
    Target.Rows.Add(Results)
End Sub
-------------------------------------------------------------------------------------------------------------------------

Usage on the current row of DataGridView1 to add it to DataGridView2. Both DataGridView controls must have the same columns.

DataGridView1.CurrentRow.CloneRowWithValues(DataGridView2)

-------------------------------------------------------------------------------------------------------------------------
For copying all rows from DataGridView1 to DataGridView2
For Each row As DataGridViewRow In DataGridView1.Rows
    row.CloneRowWithValues(DataGridView2)
Next

 -------------------------------------------------------------------------------------------------------------------------
Another idea, you set a DataTable as the DataSource of a BindingSource component and set the DataSource of a DataGridView to the BindingSource. Now select some rows in the DataGridView, the code below shows how to copy the selected rows.

DataGridView1.EndEdit()
Dim TargetTable = DirectCast(bsData.DataSource, DataTable)
Dim rows = DataGridView1.SelectedRows
For Each row As DataGridViewRow In rows
    TargetTable.ImportRow(CType(bsData.Item(row.Index), DataRowView).Row)
Next

-------------------------------------------------------------------------------------------------------------------------
I tend to work from the DataTable (the DataSource) rather than the DataGridView. The above gives both approachs. You can modify the last one to exclude the BindingSource.
________________________________________
Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem.


source "https://social.msdn.microsoft.com/Forums/vstudio/en-US/e1c01817-1adb-4053-a5df-814ccd93abdb/copy-datagridview-data-to-another-datagridview?forum=vbgeneral"