Click here to Skip to main content
15,791,562 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
dear all,

Can any body send me a code how to populate combox or list box in c# from sql2005.

Thanks in advance

Asgar Ali Baig
Updated 11-Dec-10 20:19pm

Thank you for your question. You can follow the bellow code.

public void PopulateGCSCompany(ListBox list, String connectionString)
            StringBuilder sbQuery = new StringBuilder();

            sbQuery.AppendLine(" SELECT ");
            sbQuery.AppendLine(" [GCSCompanyId],[CompanyName] ");
            sbQuery.AppendLine("  FROM [GCSCompany] ");
            sbQuery.AppendLine(" ORDER BY [CompanyName] ASC ");

            using (SqlConnection conn = new SqlConnection(connectionString))
                DataTable companyDataTable = new DataTable();
                SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(sbQuery.ToString(), conn);

                list.DataValueField = "GCSCompanyId";
                list.DataTextField = "CompanyName";
                list.DataSource = companyDataTable;

                list.Items.Insert(0, new ListItem("", "0"));

Share this answer
asgar ali 12-Dec-10 0:51am    
Abdul Quader Mamun 12-Dec-10 1:13am    
This code is not sufficient for you.
Abdul Quader Mamun 12-Dec-10 1:17am    
Try yourself.
How about come with your code snippet instead of asking just a question?
It's a simple question...for this you can get the solution by using search engines.
Here after put your effort & come with your code snippet so that you will get the solutions quickly.

Working with DropDownList and ListBox Controls in ASP.NET[^]

An unhandled exception of type 'System.ArgumentException' occurred[^]
Share this answer
asgar ali 11-Dec-10 6:50am    
Thnks for the code.. it works but 1 error is Argument Execption was unhandled
thatraja 11-Dec-10 6:53am    
check my updated answer for the current issue.
asgar ali 12-Dec-10 0:50am    
Thanks it works...

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900