Solved

ASP.net Programatically populate ListBox from SQL backend table

Posted on 2011-09-29
9
460 Views
Last Modified: 2012-05-12
Hi

Using the System.Data.SqlClient namespace, how would I programatically populate
a ListBox on an ASP.net WebPage?
0
Comment
Question by:murbro
  • 4
  • 2
  • 2
  • +1
9 Comments
 
LVL 39

Expert Comment

by:Pratima Pharande
ID: 36813547
refer

http://geekswithblogs.net/dotNETvinz/archive/2009/02/24/binding-dropdownlist-listbox-and-checkboxlist-control-the-ado.net-way.aspx 
private void BindListBox()

    {

        DataTable dt = new DataTable();

        SqlConnection connection = new SqlConnection(GetConnectionString());

        try

        {

            connection.Open();

            string sqlStatement = "SELECT Top(20)* FROM Customers";

            SqlCommand sqlCmd = new SqlCommand(sqlStatement, connection);

            SqlDataAdapter sqlDa = new SqlDataAdapter(sqlCmd);

 

            sqlDa.Fill(dt);

            if (dt.Rows.Count > 0)

            {

                ListBox1.DataSource =dt;

                ListBox1.DataTextField = "ContactName"; // the items to be displayed in the list items

                ListBox1.DataValueField = "CustomerID"; // the id of the items displayed

                ListBox1.DataBind();

            }

        }

        catch (System.Data.SqlClient.SqlException ex)

        {

            string msg = "Fetch Error:";

            msg += ex.Message;

            throw new Exception(msg);

        }

        finally

        {

            connection.Close();

        }

    }

}

Open in new window

0
 
LVL 39

Expert Comment

by:Pratima Pharande
ID: 36813552
refer

http://geekswithblogs.net/dotNETvinz/archive/2009/02/24/binding-dropdownlist-listbox-and-checkboxlist-control-the-ado.net-way.aspx 
private void BindListBox()

    {

        DataTable dt = new DataTable();

        SqlConnection connection = new SqlConnection(GetConnectionString());

        try

        {

            connection.Open();

            string sqlStatement = "SELECT Top(20)* FROM Customers";

            SqlCommand sqlCmd = new SqlCommand(sqlStatement, connection);

            SqlDataAdapter sqlDa = new SqlDataAdapter(sqlCmd);

 

            sqlDa.Fill(dt);

            if (dt.Rows.Count > 0)

            {

                ListBox1.DataSource =dt;

                ListBox1.DataTextField = "ContactName"; // the items to be displayed in the list items

                ListBox1.DataValueField = "CustomerID"; // the id of the items displayed

                ListBox1.DataBind();

            }

        }

        catch (System.Data.SqlClient.SqlException ex)

        {

            string msg = "Fetch Error:";

            msg += ex.Message;

            throw new Exception(msg);

        }

        finally

        {

            connection.Close();

        }

    }

}

Open in new window

0
 
LVL 17

Expert Comment

by:sonawanekiran
ID: 36813566
on aspx page add listbox control like
<asp:DropDownList ID="dpDistributor" runat="server" Height="22px" Width="153px" 
                    DataSourceID="LinqDataSource1" DataTextField="CompanyName" DataValueField="CompanyName" 
                   >

Open in new window


In Code behind

 
private void FillListBox()
{
        DataTable dt = new DataTable();
        SqlConnection connection = new SqlConnection("YOUR CONNECTION STRING HERE"); 
        try
        {
        connection.Open();
        SqlCommand sqlCmd = new SqlCommand("SELECT * FROM TableName ", connection);
        SqlDataAdapter sqlDa = new SqlDataAdapter(sqlCmd);

        sqlDa.Fill(dt);
        if (dt.Rows.Count > 0)
        {
           ListBox1.DataTextField = "ColumnName";
           ListBox1.DataValueField = "ColumnName";
           ListBox1.DataSource = dt;
           ListBox1.DataBind()
        }
        }
        catch (System.Data.SqlClient.SqlException ex)
        {
                string msg = "Fetch Error:";
                msg += ex.Message;
                throw new Exception(msg);

        }
        finally
        {
            connection.Close();
        }
}
protected void Page_Load(object sender, EventArgs e)
{

   if (!Page.IsPostBack){
        FillListBox();
   }


}

Open in new window

0
 

Author Comment

by:murbro
ID: 36813574
Hi. Thank you very much. I forgot to add that I need this in VB.net.
0
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 
LVL 8

Expert Comment

by:PeteEngineer
ID: 36813575
0
 
LVL 17

Expert Comment

by:sonawanekiran
ID: 36813586
ASPX code same as above and below is vb code


Private Sub FillListBox()
	Dim dt As New DataTable()
	Dim connection As New SqlConnection("YOUR CONNECTION STRING HERE")
	Try
		connection.Open()
		Dim sqlCmd As New SqlCommand("SELECT * FROM TableName ", connection)
		Dim sqlDa As New SqlDataAdapter(sqlCmd)

		sqlDa.Fill(dt)
		If dt.Rows.Count > 0 Then
			ListBox1.DataTextField = "ColumnName"
			ListBox1.DataValueField = "ColumnName"
			ListBox1.DataSource = dt
			ListBox1.DataBind()
		End If
	Catch ex As System.Data.SqlClient.SqlException
		Dim msg As String = "Fetch Error:"
		msg += ex.Message

		Throw New Exception(msg)
	Finally
		connection.Close()
	End Try
End Sub
Protected Sub Page_Load(sender As Object, e As EventArgs)

	If Not Page.IsPostBack Then
		FillListBox()
	End If


End Sub

Open in new window

0
 
LVL 39

Expert Comment

by:Pratima Pharande
ID: 36813590
Dim cmd As New SqlCommand("SELECT * FROM [tblOne]", New SqlConnection(ConfigurationManager.AppSettings("ConnString")))
cmd.Connection.Open()

Dim ddlValues As SqlDataReader
ddlValues = cmd.ExecuteReader()

ListBox1.DataSource = ddlValues
ListBox1.DataValueField = "theName"
ListBox1.DataTextField = "theName"
ListBox1.DataBind()

cmd.Connection.Close()
cmd.Connection.Dispose()
0
 
LVL 39

Accepted Solution

by:
Pratima Pharande earned 500 total points
ID: 36813598
0
 

Author Closing Comment

by:murbro
ID: 36813618
Thank you very much
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Today is the age of broadband.  More and more people are going this route determined to experience the web and it’s multitude of services as quickly and painlessly as possible. Coupled with the move to broadband, people are experiencing the web via …
A quick way to get a menu to work on our website, is using the Menu control and assign it to a web.sitemap using SiteMapDataSource. Example of web.sitemap file: (CODE) Sample code to add to the page menu: (CODE) Running the application, we wi…
Edureka is one of the fastest growing and most effective online learning sites.  We are here to help you succeed.
Many functions in Excel can make decisions. The most simple of these is the IF function: it returns a value depending on whether a condition you describe is true or false. Once you get the hang of using the IF function, you will find it easier to us…

912 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

21 Experts available now in Live!

Get 1:1 Help Now