How to set width of Column in Gridview Control?
By default width of column handled automatically, means columns in Gridview control are sized automaticlaly internally column cells redered as HTML cell. On the basis of requirement one can set the width dynamically also.
Following are the steps to do it;
1. Setting Column Width Dynamically:
Through code, set the width property on the ItemStyle of GridView.
Following is the code-snippet for the same:
VB.NEt:
Dim intColWidth As Integer = 25
GridView1.Columns(0).ItemStyle.Width = intColWidth
C#:
int intColWidth = 25;
GridView1.Columns(0).ItemStyle.Width = intColWidth;
2. Setting Column width as per Data-Content :
Write following piece of code in RowDataBound handler / event:
Note: Code is taken from MSDn for reference purpose only:
VB.NET:
Protected widestData As Integer
Protected Sub GridView1_RowDataBound(ByVal sender As Object, _
ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs)
Dim drv As System.Data.DataRowView
drv = CType(e.Row.DataItem, System.Data.DataRowView)
If e.Row.RowType = DataControlRowType.DataRow Then
If drv IsNot Nothing Then
Dim catName As String = drv(1).ToString()
Dim catNameLen As Integer = catName.Length
If catNameLen > widestData Then
widestData = catNameLen
GridView1.Columns(2).ItemStyle.Width = _
widestData * 30
GridView1.Columns(2).ItemStyle.Wrap = False
End If
End If
End If
End Sub
Protected Sub Page_Load(ByVal sender As Object, _
ByVal e As System.EventArgs) Handles Me.Load
widestData = 0
End Sub
C#:
protected int widestData;
protected void GridView1_RowDataBound(object sender, System.Web.UI.WebControls.GridViewRowEventArgs e)
{
System.Data.DataRowView drv = default(System.Data.DataRowView);
drv = (System.Data.DataRowView)e.Row.DataItem;
if (e.Row.RowType == DataControlRowType.DataRow) {
if (drv != null) {
string catName = drv(1).ToString();
int catNameLen = catName.Length;
if (catNameLen > widestData) {
widestData = catNameLen;
GridView1.Columns(2).ItemStyle.Width = widestData * 30;
GridView1.Columns(2).ItemStyle.Wrap = false;
}
}
}
}
protected void  // ERROR: Handles clauses are not supported in C#
Page_Load(object sender, System.EventArgs e)
{
widestData = 0;
}
Popularity: unranked [?]
Related interview questions
- DB2 : SQL Codes and Description
- In which column of which DB2 catalog would you find the length of rows for all tables?
- How to add flash movie in my project?
- Difference between Clone, Close and Dispose methods of Crystal Report?
- Write query to get custom results











Leave your response!
You must be logged in to post a comment.