how to bind multiple values from database dropdownlist?
how to bind multiple values from database dropdownlist?
Know the answer? Post it — somebody with the same question will find it here.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
Satyapriya NayakPosted May 29, 2013, 7:34 AM
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;
namespace Dropdownlist
{
public partial class WebForm4 : System.Web.UI.Page
{
string strConnString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
string str;
SqlCommand com;
SqlDataAdapter sqlda;
DataSet ds;
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(strConnString);
con.Open();
str = "select * from employee";
com = new SqlCommand(str, con);
sqlda = new SqlDataAdapter(com);
ds = new DataSet();
sqlda.Fill(ds, "employee");
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
DropDownList1.Items.Add(ds.Tables[0].Rows[i]["empname"] +"---" + ds.Tables[0].Rows[i]["empaddress"].ToString());
}
con.Close();
}
}
}
Sandeep Singh ShekhawatPosted May 29, 2013, 6:52 AM
MyDropDownList.DataTextField = "blah";
MyDropDownList.DataValuefield = "blah";
MydropDownList.DataBind();
//Do this.
foreach(YourObject instance in YourObjectList)
{
MyDropDownList.Items.add(new ListItem(YourObject.column1+Yourojbect.colum2+Yourobject.Column3, Yourobject.DataKey));
}
for example you can do
DVU_eventsTableAdapter events = new DVU_eventsTableAdapter();
DataTable dt = events.GetData();
for (int i = 0; i < dt.Rows.Count; i++)
{
DateTime eventdate = new DateTime();
eventdate = Convert.ToDateTime(dt.Rows[i]["event_date"].ToString());
string formatted_date = String.Format("{0:d}", eventdate);
ddlEvent.Items.Add(new ListItem(dt.Rows[i]["loc_city"].ToString() + ", " + dt.Rows[i]["loc_state"].ToString() + " (" + formatted_date + ")", dt.Rows[i]["event_id"].ToString()));
}