How to add ListItem to Dropdownlist at first position

January 11, 2013 3:31 pm
Andri Kasta Marengga

How to add ListItem to Dropdownlist at first position

Recently I knew a “new” method named ddlArea.Items.Insert. Here’s the story how we met

void fillDdlArea()
{
try
{
ListItem myItem = new ListItem("All Area", String.Empty);
ddlArea.Items.Add(myItem);
using (l2sHeliosDataContext db = new l2sHeliosDataContext())
{
var area=
from reg in db.Vsn_servicepointExtensionBases
join sa in db.Vsn_servicepointExtensionBases on reg.Vsn_servicepointId equals sa.Vsn_ParentId
where reg.Vsn_Level==11
select new {
isiDdl= reg.Vsn_name+" - "+sa.Vsn_name
};
ddlArea.DataSource = area;
ddlArea.DataTextField = "isiDdl";
ddlArea.DataValueField = "isiDdl";
ddlArea.DataBind();
};
}
catch (Exception ex)
{
txtMessage.Text = ex.Message;
}
}

Result of code snippet above:  “All Area” item disappear from my dropdownlist, I guess binding dropdownlist with a new datasource replace all its item with new items.

If I put ddlArea.Items.Add(myItem) after DataBinding call, myItem will be placed on the last position.

After some research, I realize that ddlArea.Items.Add method doesnt met my need, but ddlArea.Items.Insert will

void fillDdlArea()
{
try
{
ListItem myItem = new ListItem("All Area", String.Empty);
ddlArea.Items.Add(myItem);
using (l2sHeliosDataContext db = new l2sHeliosDataContext())
{
var area=
from reg in db.Vsn_servicepointExtensionBases
join sa in db.Vsn_servicepointExtensionBases on reg.Vsn_servicepointId equals sa.Vsn_ParentId
where reg.Vsn_Level==11
select new {
isiDdl= reg.Vsn_name+" - "+sa.Vsn_name
};
ddlArea.DataSource = area;
ddlArea.DataTextField = "isiDdl";
ddlArea.DataValueField = "isiDdl";
ddlArea.DataBind();
ddlArea.Items.Insert(0, new ListItem(String.Empty, String.Empty));
ddlArea.SelectedIndex = 0;
};
}
catch (Exception ex)
{
txtMessage.Text = ex.Message;
}
}

, , ,

No comments yet.

Leave a Reply