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 “Data” choose “DataGridView” 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 “DataGridView”. In this case I have renamed Grid View as “dataGridViewCountry”.
- private void MainWindow_Load(object sender, EventArgs e)
- {
- try
- {
- DataTable countryTable = new DataTable();
- countryTable = DatabaseInterface.getData();
-
- BindingSource primaryGroupsBinding = new BindingSource();
- primaryGroupsBinding.DataSource = countryTable;
- dataGridViewCountry.DataSource = primaryGroupsBinding;
- }
- catch(Exception ex)
- {
- MessageBox.Show(ex.Message,"Error");
- }
- }
Now our “DataGridView” is ready with data.