Solved

ASP.net Programatically populate ListBox from SQL backend table

Posted on 2011-09-29
9
462 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
[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
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!

 

Author Comment

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

Technology Partners: 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

Suggested Solutions

Just a quick little trick I learned recently.  Now that I'm using jQuery with abandon in my asp.net applications, I have grown tired of the following syntax:      (CODE) I suppose it just offends my sense of decency to put inline VBScript on a…
In an ASP.NET application, I faced some technical problems. In this article, I list them out and show the solutions that I found.  I hope it will be useful. Problem: After closing a pop-up window, the parent page should be refreshed automaticall…
Nobody understands Phishing better than an anti-spam company. That’s why we are providing Phishing Awareness Training to our customers. According to a report by Verizon, only 3% of targeted users report malicious emails to management. With compan…
The Email Laundry PDF encryption service allows companies to send confidential encrypted  emails to anybody. The PDF document can also contain attachments that are embedded in the encrypted PDF. The password is randomly generated by The Email Laundr…

749 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