.Net DataGridView Show/Hide/Change Columns display Order in Windows Application

I am still working on the application, which need to consume the web-service from the other company. I would need to represent data into DataGridView from the response/result of the web-service, however the result is array of object, which I have not use as Data source for DataGridView before [most of the time I use, DataTable, which is generated by making a SQL call, E.g. by using DataAdapter]

DataGridView is clever enough to use array object as Data Source. It works reasonably well, except the columns order do not appear as the way I want. And I have no idea how to sort it out. It is very easy to achieve that on ASP.Net by using GridView, via BoundField or if the Data Source is from DataTable, which you can change the Columns Order by changed the SQL query.

Fortunately, I have worked out how to change the Columns Order on DataGridView.

Here it is my notes:
–Assign Data Source [Method GetLatestInfomation() return array of objects] 
       dgv_ShareChiWai.DataSource = GetLatestInfomation()
–You would need to set AutoGenerateColumns = False, otherwise as it said, it will generate column automatically and the columns you setup below will not be able to assign any values.
        dgv_ShareChiWai.AutoGenerateColumns = False

–Clear any existing column, otherwise when you reload the Data for the DataGridView, it will duplicate the columns

–The code below is used to
–dgv_ShareChiWai.Columns.Add(“The name of the property on the object which you want to assign to the column”, “Column Header”)

        dgv_ShareChiWai.Columns.Add(“id”, “Blog ID”)
        dgv_ShareChiWai.Columns.Add(“title”, “Title”)

   –Assign the property/values to the column.
        dgv_ShareChiWai.Columns(0).DataPropertyName = “id”
        dgv_ShareChiWai.Columns(1).DataPropertyName = “title”

Hope you find this useful. If you have better way to do it, feel free to share you experience.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.