473,698 Members | 2,554 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Align or increase width for one column for DataGrid in Vb.net

115 New Member
I’m using Vb.net application program. I created a datagrid having text field and checkbox fields. Everything is displaying correctly. I have 9 Columns and each columns are equally separated. In DataGrid property, I made PreferredColumn Width = 85. So its equally aligned.

I would like to give more width for the column named Department than rest of the columns. Because when its equally aligned, I can see the Departments displayed.

Department is the second column. that having long names under that. so when page loads, its only displaying half of that. so if i increase that column width i can see that. but i don't need to increase the other columns width. make rest of the columns width smaller and increase the second columns width.

The code I’m using to display this table is
Expand|Select|Wrap|Line Numbers
  1. Private Sub MainForm_Load(ByVal …………… ) Handles Me.Load
  2.         InitializeDataGrid()
  3.         getDepartments()
  4. End Sub
  6. Private Sub InitializeDataGrid()
  7.   Dim column1 As DataColumn
  8.         MonitorTable1 = New DataTable("MonitorTable")
  10.         ' Create "Dep ID" column
  11.         column1 = New DataColumn("DepID", GetType(Integer))
  12.         MonitorTable1.Columns.Add(column1)
  14.         ' Create "Dep Name" column
  15.         column1 = New DataColumn("Department", GetType(String))
  16.         MonitorTable1.Columns.Add(column1)
  18.         ' Create a column for each monitor
  19.         For i As Integer = 1 To 7
  20.             column1 = New DataColumn("Monitor " & i.ToString(), GetType(Boolean))
  22.             column1.AllowDBNull = False
  23.             column1.DefaultValue = False
  25.             MonitorTable1.Columns.Add(column1)
  26.         Next
  27.         DataGrid1.DataSource = MonitorTable1
  28. End Sub
  30. Sub getDepartments()
  32.         ' This is where you might ask the database how many departments there are
  33.         MonitorTable1.Rows.Clear()
  34.         myConnection.Open()
  35.         Dim strSQL As String = "Select DepID, DepName from Dep order by DepName"
  36.         Dim myCommand As OleDbCommand = New OleDbCommand(strSQL, myConnection)
  37.         Dim myReader As OleDbDataReader = myCommand.ExecuteReader
  38.         While myReader.Read
  39.             Dim row As DataRow = MonitorTable1.NewRow()
  40.             row("DepID") = myReader(0)
  41.             row("Department") = myReader(1)
  42.             MonitorTable1.Rows.Add(row)
  43.         End While
  44.         myReader.Close()
  45.         myConnection.Close()
  46.         DataGrid1.DataSource = MonitorTable1
  48. End Sub
If you have any idea how to align datagrid, please let me know. If you can provide an example then it will be great help for me.

Thanks in advance.
Jun 12 '08 #1
3 6129
7,872 Recognized Expert Expert
Isn't there an autowidth property that allows you to make the columns as wide as the header text, or as wide as the column data or neither or both?
Jun 12 '08 #2
115 New Member
To made auto width, inside DataGrid properties PreferredColumn Width property set to 85. so all the column width are equally aligned but not wide as column data.

but i want the second column more wide than other columns. because only the second column having long data.

if you have any idea how to do this, please help me. if you can provide an example then it will be great.

Thanks in advance.
Jun 12 '08 #3
115 New Member
This code will help to align the datagrid according to the contents (data) length in each columns.

