crowso
crowso

Reputation: 2077

how to populate asp:DropDownList from C# side

I am trying to populate asp:DropDownList with data items and here is the code i have written so far

.aspx side

<asp:DropDownList ID="ddl" runat="server" />

C# side

protected void btnAdd_Click(object sender, EventArgs e)
{
  ddl.DataTextField = "hello";
  ddl.DataTextField = "2";
  ddl.DataBind();
}

The method btnAdd_Click is invoked. I tested it. But the data list is not getting populated with those data items.

Upvotes: 0

Views: 1886

Answers (2)

Erwin
Erwin

Reputation: 4817

If you want to use DataTextField and DataBind, I asume you have a datasource to bind to your dropdownlist. If you want to do that you also have to have a DataValueField.

ddl.DataValueField = "id";
ddl.DataTextField = "name";
ddl.DataSource = GetData();
ddl.DataBind();

The GetData method have to return a datasource with an id and a name column.

Upvotes: 0

Issa Qandil
Issa Qandil

Reputation: 1238

Try adding your items like this

ddl.Items.Add(new ListItem("Your Text", "0"));

Upvotes: 2

Related Questions