Click here to Skip to main content
15,885,914 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi I am a newbie to c#. I want to load data from sql server into my combobox. How do i proceed please guide me the steps.

Thank you in advance.
Posted

check out this link from codeproject

Populate data from database in a ComboBox[^]
 
Share this answer
 
Here are the steps:
1. Open your browser, and go to http://www.google.com[^]
2. Type database to combobox .net
3. Be amazed with the abundance of results of your search query.
4. Some articles are written in VB.Net, some are in C#. Choose those that are in C#.

I think this[^] can be useful for starters. But in order to fully understand this, I suggest you learn ADO.Net[^] first.
 
Share this answer
 
Comments
Shmuel Zang 9-Mar-12 4:43am    
I like your approach. My 5.
walterhevedeich 9-Mar-12 5:03am    
Thanks.
That's a very broad question!
Start reading here: MSDN: How to: Bind a Windows Forms ComboBox or ListBox Control to Data[^]

You should know already how to get the data from SQL - if you don't then we need to know how you would normally access it as there are quite a few different ways!
 
Share this answer
 
1. Have a SqlCommand object returning a Datatable with the records you want to use.
2. use the dropdownliads datasource property to specify this table as datasource
3. Use the DataMember property to specify the exact column of the table you want for the dropdown.

Here is a small code snippet that could help.

C#
//executing select command
 public DataTable ExecuteSelectCommand(string CommandName)
{
              SqlCommand cmd = null;
              DataTable table = new DataTable();
  
              cmd = con.CreateCommand();
  
              cmd.CommandType = CommandType.Text;
              cmd.CommandText = CommandName;
  
             try
              {
                  con.Open();
   
                 SqlDataAdapter da = null;
                   using (da = new SqlDataAdapter(cmd))
                 {
                      da.Fill(table);
                 }
                   con.Close();
              }
             catch (Exception ex)
              {
                  throw;
               }
              finally
 	      {
                  cmd.Dispose();
                  cmd = null;
              }
  
               return table;
          }

//specifying the sql statement
 public DataTable GetCategories()
           {
               return Functions.ExecuteSelectCommand("Select * from Categories");
           }

//attaching to the drop down list
drp.DataSource = GetCategories();
drp.DataTextField = "Category";
drp.DataValueField = "category";
drp.DataBind();
 
Share this answer
 

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