Expand|Select|Wrap|Line Numbers
  1. SizeColumnsToContent(Me.DataGrid1, -1)
  3. Public Sub SizeColumnsToContent(ByVal dataGrid As DataGrid, ByVal nRowsToScan As Integer)
  5.         ' Create graphics object for measuring widths.
  6.         Dim Graphics As Graphics = DataGrid1.CreateGraphics
  8.         ' Define new table style.
  9.         Dim tableStyle As DataGridTableStyle = New DataGridTableStyle
  11.         Try
  12.             Dim dataTable As DataTable = dataGrid.DataSource
  14.             If (-1 = nRowsToScan) Then
  15.                 nRowsToScan = dataTable.Rows.Count
  16.             Else
  17.                 ' Can only scan rows if they exist.
  18.                 nRowsToScan = System.Math.Min(nRowsToScan, dataTable.Rows.Count)
  19.             End If
  21.             ' Clear any existing table styles.
  22.             dataGrid.TableStyles.Clear()
  24.             ' Use mapping name that is defined in the data source.
  25.             tableStyle.MappingName = dataTable.TableName
  27.             ' Now create the column styles within the table style.
  28.             Dim textColumnStyle As DataGridTextBoxColumn
  29.             Dim iWidth As Integer
  30.             Dim iCurrCol As Integer
  31.             For iCurrCol = 0 To dataTable.Columns.Count - 8
  32.                 Dim dataColumn As DataColumn = dataTable.Columns(iCurrCol)
  34.                 textColumnStyle = New DataGridTextBoxColumn
  35.                 textColumnStyle.TextBox.Enabled = True
  36.                 textColumnStyle.HeaderText = dataColumn.ColumnName
  37.                 textColumnStyle.MappingName = dataColumn.ColumnName
  39.                 ' Set width to header text width.
  40.                 iWidth = (Graphics.MeasureString(textColumnStyle.HeaderText, dataGrid.Font).Width)
  42.                 ' Change width, if data width is wider than header text width.
  43.                 ' Check the width of the data in the first X rows.
  44.                 Dim DataRow As DataRow
  45.                 Dim iRow As Integer
  46.                 For iRow = 0 To nRowsToScan - 1
  47.                     DataRow = dataTable.Rows(iRow)
  48.                     Dim iColWidth As Integer
  49.                     iColWidth = (Graphics.MeasureString(DataRow.ItemArray(iCurrCol).ToString(), dataGrid.Font).Width)
  50.                     iWidth = System.Math.Max(iWidth, iColWidth)
  51.                 Next
  53.                 textColumnStyle.Width = iWidth + 4
  55.                 ' Add the new column style to the table style.
  56.                 tableStyle.GridColumnStyles.Add(textColumnStyle)
  57.             Next
  59.             ' Now create the column styles within the table style.
  60.             Dim boolColumnStyle As DataGridBoolColumn
  61.             For iCurrCol = 2 To dataTable.Columns.Count - 1
  62.                 Dim dataColumn As DataColumn = dataTable.Columns(iCurrCol)
  64.                 boolColumnStyle = New DataGridBoolColumn
  65.                 boolColumnStyle.AllowNull = False
  66.                 boolColumnStyle.HeaderText = dataColumn.ColumnName
  67.                 boolColumnStyle.MappingName = dataColumn.ColumnName
  69.                 ' Set width to header text width.
  70.                 iWidth = (Graphics.MeasureString(boolColumnStyle.HeaderText, dataGrid.Font).Width)
  72.                 ' Change width, if data width is wider than header text width.
  73.                 ' Check the width of the data in the first X rows.
  74.                 Dim DataRow As DataRow
  75.                 Dim iRow As Integer
  76.                 For iRow = 0 To nRowsToScan - 1
  77.                     DataRow = dataTable.Rows(iRow)
  78.                     Dim iColWidth As Integer
  79.                     iColWidth = (Graphics.MeasureString(DataRow.ItemArray(iCurrCol).ToString(), dataGrid.Font).Width)
  80.                     iWidth = System.Math.Max(iWidth, iColWidth)
  81.                 Next
  83.                 boolColumnStyle.Width = iWidth + 4
  85.                 ' Add the new column style to the table style.
  86.                 tableStyle.GridColumnStyles.Add(boolColumnStyle)
  87.             Next
  88.             ' Add the new table style to the data grid.
  89.             dataGrid.TableStyles.Add(tableStyle)
  90.         Catch e As Exception
  91.         Finally
  92.             Graphics.Dispose()
  93.         End Try
  95.     End Sub
hope this will help someone.
Jun 17 '08 #4

Sign in to post your reply or Sign up for a free account.

Similar topics

by: Prateek | last post by:
Hi, How can I change the width of a column in datagrid control? TIA Prateek
by: Enver | last post by:
Hi! I am trying to use a datagrid control on a smart device application. I managed to see my data on it but i have to arrange the width of columns. How can i do that? I ve tried to use tablestyles but couldnt manage. I get System Null Reference Exception...
by: Hajash | last post by:
hi all, how do i set the width of a column in a datagrid.Please help.Thanks in advance. regards, hajash
by: web1110 | last post by:
Hi y'all, I have resized the columns in a DataGrid and I want to set the width of the DataGrid to fit the columns. Just summing the column widths is too short due to the grid and gray row selection column on the left. I have the widths of the columns. What other values do I need to include in the DataGrid width? Thanx,
by: Lalit Bhatia | last post by:
Hi, In Datagrid, while setting width of column through GridColumnStyles collection. width does not set to exact width that I am setting in my code. If I set width to 13, it is changed to 130 or if set to 208, it changes to 206. On changing width of column I am resizing the width of grid. I am using mouse down and mouse up events for this. On Mouse down, I store the position and on mouse up, check the difference between positions and set...
by: Mike L | last post by:
This is for a Win form, in C# 2005. I want to load a datagrid, make some columns width 0, and then clean out the record I added. I get the error message, ""Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index"" I have tried, -1,0,1,2 for the index, and I get the same error message on each try.
by: Drew | last post by:
Hey, thanks in advance for helping me out with my problem: I have a datagrid which is embedded in another datagrid. The datagrid is filled directly by a dataset generated from a sql query. So far everything is fine. Now i try to format the embedded datagrid - e.g. setting font size and the column size/width of each column. Everything is working fine, except the width of the columns.
by: Dennis | last post by:
I am trying to align a column in DataGrid so the decimal's match up (not using fixed fonts). Is there anyone who has code for doing this using StringFormat or something else. Thanks. -- Dennis in Houston
by: Jacksm | last post by:
How can I align an asp:table columns with gridview columns (the widths)? I have tried setting table.column(0).width = gridview.column(0).width at page_load but it doesn't work. Thanks in advance
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.