Home > Articles > C# Articles > Set Gridview column width dynamically using C#

Set Gridview column width dynamically using C#

by Thamil   on Oct 09, 2014   Category: C#  | Level: Beginner  |  Views: 25919    |  Points: 100   
Like this article? Bookmark and Share:
In this article, I will explain how to set the gridview column width dynamically.


Generally we know the list of column details which are going to bind with gridview control, in this case we set the AutoGenerateColumns="false" and assign the column names in Datafield property as like below and set column width in ItemStyle-Width property.

<asp:GridView ID="GVEmp" AutoGenerateColumns="False" runat="server">


<asp:BoundField DataField="NAME" HeaderText="Name" ItemStyle-Width="200px" />

<asp:BoundField DataField="DEPARTMENT" HeaderText="Job" ItemStyle-Width="200px"/>




Set Column width

Now we are going to bind the columns dynamilcally with gridview so AutoGenerateColumns must be true as like below and there is no columns defined in the gridview control.

<asp:GridView ID="GVEmp" AutoGenerateColumns="true" runat="server"




Code behind part:

We can able to achieve this setting column/header width by using gridview rowdatabound event, so add the onrowdatabound="GVEmp_RowDataBoun" event in the gridview and set the column/header width as like  below.

protected void GVEmp_RowDataBound(object sender, GridViewRowEventArgs e)


if (e.Row.RowType == DataControlRowType.Header)


e.Row.Cells[0].Width = new Unit("300px");

e.Row.Cells[1].Width = new Unit("250px");



Gridview binding:

protected void Page_Load(object sender, EventArgs e)


GVEmp.DataSource = GetData();




private DataTable GetData()


DataTable dtEmp = new DataTable("Emp");

DataColumn Name = new DataColumn("Name", typeof(System.String));

DataColumn Dept = new DataColumn("Department", typeof(System.String));

dtEmp.Columns.AddRange(new DataColumn[] { Name, Dept });

dtEmp.Rows.Add("Ricki", "Information Technoloy");

dtEmp.Rows.Add("Loretta", "Finance Control");

dtEmp.Rows.Add("Sebastianne", "Customer Care");

return dtEmp;


Thanks for reading, I hope you enjoyed this article.

Like this article? Bookmark and Share:

Most viewed Articles

User Comments

No response found, be the first to review this article.

Submit feedback about this article

Please sign in to post feedback

Latest Posts