Pages

Sunday, January 20, 2013

Asp.net SetGridview Column Width Dynamically in C#, VB.NET

Introduction: Here I will explain how to set gridview column width in asp.net or set gridview column width dynamically in asp.net using C# and VB.NET. Description: In previous articles I explained Asp.net Interview questions, Export Gridview data to PDF, Send values from one page to another page using QueryString, Joins in SQL Server, Highlight Gridview records based on search and many articles relating to Gridview, SQL ,jQuery,asp.net, C#,VB.NET. Now I will explain how to set gridview column width dynamically in asp.net using C# and VB.NET. Method 1: Suppose if our gridview property AutoGenerateColumns="false" then we can set the columns width by using ItemStyle-Width property like as shown below Method 2: Suppose if we are binding columns dynamically to gridview then we need to write the code like as shown below to set width for required columns C# Code protected void GrdView_RowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow) { grdListings.Columns[1].ItemStyle.Width = 50; grdListings.Columns[2].ItemStyle.Width = 150; } } VB.NET Code Protected Sub GrdView_RowDataBound(sender As Object, e As GridViewRowEventArgs) If e.Row.RowType = DataControlRowType.DataRow Then grdListings.Columns(1).ItemStyle.Width = 50 grdListings.Columns(2).ItemStyle.Width = 150 End If End Sub Method 3: We can set the columns width by using CSS calss also for that first we need to write the css class in aspx page like shown below Once we create css class in aspx then we need to write the following code in code behind C# Code protected void GrdView_RowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow) { grdListings.Columns[1].ItemStyle.Width = 50; grdListings.Columns[2].ItemStyle.Width = 150; for (int i = 1; i > e.Row.Cells.Count; i++) { e.Row.Cells[i].CssClass = "columnscss"; } } } VB.NET Code Protected Sub GrdView_RowDataBound(sender As Object, e As GridViewRowEventArgs) If e.Row.RowType = DataControlRowType.DataRow Then grdListings.Columns(1).ItemStyle.Width = 50 grdListings.Columns(2).ItemStyle.Width = 150 Dim i As Integer = 1 While i > e.Row.Cells.Count e.Row.Cells(i).CssClass = "columnscss" i += 1 End While End If End Sub Source: http://www.aspdotnet-suresh.com/2013/01/aspnet-set-gridview-column-width.html

No comments:

Post a Comment