472,344 Members | 1,981 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 472,344 software developers and data experts.

DataGrid Columns

I am using the DataGrid in a Windows Application, how can
I adjust the widths of each column individually.
Nov 19 '05 #1
2 6230

You have to add a tablestyle to your grid. When filling for your
dataset specify a tablename that will be your mappingname. ie
DataAdapter.Fill(dataset, "MappingName")
Private Sub SetupGrid()

Dim ts As New DataGridTableStyle

ts.MappingName = "InvoiceData"

Dim colDescription As New DataGridTextBoxColumn

With colDescription

..MappingName = "Description"

..HeaderText = "Description"

..Width = 280

..NullText = ""

End With

Dim colQty As New DataGridTextBoxColumn

With colQty

..MappingName = "Quantity"

..HeaderText = "Qty"

..Width = 50

End With

Dim cm As CurrencyManager = CType(Me.BindingContext(dvClient),

Dim pd As System.ComponentModel.PropertyDescriptor =

Dim colEach As New DataGridTextBoxColumn(pd, "C")

With colEach

..MappingName = "Each"

..HeaderText = "Each"

..Width = 50

End With

Dim colPrice As New DataGridTextBoxColumn(pd, "C")

With colPrice

..MappingName = "Price"

..HeaderText = "Price"

..Width = 50

End With






ts = Nothing

colPrice = Nothing

colEach = Nothing

colQty = Nothing

colDescription = Nothing

End Sub



"CSL" <co*****@kga.co.za> wrote in message
I am using the DataGrid in a Windows Application, how can
I adjust the widths of each column individually.

Nov 19 '05 #2

Lot here to try and work on thank you I will let you know how it goes......
"Joe Fallon" <jf******@nospamtwcny.rr.com> wrote in message
Here is a class you can use to inherit a standard DataGrid and then use some new properties and methods.

Option Explicit On
Option Strict On

Imports System.Drawing
Imports System.Windows.Forms

Namespace abc.xyz
Public Class MyDataGrid
Inherits DataGrid

#Region "Public Properties"
Public ReadOnly Property VerticalScrollBarVisible() As Boolean
'The VertScrollBar property of a DataGrid is Protected. The only way to access it is thru a derived class!
Return Me.VertScrollBar.Visible
End Get
End Property
#End Region

#Region "Public Methods"
Public Sub WidenRightColumn(ByRef DataGrid As MyDataGrid, ByVal dt As
DataTable, ByVal TableStyle As String)
'computes the width of the running grid and only widens the right
column if it is less than the width.
Dim numCols As Integer
numCols = dt.Columns.Count

Dim scrollBarWidth As Integer
If DataGrid.VerticalScrollBarVisible = True Then
scrollBarWidth = SystemInformation.VerticalScrollBarWidth
scrollBarWidth = 0
End If

'the fudge -4 is for the grid borders
Dim targetWidth As Integer
targetWidth = DataGrid.ClientSize.Width - scrollBarWidth - 4

Dim runningWidthUsed As Integer
runningWidthUsed = DataGrid.TableStyles(TableStyle).RowHeaderWidth
Dim i As Integer
i = 0

Do While (i < (numCols - 1)) And (runningWidthUsed < targetWidth)
runningWidthUsed +=
DataGrid.TableStyles(TableStyle).GridColumnStyles( i).Width
i += 1

If (runningWidthUsed < targetWidth) Then
DataGrid.TableStyles(TableStyle).GridColumnStyles( (numCols -
1)).Width = (targetWidth - runningWidthUsed)
End If

End Sub

'Comments on Method: AutoFitColumns
' DataGrid=DataGrid that is to be formatted.
' DataTable = DataGrid.DataSource.DataSet.Tables(0)
' NumberOfRowsToScan=Number of data records to be scanned in order to
compute the columns widths (Recommend 20).
' MaxPixelWidth=Maximum allowable pixel width of a COLUMN. (JF - Use a large number like 300.)

'The MaxPixelWidth parameter specifies the MAXIMUM value of the width
component of the returned SizeF structure
'(SizeF.Width). If the width parameter is less than the actual width of the string, the returned SizeF.Width
'component is truncated to a value representing the maximum number of
characters that will fit within the specified width.

'Takes a DataGrid that should be already assigned a populated dataset,
'and formats the DataGrid so that the column widths reflect the widths
of the data.
'This is accomplished by dynamically creating a single
DataGridTableStyle and multiple DataGridTextBoxColumn(s).
'For each data column, the width of the column is set to the highest
data width within the column.
'In order to reduce computation time where large datasets exist,
'a parameter exists to define how many rows are scanned.
'I would suggest that only the first 20 rows are scanned.

Public Sub AutoFitColumns(ByRef DataGrid As MyDataGrid, ByVal dt As
DataTable, ByVal TableStyle As DataGridTableStyle, _
ByVal NumberOfRowsToScan As Integer, ByVal
MaxColumnWidth As Integer)
Dim HideColumns() As String = {""}
AutoFitColumns(DataGrid, dt, TableStyle, NumberOfRowsToScan,
MaxColumnWidth, HideColumns)
End Sub

Public Sub AutoFitColumns(ByRef DataGrid As MyDataGrid, ByVal dt As
DataTable, ByVal TableStyle As DataGridTableStyle, _
ByVal NumberOfRowsToScan As Integer, ByVal
MaxColumnWidth As Integer, ByVal HideColumns() As String)
'Create graphics object for measuring widths.
Dim Graphics As Graphics = DataGrid.CreateGraphics()
'Can only scan rows if they exist.
NumberOfRowsToScan = System.Math.Min(NumberOfRowsToScan,

'Now loop through the columns and set the widths.
Dim Column As DataColumn
Dim ColumnStyle As DataGridColumnStyle
Dim Width As Integer
For Each Column In dt.Columns
ColumnStyle = TableStyle.GridColumnStyles(Column.ColumnName)

If Not ColumnStyle Is Nothing Then
If HideColumns.IndexOf(HideColumns, Column.ColumnName) >= 0 Then 'hide all columns in the HideColumns array
ColumnStyle.Width = 0
'Set width to header text width.
Width = CInt(Graphics.MeasureString(ColumnStyle.HeaderText ,
DataGrid.Font, MaxColumnWidth).Width)
'Change width, if data width is wider than header text width. 'Check the width of the data in the first X rows.
Dim iRow As Integer
Dim dr As DataRow
For iRow = 0 To NumberOfRowsToScan - 1
dr = dt.Rows(iRow)
If Not IsDBNull(dr(Column.ColumnName)) Then
Width = CInt(System.Math.Max(Width,
Graphics.MeasureString(CStr(dr(Column.ColumnName)) , DataGrid.Font,
End If
'ColumnStyle.Width = Width + 4
'increase width from 4 to 20 to allow for the Sort arrow when a column header is clicked on.
ColumnStyle.Width = Width + 20
End If
End If
End Try
End Sub

Public Sub MakeColumnsReadOnly(ByRef DataGrid As MyDataGrid, ByVal
TableName As String, ByVal ReadOnlyColumns() As String)
Dim ColName As String
For Each ColName In ReadOnlyColumns
DataGrid.TableStyles(TableName).GridColumnStyles(C olName).ReadOnly = True
Next ColName
End Sub

#End Region

End Class
End Namespace
Sample code to use the class in a Windows Form with a MyDataGrid on it:

'define a list of columns to make ReadOnly
Dim ReadOnlyColumns() As String = {"field1", "field2"}

'define a list of columns to Hide
Dim HideColumns() As String = {"field3", "field4"}

tableStyle.MappingName = strTableName
tableStyle.AlternatingBackColor = Bisque

'see below for another class to change the color of READ ONLY fields.
Dim MyColoredColumn As DataGridColoredTextBoxColumn
Dim i As Integer
Do While i < dsMain.Tables(strTableName).Columns.Count
MyColoredColumn = New DataGridColoredTextBoxColumn
MyColoredColumn.HeaderText =
MyColoredColumn.MappingName =
End If
i += 1

With DataGrid1
.DataSource = ds
.DataMember = "dtName"
.AllowNavigation = False
.MakeColumnsReadOnly(DataGrid1, strTableName, ReadOnlyColumns)
.AutoFitColumns(DataGrid1, ds.Tables(strTableName), tableStyle, 20, 300, HideColumns)
.WidenRightColumn(DataGrid1, ds.Tables(strTableName), strTableName) End With
To make the read only columns a different color you need another class:

Option Explicit On
Option Strict On

Imports System.Drawing
Imports System.Drawing.Drawing2D
Imports System.Windows.Forms

Namespace xyz.abc
Public Class DataGridColoredTextBoxColumn
Inherits DataGridTextBoxColumn

#Region "Constructor"
Public Sub New()
'do nothing
End Sub
#End Region

#Region "Public Methods"
Protected Overloads Overrides Sub Paint(ByVal g As Graphics, ByVal
bounds As Rectangle, ByVal source As CurrencyManager, ByVal rowNum As
Integer, ByVal backBrush As Brush, ByVal foreBrush As Brush, ByVal
alignToRight As Boolean)
' the idea is to conditionally set the foreBrush and/or backbrush
depending upon some criteria on the cell value
' Here, we color any cell that is Read Only.
If Me.ReadOnly = True Then
'could be as simple as
'backBrush = New SolidBrush(Color.Aqua)
'or something fancier
backBrush = New LinearGradientBrush(bounds, Color.FromArgb(255,
200, 200), Color.FromArgb(128, 20, 20), LinearGradientMode.BackwardDiagonal) foreBrush = New SolidBrush(Color.White)
End If
'make sure the base class gets called to do the drawing with the
possibly changed brushes
MyBase.Paint(g, bounds, source, rowNum, backBrush, foreBrush,
End Try
End Sub
#End Region

End Class

End Namespace
Joe Fallon

"CSL" <co*****@kga.co.za> wrote in message
I am using the DataGrid in a Windows Application, how can
I adjust the widths of each column individually.

Nov 20 '05 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

by: Reb | last post by:
I am using a datagrid within another datagrid. My second datagrid is expand/collapse one. I am facing some error. This is my code. ...
by: Josef Meile | last post by:
Hi, I'm using a ComboBox, some Textboxes, and a DataGrid to represent a many-to-many relationship between Person and Course. Each time that I...
by: Amber | last post by:
The DataGrid allows you to make columns visible or invisible on demand - even edit and other special columns. This article will show you how it is...
by: Jim Heavey | last post by:
Trying to figure out the technique which should be used to add rows to a datagrid. I am thinking that I would want an "Add" button on the footer,...
by: tshad | last post by:
I am having trouble with links in my DataGrid. I have Links all over my page set to smaller and they are consistant all over the page in both...
by: CanoeGuy | last post by:
I have been trying for the last two weeks to display a dynamic DataGrid. The data that I'm pulling from a SQL Server DB will have whole columns...
by: jimb | last post by:
I can get the dropdownlist into the datagrid, and I can populate it, but I can't read it. Anybody have a working example of a dropdownlist in an...
by: Arpan | last post by:
Assume that a database table has the following 4 columns - ID, UserID, Subject & Marks. I am retrieving the records existing in this DB table &...
by: rn5a | last post by:
A SqlDataReader is populated with the records from a SQL Server 2005 DB table. The records retrieved depends upon 2 conditions (the conditions...
by: Kemmylinns12 | last post by:
Blockchain technology has emerged as a transformative force in the business world, offering unprecedented opportunities for innovation and...
by: Naresh1 | last post by:
What is WebLogic Admin Training? WebLogic Admin Training is a specialized program designed to equip individuals with the skills and knowledge...
by: jalbright99669 | last post by:
Am having a bit of a time with URL Rewrite. I need to incorporate http to https redirect with a reverse proxy. I have the URL Rewrite rules made...
by: antdb | last post by:
Ⅰ. Advantage of AntDB: hyper-convergence + streaming processing engine In the overall architecture, a new "hyper-convergence" concept was...
by: Matthew3360 | last post by:
Hi there. I have been struggling to find out how to use a variable as my location in my header redirect function. Here is my code. ...
by: Arjunsri | last post by:
I have a Redshift database that I need to use as an import data source. I have configured the DSN connection using the server, port, database, and...
by: WisdomUfot | last post by:
It's an interesting question you've got about how Gmail hides the HTTP referrer when a link in an email is clicked. While I don't have the specific...
by: Matthew3360 | last post by:
Hi, I have been trying to connect to a local host using php curl. But I am finding it hard to do this. I am doing the curl get request from my web...
by: Oralloy | last post by:
Hello Folks, I am trying to hook up a CPU which I designed using SystemC to I/O pins on an FPGA. My problem (spelled failure) is with the...

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.