views:

53

answers:

2

I have a datatable binded with gridview and I want to change the column width. This it the code I use:

DataTable aTable = new DataTable("Words"); 
aTable.Columns.Add("word");

GridView1.DataSource = aTable;
DataRow a = aTable.NewRow();
a[0] = "test";
aTable.Rows.Add(a);
GridView1.DataBind();

GridView1.Columns[0].ItemStyle.Width = Unit.Pixel(200);

When the execution gets to the last line it produces an error saying that the column with index 0 is not found, howerver it is in the datatable and it is shown in the webpage.

Why doesn't the gridview see the column and is there a way around this?

A: 

I'd try placing this in the grid view's prerender event. You may be trying to do this in the wrong spot.

EDIT Try adding this before your statement:

if(GridView1.Columns.Count > 0)
//do stuff here
Aaron
The error still remains if put in the GridView1_PreRender function.
Desecho
GridView1.Columns.Count is in fact 0. This is the actual problem. The question is why is that so and how can I fix it.
Desecho
A: 

The column count will always be 0 unless you explicitly define <columns> in your gridview.

You are autogenerating. So use <columns> with <asp:BoundField DataField="word" />and it will work.

Alan Stephens
When I do that and bind it with my datatable it displays 2 equal columns. It doesn't merge the columns into one, it clones them. How can I fix that?
Desecho
the markup is thus<asp:GridView runat="server" ID="GridView1" AutoGenerateColumns="false" ShowHeader="false"> <Columns> <asp:BoundField DataField="word" /> </Columns> </asp:GridView>works a treat
Alan Stephens
I didn't have this attribute - AutoGenerateColumns="False". I have not thought of that. Silly me. Thanks a lot for your help!
Desecho