My stored procedure is like this
SELECT Id, StudentName
FROM xyz
I have a drop down list in asp.net, which I am loading as :
it's very simple, only you have concat fields in the query
SELECT Id ,Id || ' ' || StudentName ""TEXT"",
FROM xyz
then you build a drop down list
ddlA.DataSource = // Some source
ddlA.DataTextField = "TEXT";
ddlA.DataValueField = "Id";
ddlA.DataBind();
ddlA.Items.Insert(0, new ListItem(" Select one", "0"));
If the DataSource is a DataTable, you can add an "expression" (calculated column) to the table. The expression for the new column would look like this:
newcolumn.Expression = "Id + ' - ' + StudentName";
If you have list of class to fill drop down list, this is probably best to do;
List<FOO> foo = new List<FOO>();
ddlFoo.DataSource = foo.Select(x =>
new ListItem { Text = x.Text1 + " - " + x.Text2, Value = x.Id.ToString() });
ddlFoo.DataBind();
DropDownList1.DataTextFormatString = "{0} - {1}";
DropDownList1.DataTextField = "Id,StudentName";
It seems that it's not achievable automatically, e.g. see this MS Connect ticket.
Thus do that programmatically:
foreach (var row in table.Rows)
{
row.Field<string>("text") = String.Format(..);
}
or
foreach (var item in data)
{
new ListItem { Text = String.Format(..); };
}
You can use LINQ to make a new datasource containing a displayfield which is formatted, the way you want it to be, like:
var datasource = from x in products
select new {
x.Id,
x.Code,
x.Description,
DisplayField = String.Format("{0} ({1})", x.Code, x.Description)
};
comboBox.DataSource = datasource;
comboBox.DataValueField = "Id";
comboBox.DataTextField = "DisplayField";
comboBox.DataBind();
You can achieve it by following code
dsStudent.Tables[0].Columns.Add("IdWithStudenName",typeof(string),"Id + ' - ' + StudenName");
DropDownList1.DataSource = dsStudent;
DropDownList1.DataTextField = "IdWithStudenName";
DropDownList1.DataBind();
DropDownList1.Items.Insert(0, new ListItem("Please select"));
For more understanding refer here.