Click here to Skip to main content
15,921,113 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
Posted
Updated 11-Dec-10 19:19pm
v2

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

C#
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);
                sqlDataAdapter.Fill(companyDataTable);

                list.DataValueField = "GCSCompanyId";
                list.DataTextField = "CompanyName";
                list.DataSource = companyDataTable;
                list.DataBind();

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


Thanks,
Mamun
 
Share this answer
 
v4
Comments
asgar ali 12-Dec-10 0:51am    
thanks....
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[^]

[Edit]
An unhandled exception of type 'System.ArgumentException' occurred[^]
[/Edit]
 
Share this answer
 
v2
Comments
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