How to set Gridview column width dynamically in Asp.Net C#
In this article, I will show you how to set column-
width of gridview in asp.net .We can use several methods to achieve it just
like source code (grid view property), code behind(C#) and CSS.
First Method:-
we can set the columns width by using ItemStyle-Width property just like
below :-
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="Name" HeaderText="Name" ItemStyle-Width="50px" />
<asp:BoundField DataField="Contactno" HeaderText="Contactno" ItemStyle-Width="50px" />
<asp:BoundField DataField="Brithday" HeaderText="Brithday" ItemStyle-Width="50px" />
</Columns>
</asp:GridView>
Second Method:-
We can call the columns’s width from code behind
just like below :-
For this code we need to need to call RowDataBound.
protected void GridView1_RowDataBound(object
sender, GridViewRowEventArgs e)
{
if
(e.Row.RowType == DataControlRowType.DataRow)
{
GridView1.Columns[0].ItemStyle.Width = 50;
GridView1.Columns[1].ItemStyle.Width = 50;
GridView1.Columns[2].ItemStyle.Width = 50;
}
}
Third method:-
We can set the column width using css but we call
this call on only code behind because we can not directly call the css in
column from source code and if we call on this gridview then it will be set
whole gridview width not the columns. We can use this method like below:-
Source code:-
<style type="text/css">
.columnwidth
{
width:
50px;
}
</style>
Codebehind:-
protected void GridView1_RowDataBound(object
sender, GridViewRowEventArgs e)
{
if
(e.Row.RowType == DataControlRowType.DataRow)
{
for
(int i = 0; i > e.Row.Cells.Count; i++)
{
e.Row.Cells[i].CssClass = "columnwidth";
}
}
}
How to set Gridview column width dynamically in Asp.Net C#
Reviewed by NEERAJ SRIVASTAVA
on
11:36:00 AM
Rating:
No comments: