Create a Window form application have a look at my previous blog - how to create window form application. Once our window is ready click on Toolbox under “All windows form” choose “ComboBox” and drag onto the window.
We will have,
Here we are binding the data from database table. Double click on window so we will get the window load method.
Now add new classes file to the project
Once class is created add the database connection method and method to retrieve data.
- public static class DatabaseInterface
- {
- static MySqlConnection databaseConnection = null;
-
-
-
-
-
- public static MySqlConnection getDBConnection()
- {
- string connectionString = ConfigurationManager.ConnectionStrings["myDemoConnection"].ConnectionString;
- databaseConnection = new MySqlConnection(connectionString);
- return databaseConnection;
- }
-
-
-
-
-
-
- public static DataTable getData()
- {
- try
- {
- DataTable countries = new DataTable();
- DataSet DsConType = new DataSet();
- string sqlStatement = "SELECT * FROM country ORDER BY id ASC";
- getDBConnection().Open();
- MySqlDataAdapter myDatabaseAdapter = new MySqlDataAdapter(sqlStatement, databaseConnection);
- myDatabaseAdapter.Fill(DsConType, "AllCountries");
- return DsConType.Tables["AllCountries"];
- }
- catch (Exception excp)
- {
- throw excp;
- }
- finally
- {
- if (databaseConnection != null)
- {
- databaseConnection.Close();
- }
- }
-
- }
- }
Here I used “ConfigurationManager” to retrieve the connection string from app.config. to know how to connect through app.config please follow the my revious blog.
Once it is finished then we have to bind get the table info in window _load() and bind it to “ComboBox”. In this case I have renamed Grid View as “comboBoxSelectCountry”.
- private void MainWindow_Load(object sender, EventArgs e)
- {
- try
- {
- DataTable countryTable = new DataTable();
- countryTable = DatabaseInterface.getData();
-
- comboBoxSelectCountry.DataSource = countryTable;
- comboBoxSelectCountry.DisplayMember = "name";
- comboBoxSelectCountry.ValueMember = "id";
- }
- catch(Exception ex)
- {
- MessageBox.Show(ex.Message,"Error");
- }
- }
Now our “ComboBox” is ready with data.