How To Search Data In MySQL Database Between Two Dates Using C#
In This C# Tutorial We Will See How To Get Records Between Two Date From MySQL Database Table Using Two DateTimePicker And Display The Selected Records Into A DataGridView Rows Using Csharp Programming Language And Visual Studio Editor.
Project Source Code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
namespace Csharp_Tutorials
{
public partial class Search_Data_In_MySQL_Between_2_Date : Form
{
public Search_Data_In_MySQL_Between_2_Date()
{
InitializeComponent();
}
// mysql connection
MySqlConnection connection = new MySqlConnection("datasource=localhost;port=3306;Initial Catalog='mydb';username=root;password=");
private void Search_Data_In_MySQL_Between_2_Date_Load(object sender, EventArgs e)
{
// populate datagridview from database using mysql data adapter
MySqlDataAdapter adapter = new MySqlDataAdapter("SELECT * FROM student", connection);
DataTable table = new DataTable();
adapter.Fill(table);
dataGridView1.DataSource = table;
}
// button search
private void BTN_Search_Click(object sender, EventArgs e)
{
// create a command with 2 parameters [ d1, d2 ]
// mean the first date and second one
MySqlCommand command = new MySqlCommand("SELECT `id`, `first_name`, `last_name`, `birthdate`, `address` FROM `student` WHERE `birthdate` BETWEEN @d1 AND @d2", connection);
// add values to the parameters form dateTimePickers
command.Parameters.Add("@d1", MySqlDbType.Date).Value = dateTimePicker1.Value;
command.Parameters.Add("@d2", MySqlDbType.Date).Value = dateTimePicker2.Value;
MySqlDataAdapter adapter = new MySqlDataAdapter("SELECT * FROM student", connection);
DataTable table = new DataTable();
adapter.Fill(table);
dataGridView1.DataSource = table;
}
}
}
///////////////OUTPUT:
Download Projects Source Code