Setting GridVIew column widths at runtime

G

Guest

Hi,

I would like to set the column widths in the ASP.NET GridView control at
runtime

I have tried the following:
http://msdn2.microsoft.com/en-us/library/ms178296.aspx
Which uses the following code on a button:

Protected Sub Button1_Click(ByVal sender As Object, _
ByVal e As System.EventArgs)
Try
Dim colWidth As Integer
colWidth = CInt(Server.HtmlEncode(TextBox1.Text))
If colWidth > 0 Then
For i As Integer = 0 To GridView1.Columns.Count - 1
GridView1.Columns(i).ItemStyle.Width = colWidth
Next
End If
Catch
' Report error.
End Try
End Sub

But the count on the columns collection returns 0.

I have tried putting the code immediately before and after the databind but
that doesn't work either.

Could someone please tell me what I am doing wrong?

Regards

Steve
 
G

Guest

If your GridView is creating the columns using the AutoGenerateColumns=true
then the Columns collection would not have them.

http://msdn2.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.columns.aspx
"Explicitly declared column fields can be used in combination with
automatically generated column fields. When both are used, explicitly
declared column fields are rendered first, followed by the automatically
generated column fields. Automatically generated column fields are not added
to the Columns collection."
 
T

Teemu Keiski

They should be capable to set in autogenerating scenario also if one handles
RowCreated event and sets cell width explicitly in code.
 
G

Guest

Hello Phillip and Teemu,

THankyou for your repllies.

I tried putting the code in the rowcreated event but that didn't work either.

I am binding to a datatable, whose structure is determined at runtime.
Therefore the autogeneratecolumns has to be set true.

Does anyone have any other ideas as to how I can set the widths?

Steve
 
G

Guest

During the RowCreated event you can loop through the Row.Cells collection (to
get the equivalent of the GridView.Columns collection), e.g.

Sub GridView1_RowCreated(ByVal sender As Object, ByVal e As
GridViewRowEventArgs)

If e.Row.RowType = DataControlRowType.DataRow Then
dim td as TableCell
For each td in e.Row.Cells
'set the td style to the desired width
Next For
End If
End Sub
 
G

Guest

Thankyou Phillip. That works perfectly.

I was using the wrong collection ie
For r As Integer = 0 To grdViewEnteredData.Columns.Count - 1
grdViewEnteredData.Columns(r).ItemStyle.Width = 100
grdViewEnteredData.Columns(r).ItemStyle.Wrap = True
Next
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,982
Messages
2,570,185
Members
46,737
Latest member
Georgeengab

Latest Threads

Top