ASP.Net DropDownList DataTextField Multiple Columns

Updated on 04 Jul 2012,
Published on 29 Oct 2009

Is it really possible to specify the multiple column names to the DataTextField property of ASP.Net DropDownList control? As per the definition of DataTextField property it is meant for single data field only. You can also verify according to the naming standards that the property name denotes singular voice i.e. DataTextField that also shows that it can support only one value. All these points determine that you cannot specify the multiple columns for this property of DropDownList control. It you will try to do so then it will throw an error of DataBinding i.e. "DataBinding: 'System.Data.DataRowView' does not contain a property with the name . . ."

If there is a requirement that needs to display multiple column values for each record retrieved from the SQL database or any datasource then you can do it by applying your own logic. In this tutorial we have used the SqlDataReader to display the multiple column values as a text content of each list item of ASP.Net DropDownList control.

Sample Code Display Multiple Column Values in DropDownList Control

HTML Code
<asp:DropDownList ID="DropDownList1" 
    runat="server" 
    AutoPostBack="True" 
    OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged">
</asp:DropDownList>
<br />
<asp:Label ID="Label1" runat="server"></asp:Label>
C# Code
protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
        BindDropDownListData();
}

public void BindDropDownListData()
{
    // connection string
    string connectionString = ConfigurationManager.ConnectionStrings["NorthwindConnectionString"].ConnectionString;

    // Sql connection object initialized with connection string used to connect
    // it with Northwind SQL database
    using (SqlConnection mySqlConnection = new SqlConnection(connectionString))
    {
        try
        {
            // open the Sql connection
            mySqlConnection.Open();

            // Sql Command object initialized with SQL query to retrieve the Employees
            SqlCommand mySqlCommand = new SqlCommand("Select EmployeeID, FirstName, LastName from Employees", mySqlConnection);

            // Sql Data Reader to fetch the records row by row in forward direction.
            SqlDataReader myDataReader = mySqlCommand.ExecuteReader();

            // read each row fetched using DataReader
            while (myDataReader.Read())
            {
                // EmployeeID value as string
                string EmployeeID = myDataReader.GetSqlInt32(0).Value.ToString();

                // multiple column values to generate Full Name of employee
                // FirstName + LastName
                string EmployeeName = myDataReader.GetSqlString(1).Value + " " + myDataReader.GetSqlString(2).Value;

                // ListItem added into the DropDownList
                DropDownList1.Items.Add(new ListItem(EmployeeName, EmployeeID));
            }

            myDataReader.Close();
        }
        catch (Exception ex)
        {
            Label1.Text = ex.Message;
        }
        finally
        {
            // close the Sql Connection
            mySqlConnection.Close();
        }

        DropDownList1.Items.Insert(0, new ListItem("[Please select any Employee Name]", ""));

    }
}

protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
    Label1.Text = "You selected the Employee = <b>" + DropDownList1.SelectedItem.Text + "</b><br />";

    Label1.Text += "EmployeeID of selected Employee = <b>" + DropDownList1.SelectedItem.Value + "</b>";
}

In the above C# code we have used the SqlDataReader to fetch the forward-only stream of rows of data retrieved form SQL Database. We have used the Employees table of SQL Northwind database to fetch the records. We have used the FirstName and LastName multiple columns as text content for each list item added into the DropDownList control. EmployeeID field of Employees table has been used to associate a unique value for each list item. You can also bind the data retrieved using DataSet object to the DropDownList control from the previous tutorial: ASP.Net DropDownList SQL Datasource Databinding. You can also use the same approach that we used in that previous tutorial by specifying the value of DataTextField property. But that needs an alteration in SQL query used to retrieve the records. You can combine the multiple fields as a single field using an alias for them that can be specified as a value for DataTextField property of DropDownList control.

Output:

Get the output for above discussed code from the following link:

DropDownList DataTextField with Multiple Columns

Continue to the next tutorial: ASP.Net DropDownList Xml DataSource Databinding to learn how to bind the data retrieved from an XML file to DropDownList control.

2 Responses to "ASP.Net DropDownList DataTextField Multiple Columns"
Robert Megee
I found that for an Oracle query I can do something like this:
select field1||' '||field2 \"thename\"
from thetable
then set the datatextfield = "thename"
The dropdown list will show both fields.

Robert
Chimphalee Kittiphong
DropdownList1.DataSource = dt; DropdownList1.DataTextField="COSTCENTER_COST_CENTER_NAME"; DropdownList1.DataValueField = "COSTCENTER_COST_CENTER"; DropdownList1.DataBind(); foreach (ListItem item in DropdownList1.Items) { item.Text = string.Format("{0} ({1})", item.Value, item.Text); }
Leave a Comment
* required
* required
* will not be published
* optional
* hint: http://www.example.com
  • Subscribe via Email