Home / ASP.NET Wiki / HTML / Web Controls / Bind ListControl's DataValueField/TextField to multiple columns

Bind ListControl's DataValueField/TextField to multiple columns

 Rate It (12)

Concept 

A very common question asked on the ASP.NET Forums is how to bind a ListControl's DataTextField or DataValueField to multiple Columns. The classic solution to do that is to make your field(s) in the "Select" like : "select 'n°' & NumCustomer & ' : ' & NameCustomer as datatxt from <table>, <table>... etc" and to attrib it in the DataValueField = "datatxt" or/and the DataTextField = "datatxt".

But an original advanced way to do that can also be possible : The ListControl is the base class for controls such as DropDownList, ListBox, RadioButtonList, and CheckBoxList server controls. that ways to do this task will be presented in this Wiki article. The code is shown in both VB.NET and C#.NET.

 

Code 

To start with, let us add a ListBox on an ASP.NET Page as follows:

<asp:ListBox ID="lstVendors" runat="server" /> 

Then, we will add a SqlDataSource to retrieve the data from the database. The database used is the AdventureWorks DB and the table used is the Purchasing.Vendor table.

    <asp:SqlDataSource ID="SqlDataSource1" runat="server" 
        ConnectionString="<%$ ConnectionStrings:AdventureWorksConnectionString %>"
        SelectCommand="SELECT TOP 5 [ActiveFlag], [VendorID], [Name] FROM [Purchasing].[Vendor]" />

The UI is not setup, let us move to the code behind. Before doing so, notice that the ListBox doesn't specify a DataSource. This is done intentionally because the binding will be done manually in the code behind. In the page_load method of the ASP.NET page, let us add the following code:

C#.NET
protected void Page_Load(object sender, EventArgs e)
    {
        // Configure the Listbox only once, the first time
        if (!Page.IsPostBack)
        {          
            // Manually execute the SqlDataSource Select method.
            // The return value is an IEnumerable and the real return
            // value is a DataView
            DataView rows = (DataView)this.SqlDataSource1.Select(new DataSourceSelectArguments());
           
            // If there is data in the DataView
            if ((rows != null) && (rows.Count >= 1))
            {
                // Loop through the record
                for (int i = 0; i < rows.Count; i++)
                {
                    // Create a new ListItem with the:
                    // Text: VendorID
                    // Value: Name;ActiveFlag
                    ListItem li = new ListItem(
                        rows[i]["VendorID"].ToString(),
                        string.Concat(rows[i]["Name"].ToString(), ";", rows[i]["ActiveFlag"].ToString()
                        ));
                    // Add the ListItem to the lstVendors
                    this.lstVendors.Items.Add(li);
                }
            }
        }
    }

 

VB.NET
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
  ' Configure the Listbox only once, the first time
  If (Not Page.IsPostBack) Then
   ' Manually execute the SqlDataSource Select method.
   ' The return value is an IEnumerable and the real return
   ' value is a DataView
   Dim rows As DataView = CType(Me.SqlDataSource1.Select(New DataSourceSelectArguments()), DataView)
' If there is data in the DataView
   If (Not rows Is Nothing) AndAlso (rows.Count >= 1) Then
    ' Loop through the record
    For i As Integer = 0 To rows.Count - 1
     ' Create a new ListItem with the:
     ' Text: VendorID
     ' Value: Name;ActiveFlag
     Dim li As ListItem = New ListItem(rows(i)("VendorID").ToString(), String.Concat(rows(i)("Name").ToString(), ";", rows(i)("ActiveFlag").ToString()))
     ' Add the ListItem to the lstVendors
     Me.lstVendors.Items.Add(li)
    Next i
   End If
  End If
 End Sub

 

Hope this article helps you out satisfy the requirement of binding the DataTextField or DataValueField of ListControls to multiple columns.

Regards

Revision number 5, Wednesday, March 04, 2009 9:48:23 PM by fasafr

Comments

This is great, How can i add tab spaces between the 2 columns of a list item in a listbox........?

Related Articles

ASP.NET MVC Best Practices

The ASP.NET MVC is becoming more and more popular each day. As the application grows in size so does the maintenance nightmare. Following are some of the better practices, that if followed, may help maintain our application and also provides a means of scalability

Membership and Roles

"ASP.NET Membership builds on the success of the Forms authentication model from ASP.NET 1.x. ASP.NET Forms authentication provides a convenient way to incorporate a login form into your ASP.NET application and validate users against a database or other

SEO For ASP.NET Web Site

Every ASP.NET developer (or at least most of us) wants a lot of visitors to their web sites. Google, Yahoo and other search engines can send plenty of visits especially if your web site is shown on first page of their search results. And vice versa, if your

Shortcuts

Table of Contents

Top Wiki Contributors

(last 30 days)

  1. francissvk (1)
  2. deepeshsp (1)