views:

747

answers:

4

I am databinding a dropdown list with the following array list:


ArrayList al = new ArrayList();
al.Add(new ListItem("Service Types", 1));
al.Add(new ListItem("Expense Types", 2));
al.Add(new ListItem("Payment Terms", 3));
al.Add(new ListItem("Classes", 4));
al.Add(new ListItem("Project", 5));
al.Add(new ListItem("Employees", 6));
al.Add(new ListItem("Payroll Codes", 7));

ddlType.DataSource = al;
ddlType.DataBind();

This results in the following HTML:


<select name="ddlType">
    <option value="Service Types">Service Types</option>
    <option value="Expense Types">Expense Types</option>
    <option value="Payment Terms">Payment Terms</option>
    <option value="Classes">Classes</option>
    <option value="Project">Project</option>
    <option value="Employees">Employees</option>
    <option value="Payroll Codes">Payroll Codes</option>
</select>

How can I set the DataTextField and DataValueField properties on my dropdown so that the values of the list items are the values in the dropdown?

Thanks.

A: 
ddlType.DataTextField = "Text";
ddlType.DataValueField = "Value";
Fabian Vilers
This does not seem to work with .NET 1.1
mmattax
-1 this does not work in .NET 1.1 - databiding is much more sophisticated in later versions of the framework.
Andrew Hare
A: 

Instead of an Instead of an ArrayList containg ListItems why don't you create a Hashtable?

Hashtable hash = new Hashtable();
hash.Add("one", "1")
hash.Add("two", "2")

dd.DataSource = ht
dd.DataTextField = "value"
dd.DataValueField = "key"
dd.DataBind()
Andrew Hare
It works with the ListItem that have Value and Key field.
Fabian Vilers
It doesn't work in .NET 1.1 - a HashTable is the best solution for .NET 1.1
Andrew Hare
This doesn't seem to work either.
mmattax
Are you seeing an error or does it still bind to the first element each time?
Andrew Hare
Binds to the first element each time.
mmattax
Fixed the typo -- the collection is Hashtable
Dana
A: 

Have you tried creating a ListItemCollection and binding to that?

JNappi
A: 

Why bother with databinding at all. You can populate the items collection directly:

ddlType.Items.Add(new ListItem("Service Types", 1));
...
ddlType.Items.Add(new ListItem("Payroll Codes", 7));

and it will even make your code 3 lines shorter ;-)

radimd