DarkW1nter DarkW1nter - 1 month ago 12
C# Question

set dropdownlist datasource and values at runtime using C#

If setting a DropDownList's

DataSourceID
to a SqlDataSource at runtime depending on certain conditions, how do I set what field from the SqlDataSource to show and what to set as its value?
Currently I have the code below:

protected void chkBondedStock_CheckedChanged(object sender, EventArgs e)
{
if (chkBondedStock.Checked)
{
ddlProject.DataSourceID = "SqlBond_Y";
ddlProject.DataBind();
}
else
{
ddlProject.DataSourceID = "SqlBond_N";
ddlProject.DataBind();
}
}

Answer

Probably you're using the System.Web.UI.WebControls.DropDownList control. If so, you should use:

ddlProject.DataValueField = "ValueField";
ddlProject.DataTextField = "TextField";

https://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.listcontrol.datatextfield(v=vs.110).aspx https://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.listcontrol.datavaluefield(v=vs.110).aspx