Go Premium for a chance to win a PS4. Enter to Win

  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 546
  • Last Modified:

Customize the column of Datagrid in VB.net

In the VB.net from the Database I am getting the following columns
Emp_Name, Rate_of_change and Salary

In the DataGrid I want to customize this columns as with the
following captions

Employee name
Rate of Change

correspondingly I want to set the width as

500 (for Employee name)
280 (for Rate of Change)
350 (for Salary)

Could you please let me know how to do this

1 Solution
myDataGrid.TableStyles[0].GridColumnStyles[0].Width = 500
 myDataGrid.TableStyles[0].GridColumnStyles[1].Width = 280
 myDataGrid.TableStyles[0].GridColumnStyles[2].Width = 350

right click the grid and select grid builder to customize it.
The easiest way to change the column header would be modifying your statement.
Instead of
"Select [ID], description from xyz"
You can use
"Select MyColumn1=[ID], MyColumn2=description from xyz"

Thats not beautiful, but is the simplest way to solve it.
A better method would be:

Dim oTable As New DataTable("test")
Dim oRead As New SqlClient.SqlDataAdapter("Select ID, description from xyz", oCon)
oTable.Columns(0).ColumnName = "myCol_Identifier"
oTable.Columns(1).ColumnName = "myCol_Text"
DataGrid1.DataSource = oTable

Notice that this will only work if you set the Datasource member of datagrid1 at runtime!
As OMC2000 as said, the best way to do that is to use the TableStyles.
If you don't provide anything, .NET will build one itself, very basic.

In the designer, add a new TableStyle and then add some columns.
For this to work, you must :
- Set a name to your DataTable : myTable.Name = "MyTable"
- Set the MappingName for the Table style to your table name "MyTable"
- For each column, set the mapping name to the name of your datatables column

Then you can customize a lot : Width, readonly, maxlength, ....

Be Careful !
The settings of the table style (backcolor, ...) override the settings of the datagrid.
So you have to set your settings there !

Featured Post

Windows Server 2016: All you need to know

Learn about Hyper-V features that increase functionality and usability of Microsoft Windows Server 2016. Also, throughout this eBook, you’ll find some basic PowerShell examples that will help you leverage the scripts in your environments!

Tackle projects and never again get stuck behind a technical roadblock.
Join Now