I am using ASP.NET C# on VS2005.
I have a GridView table with a column named Description
, and since the input is always very long, the description is very long horizontally.
I would want the GridView to have a max width size for all columns.
I have tried many ways but none of them worked.
ItemStyle-Width="50px"
,
HeaderStyle-BorderWidth="50px"
,
HeaderStyle-Width="50px"
,
RowStyle-Width="50px"
,
Width="50px"
Below is a code snippet of my GridView:
<asp:GridView ID="GridView1" AutoGenerateEditButton="True" ondatabound="gv_DataBound" runat="server" DataSourceID="SqlDataSource1">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="UserSelector" OnCheckedChanged="UserSelector_CheckedChanged" ondatabound="gv_DataBound" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Anyone know how to adjust the size of GridView columns based on my situation?
This is how I control the column width.
1.Add the CSS in the header.
<style type="text/css">
.maxWidthGrid
{
max-width: 300px;
overflow: hidden;
}
</style>
2.Then use the CSS in necessary columns like this ItemStyle-CssClass="maxWidthGrid"
<asp:BoundField ItemStyle-CssClass="maxWidthGrid" DataField="ClientName" HeaderText="Client Name"
ReadOnly="True" SortExpression="ClientName" />
I changed my code is this what you where thinking bout?
<RowStyle Width="150px"/>
Remove all the stash
<asp:TemplateField><ItemTemplate> </ItemTemplate></asp:TemplateField>
and just use simple
<columns> </columns>
Here i how i think you code will look like AutoGenerateColumns="True" or false dont seeme to matter
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="true" DataSourceID="SqlDataSource1">
<Columns>
<asp:CheckBox ID="UserSelector" OnCheckedChanged="UserSelector_CheckedChanged" ondatabound="gv_DataBound" runat="server" />
</Columns>
<RowStyle Width="150px"/>
</asp:GridView>
you can handle the RowDataBound
event.
protected int widestData;
protected void GridView1_RowDataBound(object sender,
GridViewRowEventArgs e)
{
System.Data.DataRowView drv;
drv = (System.Data.DataRowView)e.Row.DataItem;
if (e.Row.RowType == DataControlRowType.DataRow)
{
if (drv != null)
{
String catName = drv[1].ToString();
Response.Write(catName + "/");
int catNameLen = catName.Length;
if (catNameLen > widestData)
{
widestData = catNameLen;
GridView1.Columns[2].ItemStyle.Width =
widestData * 30;
GridView1.Columns[2].ItemStyle.Wrap = false;
}
}
}
}
protected void Page_Load(object sender, EventArgs e)
{
widestData = 0;
}
Check this How to: Set GridView Web Server Control Column Width Dynamically for more detailed information.
if your gridview autogeneratecolumns
property is set to false and you are creating custom columns
then you can use templatefileds
where you can implement Table
and Div
to control the width of the columns.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With