Solved

ASP.net Programatically populate ListBox from SQL backend table

Posted on 2011-09-29
9
459 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
How to improve team productivity

Quip adds documents, spreadsheets, and tasklists to your Slack experience
- Elevate ideas to Quip docs
- Share Quip docs in Slack
- Get notified of changes to your docs
- Available on iOS/Android/Desktop/Web
- Online/Offline

 
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

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

AJAX ModalPopupExtender has a required property "TargetControlID" which may seem to be very confusing to new users. It means the server control that will be extended by the ModalPopup, for instance, if when you click a button, a ModalPopup displays,…
Sometimes in DotNetNuke module development you want to swap controls within the same module definition.  In doing this DNN (somewhat annoyingly) swaps the Skin and Container definitions to the default admin selections.  To get around this you need t…
This video demonstrates how to create an example email signature rule for a department in a company using CodeTwo Exchange Rules. The signature will be inserted beneath users' latest emails in conversations and will be displayed in users' Sent Items…
You have products, that come in variants and want to set different prices for them? Watch this micro tutorial that describes how to configure prices for Magento super attributes. Assigning simple products to configurable: We assigned simple products…

708 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

16 Experts available now in Live!

Get 1:1 Help Now