Populate listbox with records from database
hi :) how can i populate a listbox with records from a database? thanks
Know the answer? Post it. Somebody with the same question will find it here.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
Sreejesh SPRank #1,975 · 740 reputationPosted Mar 23, 2013, 2:26 AM EDT
please use the below code
SqlConnection con = new SqlConnection(@"
SqlCommand cmd = new SqlCommand();
private void Form1_Load(object sender, EventArgs e)
{
DataTable dt = new System.Data.DataTable();
cmd.Connection = con;
cmd.CommandText = "select LastName,FirstName,Title,City from dbo.Employees";
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
listbox1.datasource=dt;
listbox1.databind();
}
*input your connection string
Thanks
Sreejesh
Satyapriya NayakRank #47 · 31.5K reputationPosted Mar 23, 2013, 4:46 AM EDT
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 Populate_listbox_records_database
{
public partial class _Default : 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");
ListBox1.DataValueField = "empid";
ListBox1.DataTextField = "empname";
ListBox1.DataSource = ds;
ListBox1.DataMember = "employee";
ListBox1.DataBind();
con.Close();
}
}
}