locked
how to reorder dgv columns at runtime? RRS feed

  • Question

  • how do i reorder dgv's columns at runtime programatically?? vb code.

    even if i can do that at design time is alrite, i have a bindingsource   with as source a list of a class, and the b.source isthe source of the dgv. how is it ordering the columns? it s not evident from my contructor or anything.

    Tuesday, September 5, 2006 10:45 AM

Answers

  • Try something like this

     

    Dim strConn As String

    Dim conn As SqlConnection

    Dim da As SqlDataAdapter

    Dim dt As New DataTable

    strConn = "Server = .\SQLEXPRESS; Database = pubs; Integrated Security = SSPI;"

    conn = New SqlConnection(strConn)

    da = New SqlDataAdapter("Select * From titles", conn)

    da.Fill(dt)

    DataGridView1.DataSource = dt

    DataGridView1.Columns(0).ReadOnly = True

    Dim x As Integer = DataGridView1.Columns.Count - 1

    Dim col As DataGridViewColumn = DataGridView1.Columns(x).Clone

    DataGridView1.Columns.RemoveAt(x)

    DataGridView1.Columns.Insert(0, col)

    Tuesday, September 5, 2006 4:13 PM

All replies

  • Try something like this

     

    Dim strConn As String

    Dim conn As SqlConnection

    Dim da As SqlDataAdapter

    Dim dt As New DataTable

    strConn = "Server = .\SQLEXPRESS; Database = pubs; Integrated Security = SSPI;"

    conn = New SqlConnection(strConn)

    da = New SqlDataAdapter("Select * From titles", conn)

    da.Fill(dt)

    DataGridView1.DataSource = dt

    DataGridView1.Columns(0).ReadOnly = True

    Dim x As Integer = DataGridView1.Columns.Count - 1

    Dim col As DataGridViewColumn = DataGridView1.Columns(x).Clone

    DataGridView1.Columns.RemoveAt(x)

    DataGridView1.Columns.Insert(0, col)

    Tuesday, September 5, 2006 4:13 PM
  • i'd say this is a property microsoft should have implemented for the dgv.

    dgv.reordercolumn(indexofcolumn,newindex)

    dgv.reordercolumn(nameofcolumn,indexofcolumn)

    it makes sense and i think it is somewhere already there but not public methods.

    Wednesday, September 6, 2006 6:29 AM
  •  hrubesh wrote:

    i'd say this is a property microsoft should have implemented for the dgv.

    dgv.reordercolumn(indexofcolumn,newindex)

    dgv.reordercolumn(nameofcolumn,indexofcolumn)

    it makes sense and i think it is somewhere already there but not public methods.

    It's actually quite easy.  The example is in C#, but can easily be converted to VB.

        int i = 0;

        dgv.AutoGenerateColumns = false;
        dgv.Columns["FirstName"].DisplayIndex = i++;
        dgv.Columns["MiddleName"].DisplayIndex = i++;
        dgv.Columns["LastName"].DisplayIndex = i++;

    Hope this helps.

    Monday, October 16, 2006 8:13 PM