DataGrid – Changing the Column Size

Sometimes, it may become necessary to make a DataGrid column more narrow, or wider. This code sample, using the Northwind Database in SQL Server, uses the Employees database to show you just that.

To use this yourself, just copy the code to a new file, change the connection string/database info and you’ve got a running sample!

lt;%@ Import Namespace=”System.Data” %>
<%@ Import Namespace=”System.Data.SQLClient” %>
<html>
<head>
<meta name=”GENERATOR” Content=”ASP Express 2.0″>
<title>Change DataGrid Column Size</title>
<script language=”VB” runat=”server”>
Sub Page_Load(Source as Object, E as EventArgs)

if not Page.IsPostBack then
Dim strConn as string = “server=(local);uid=UserID;pwd=Password;database=Northwind”
Dim sql as string = “Select FirstName, LastName from Employees”
Dim conn as New SQLConnection(strConn)
Dim ds as DataSet=New DataSet()
Dim Cmd as New SQLDataAdapter(sql,conn)
Cmd.Fill(ds,”Employees”)
MyDataGrid.Datasource=ds.Tables(“Employees”).DefaultView
MyDataGrid.DataBind()

end if
End Sub
Sub changesize(Source as Object, E as EventArgs)
Dim intSize as integer
intSize=size.selecteditem.text
MyDataGrid.Columns(0).ItemStyle.Width=Unit.percentage(intSize)
End Sub

</script>
</head>
<body>
<form runat=”server” method=”post”>
<asp:Datagrid runat=”server”
Id=”MyDataGrid”
GridLines=”Both”
cellpadding=”0″
cellspacing=”0″
Headerstyle-BackColor=”#8080C0″
Headerstyle-Font-Name=”Arial”
Headerstyle-Font-Bold=”True”
Headerstyle-Font-Size=”8″
BackColor=”#8080FF”
Font-Name=”Arial”
Font-Bold=”True”
Font-Size=”8″
width=”100%”
BorderColor=”Black”
AutogenerateColumns=”False”>
<Columns>
<asp:BoundColumn DataField=”FirstName” SortExpression=”FirstName” HeaderText=”FirstName”></asp:BoundColumn>
<asp:BoundColumn DataField=”LastName” SortExpression=”LastName” HeaderText=”LastName”></asp:BoundColumn>
</Columns>
</asp:DataGrid>

<asp:dropdownlist id=”size” runat=”server”>
<asp:listitem selected=”true”>10</asp:listitem>
<asp:listitem>20</asp:listitem>
<asp:listitem>30</asp:listitem>
<asp:listitem>50</asp:listitem>
</asp:dropdownlist><b>% </b> <asp:Button id=”button1″ Text=”change size” onclick=”changesize” runat=”server” />
</form>
</body>
</html>

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>