Now that the database is created we can move on to creating the application to view it. The first step is to create a new C# Windows Application in Visual Studio. On the main form, place a datagrid control in the middle and call it mysqltable. Next we will want to fill this datagrid with information from our table. To accomplish this we will need to use ADO at load time. Double click on the main form to bring up the code view for the Form1_Load function. The code for the load function should look as follows:
private void Form1_Load(object sender, System.EventArgs e)
{
//create a connection string, contains the driver, the servername and the database name
String ConnectionString = “Driver={MySQL ODBC 3.51 Driver};Server=localhost;Database=mysqlsample;option=3”;
//create a query string
String myquery = “SELECT * FROM tutorials”;
//run the connection string and the query and store it in the dataadapter
OdbcDataAdapter MySQLDataAdapter = new OdbcDataAdapter(myquery,ConnectionString);
//create a new dataset
DataSet MySQLDataSet = new DataSet();
//fill the dataset with data from the dataadapter
MySQLDataAdapter.Fill(MySQLDataSet,”tutorials”);
//now set the datasource of our grid to that of the main table of the dataset
mysqltable.DataSource = MySQLDataSet.Tables[”tutorials”].DefaultView;
}
This code connects to the database using the OdbcDataAdapter and performs our query. We then store the results in a dataset which can be used as the datasource for our grid. Next we add a quit button somewhere on the form to allow the application to exit. The code for quitting is simply:
private void button1_Click(object sender, System.EventArgs e)
{
//quit the application
Application.Exit();
}
Comments