?
Solved

ASP.net Programatically populate ListBox from SQL backend table

Posted on 2011-09-29
9
Medium Priority
?
465 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:Murray Brown
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 

Author Comment

by:Murray Brown
ID: 36813574
Hi. Thank you very much. I forgot to add that I need this in VB.net.
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 2000 total points
ID: 36813598
0
 

Author Closing Comment

by:Murray Brown
ID: 36813618
Thank you very much
0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

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

ASP.Net to Oracle Connectivity Recently I had to develop an ASP.NET application connecting to an Oracle database.As I am doing it first time ,I had to solve several problems. This article will help to such developers  to develop an ASP.NET client…
User art_snob (http://www.experts-exchange.com/M_6114203.html) encountered strange behavior of Android Web browser on his Mobile Web site. It took a while to find the true cause. It happens so, that the Android Web browser (at least up to OS ver. 2.…
In this video you will find out how to export Office 365 mailboxes using the built in eDiscovery tool. Bear in mind that although this method might be useful in some cases, using PST files as Office 365 backup is troublesome in a long run (more on t…
In response to a need for security and privacy, and to continue fostering an environment members can turn to for support, solutions, and education, Experts Exchange has created anonymous question capabilities. This new feature is available to our Pr…

719 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