Click here to Skip to main content
15,881,882 members
Articles / Web Development / ASP.NET
Article

Bind ListControl's DataValueField/TextField to multiple columns

Rate me:
Please Sign up or sign in to vote.
0.00/5 (No votes)
11 Oct 2013CPOL1 min read 11.2K   1  
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

This articles was originally at wiki.asp.net but has now been given a new home on CodeProject. Editing rights for this article has been set at Bronze or above, so please go in and edit and update this article to keep it fresh and relevant.

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" <br />        ConnectionString="<%$ ConnectionStrings:AdventureWorksConnectionString %>" <br />        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)<br />    {<br />        // Configure the Listbox only once, the first time<br />        if (!Page.IsPostBack)<br />        {           <br />            // Manually execute the SqlDataSource Select method.<br />            // The return value is an IEnumerable and the real return<br />            // value is a DataView<br />            DataView rows = (DataView)this.SqlDataSource1.Select(new DataSourceSelectArguments());<br />            <br />            // If there is data in the DataView<br />            if ((rows != null) && (rows.Count >= 1))<br />            {<br />                // Loop through the record<br />                for (int i = 0; i < rows.Count; i++)<br />                {<br />                    // Create a new ListItem with the:<br />                    // Text: VendorID<br />                    // Value: Name;ActiveFlag<br />                    ListItem li = new ListItem(<br />                        rows[i]["VendorID"].ToString(),<br />                        string.Concat(rows[i]["Name"].ToString(), ";", rows[i]["ActiveFlag"].ToString()<br />                        ));<br />                    // Add the ListItem to the lstVendors<br />                    this.lstVendors.Items.Add(li);<br />                }<br />            }<br />        }<br />    }

 

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

 

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

Regards

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
United States United States
The ASP.NET Wiki was started by Scott Hanselman in February of 2008. The idea is that folks spend a lot of time trolling the blogs, googlinglive-searching for answers to common "How To" questions. There's piles of fantastic community-created and MSFT-created content out there, but if it's not found by a search engine and the right combination of keywords, it's often lost.

The ASP.NET Wiki articles moved to CodeProject in October 2013 and will live on, loved, protected and updated by the community.
This is a Collaborative Group

754 members

Comments and Discussions

 
-- There are no messages in this forum --