473,395 Members | 1,473 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

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

DataGrid Columns

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

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),
CurrencyManager)

Dim pd As System.ComponentModel.PropertyDescriptor =
cm.GetItemProperties()("Each")

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.GridColumnStyles.Add(colDescription)

ts.GridColumnStyles.Add(colQty)

ts.GridColumnStyles.Add(colEach)

ts.GridColumnStyles.Add(colPrice)

dgInvoiceData.TableStyles.Add(ts)

ts = Nothing

colPrice = Nothing

colEach = Nothing

colQty = Nothing

colDescription = Nothing

End Sub

Ken

---------

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

Nov 19 '05 #2
Joe,

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
news:Or**************@TK2MSFTNGP11.phx.gbl...
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
Get
'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
Else
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
Loop

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

End Sub

'Comments on Method: AutoFitColumns
'Parameters
' 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()
Try
'Can only scan rows if they exist.
NumberOfRowsToScan = System.Math.Min(NumberOfRowsToScan,
dt.Rows.Count)

'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
Else
'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,
MaxColumnWidth).Width))
End If
Next
'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
Next
Finally
Graphics.Dispose()
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 =
ds.Tables(strTableName).Columns(i).ColumnName
MyColoredColumn.MappingName =
ds.Tables(strTableName).Columns(i).ColumnName
tableStyle.GridColumnStyles.Add(MyColoredColumn)
End If
i += 1
Loop

With DataGrid1
.TableStyles.Clear()
.TableStyles.Add(tableStyle)
.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.
Try
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
Finally
'make sure the base class gets called to do the drawing with the
possibly changed brushes
MyBase.Paint(g, bounds, source, rowNum, backBrush, foreBrush,
alignToRight)
End Try
End Sub
#End Region

End Class

End Namespace
--
Joe Fallon

"CSL" <co*****@kga.co.za> wrote in message
news:0c****************************@phx.gbl...
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

0
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. ExpandGrid.aspx <form id="Form1" method="post"...
2
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 change the value in the ComboBox (which for now is...
1
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 done. Some developers have reported problems...
3
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, but I am not quite sure how to do that. Is that...
4
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 Mozilla and IE, except for the DataGrid. Here is a...
7
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 that will be either NULL or 0. I want to display...
1
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 editable grid? Thanks. -- .....
7
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 & displaying them in a DataGrid like this: <script...
3
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 depend on what a user selects in an ASPX page). If...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
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...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...

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.