Article Options
Premium Sponsor
Premium Sponsor

 »  Home  »  Web Development  »  Using ASP.NET DataGrid Web Server Control  »  DataGrid columns creation
 »  Home  »  Web Development  »  ASP.NET  »  Using ASP.NET DataGrid Web Server Control  »  DataGrid columns creation
Using ASP.NET DataGrid Web Server Control
by Misha Zhutov | Published  11/03/2005 | Web Development ASP.NET | Rating:
DataGrid columns creation

DataGrid has different column types which determine the behavior of the columns in the control, such as BoundColumn, ButtonColumn, EditCommandButton, HyperLinkColumn and TemplateColumn.
In this demonstration I used a TemplateColumn type which provides the most freedom in customization. This alloww you to use any controls inside a data row.
TemplateColumn has its own layout tuning and two different set of controls for view and edit mode.
Let’s take a look at the HTML code in the ASPX page that creates the DataGrid columns:

<asp:TemplateColumn ItemStyle-Wrap="true" 
HeaderText="Product Name">

    <asp:Label id=Label3 runat="server"
Text='<%# DataBinder.Eval(Container, "DataItem.ProductName") %>'>
    <asp:RequiredFieldValidator id="RequiredFieldValidator1"
  ErrorMessage="Product name is empty."
Product name is empty.

    <asp:TextBox id="ProductNameTextBox" Width="110"
MaxLength="40" runat="server"
Text='<%# DataBinder.Eval(Container, "DataItem.ProductName") %>'>
    <asp:Label id="ProductIDLabel" runat="server" Visible=False
Text='<%# DataBinder.Eval(Container, "DataItem.ProductID") %>'>

As we see here, the column has two different control sets – Label for viewing mode and TextBox with a validator for edit mode. Required validator prevents the user from leaving a field empty when editing and will be described below.
Some columns are bound on table columns that have relationships with another tables. For such purposes, I used a DropDownList control in edit mode that bounded on relation table.
Let’s take a look at the HTML code that sets up a DropDownList control in edit mode:

<asp:TemplateColumn SortExpression="CategoryID" HeaderText="Category">
    <asp:Label id="Label33" runat="server" Width="150"
Text='<%# GetCategoryName(DataBinder.Eval(Container, _
    <asp:DropDownList id="CategoryDropDownList"
DataSource=<%# Categories%
SelectedValue=<%# DataBinder.Eval(Container, "DataItem.CategoryID")%>
Width="150" runat="server">

After clicking the Edit link, the user is presented with a pre-populated DropDownList, which looks  like this:

Sponsored Links