My GridView :
<asp:GridView ID="GridView1" runat="server"
OnRowDataBound="GridView1_RowDataBound"
AutoGenerateColumns="true"
DataKeyNames="Role_id">
</asp:GridView>
In code behind :
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Header)
{
//e.Row.Cells[2].Width = 120; // isn't working....
}
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Cells[2].Width = new Unit(120); // isn't working....
TableCell cell = e.Row.Cells[2];
cell.HorizontalAlign = HorizontalAlign.Right; //**** does work!
cell.BackColor = Color.LightGray; //**** does work!
//cell.Width = 120; // isn't working....
//e.Row.Cells[2].Width = new Unit("120px") ; // isn't working....
//e.Row.Cells[2].CssClass = "myGV_Cell_Width"; // isn't working....
}
}
The GridView is populated successfully.
Notice that I can set the alignment and the backcolor of the column, but not its width.
I tried many solutions circulating around but none worked.
It always resizes the column to the longest content.
Can it be done at all...?
I was able to do it with the RowCreated event but I had to set the width of the grid and also set the grid to a table-layout:fixed
<asp:GridView ID="GridView1" runat="server"
style="table-layout:fixed;" Width="1000px"
OnRowCreated = "GridView1_RowCreated"
OnRowDataBound="GridView1_RowDataBound"
AutoGenerateColumns="true"
DataKeyNames="Role_id">
</asp:GridView>
protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
{
e.Row.Cells[0].Width = New Unit("220px");
}