How to Search Data Using DateTimePicker in C#
Submitted by janobe on Thursday, September 12, 2019 - 08:39.
One of the biggest problems in programming is how to deal with the dates. So, In this tutorial, I will teach you how to search for data using DateTimePicker in C#. This project has the ability to search the data in the database by the dates you choose in the DateTimePicker. The data will automatically display into the datagridview when the date you choose is equal to the transaction date in the database.
The complete source code is included you can download it and run it on your computer.
For any questions about this article. You can contact me @
Email – [email protected]
Mobile No. – 09305235027 – TNT
Or feel free to comment below.
Creating a Database
Go to http://localhost/phpmyadmin/ and create a new database named it "salesdb". Execute the following codes for creating a table.
Execute the following codes for inserting data in the table.
Creating Application
Step 1
Open Microsoft Visual Studio 2015 and create a new windows form application for c#.
Step 2
Do the form just like shown below.
Step 3
Add MySQL.Data.dllStep 4
Press F7 to open the code editor. In the code editor, add a namespace to accessMySQL
libraries
- using MySql.Data.MySqlClient;
Step 5
Establish a connection between C# and MySQL database. After that, declare all the classes that are needed.- MySqlConnection con = new MySqlConnection("server=localhost;user id=root;password=;database=salesdb;sslMode=none");
- MySqlDataAdapter da;
- MySqlCommand cmd;
- DataTable dt;
- string sql;
Step 6
Create a method for retrieving data in the database.- private void retrieveData(string sql, DataGridView dtg)
- {
- try
- {
- con.Open();
- cmd.Connection = con;
- cmd.CommandText = sql;
- da.SelectCommand = cmd;
- da.Fill(dt);
- dtg.DataSource = dt;
- }
- catch(Exception ex)
- {
- MessageBox.Show(ex.Message);
- }
- finally
- {
- con.Close();
- da.Dispose();
- }
- }
Step 7
Write the following code to display the data into the DataGridView in the first load of the form.- private void Form1_Load(object sender, EventArgs e)
- {
- sql = "SELECT * FROM `tblsales`";
- retrieveData(sql, dataGridView1);
- }
Step 8
Write the following code for searching data in the DataGridView using the DateTimePicker when the button is clicked- private void button1_Click(object sender, EventArgs e)
- {
- DateTime dateToday = dateTimePicker1.Value;
- string strDate = dateToday.ToString("yyyy-MM-dd");
- sql = "SELECT * FROM `tblsales` WHERE Date(`TRANSDATE`) = '" + strDate + "'";
- retrieveData(sql, dataGridView1);
- }
Comments
Add new comment
- Add new comment
- 2833 views