Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Gridview column width (index out of range) 1

Status
Not open for further replies.

cawthor2

Programmer
May 2, 2002
10
0
0
US
Hi,

I've bound a datatable to a gridview and am trying to change the column width. The data is displayed correctly in the gridview, but I'm having trouble changing the width of a column.

After I've bound the datatable, I have the following code:

GridView1.DataSource = dt
GridView1.DataBind()

GridView1.Columns(1).ItemStyle.Width = 100

I receive the following error:

Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index

 
Try putting that line of code in the gridview's RowCreated event.
 
Added onrowcreated="GridView_RowCreated" to my GridView declaration, and created the following sub:

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

GridView1.Columns(1).ItemStyle.Width = 100

End Sub

Still get the same error.
 
Also, If I do a 'GridView1.Columns.Count', it returns 0?
 
The problem is that you are not defining the columns ahead of time, you are binding to the datatable to the grid. So, yes, the columns.count will return 0 even after the grid is bound. I had the same issue and found that out.
You will either have to define the columns in the UI to use the syntax you have, OR
Code:
    Protected Sub GridView1_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView1.RowDataBound
        If e.Row.RowType = DataControlRowType.Header Then
            e.Row.Cells(1).Attributes.Add("style", "width: 100px;")
        End If
    End Sub
 
Thank you for your response and explanation. I'll give your solution a try.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top