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.
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 Mar 23, 2013, 8:46 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 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();
}
}
}
Sreejesh SPPosted Mar 23, 2013, 6:26 AM
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