2

Need to set the column width of a gridview in asp.net programmatically. ** Autogenerated Columns (i.e., AutogenerateColumns = "true").

I tried the following;

protected void gv_RowCreated(object sender, GridViewRowEventArgs e) { e.Row.Cells[2].Width = Unit.Pixel(200); } 

but no use.

1
  • I'll answer with what I've done when I needed to set gridview column width programmatically.But I did not have AutogeneratedColumns=True Commented Jun 11, 2012 at 12:55

1 Answer 1

7

This is my GridView1 on aspx file

<asp:GridView ID="GridView1" runat="server" AllowSorting="True" Font-Size="Small" Width="800px" OnRowDataBound="GridView1_RowDataBound" > <Columns> <asp:CommandField SelectText="Seç" ShowSelectButton="True"/> </Columns> </asp:GridView> 

This is where I set my GridView's column width programmatically in codebehind.It is actually about setting the cell's width but it controls the column width so this is a way.As you can see I do not have AutogeneratedColumns="True", though I do not think that would matter because GridView.RowDataBound occurs when a data row is bound to data.

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) { e.Row.Cells[1].Width = 1; e.Row.Cells[0].Width = 1; e.Row.Cells[4].Width = 75; e.Row.Cells[5].Width = 1; } 
Sign up to request clarification or add additional context in comments.

3 Comments

I got ArgumentOutOfRangeException; Specified argument was out of the range of valid values. Parameter name: index
Here is the code ' protected void gv_RowDataBound(object sender, GridViewRowEventArgs e) { e.Row.Cells[1].Width = 200; }'
how are you binding data to your gridview?This event fires when data is bound to your gridview, if you do not have any data bound to it you will get that exception because e.Row.Cells[number] will not exist.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.