Nabeel Khan Nabeel Khan - 5 months ago 83
SQL Question

how to filter datagrid data from date to date in wpf C#

I can't filter datagrid data from date to date in wpf C# .

Here is my code:

public partial class MainWindow : Window
{
public DateTime SelectedDate1;
public DateTime SelectedDate2;
SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=GOLGOHAR_DB;Integrated Security=True");

GOLGOHAR_DBEntities GOG = new GOLGOHAR_DBEntities();
public MainWindow()
{
InitializeComponent();
loadgrid();
datetimepicker1.SelectedDate = DateTime.Now.Date;
datetimepicker2.SelectedDate = DateTime.Now.Date;
}


private void loadgrid()
{
var data = from r in GOG.QC_Bentonite_Phy_Tables select r;
dataGrid.ItemsSource = data.ToList();
}

private void Button_Click(object sender, RoutedEventArgs e)
{
DateTime datetime = (dataGrid.SelectedItem as QC_Bentonite_Phy_Tables).DateTime;
QC_Bentonite_Phy_Tables ben_phy = (from r in GOG.QC_Bentonite_Phy_Tables where r.DateTime == datetime select r).SingleOrDefault();
GOG.QC_Bentonite_Phy_Tables.Remove(ben_phy);
GOG.SaveChanges();
dataGrid.ItemsSource = GOG.QC_Bentonite_Phy_Tables.ToList();
}

private void FetchData_Click(object sender, RoutedEventArgs e)
{
SelectedDate1 = datetimepicker1.SelectedDate.Value;
SelectedDate2 = datetimepicker1.SelectedDate.Value;
SqlDataAdapter sdf = new SqlDataAdapter("select * from QC_Bentonite_Phy_Tables where DATED between '" + SelectedDate1.ToString() + "' and '" + SelectedDate2.ToString() + "'", con);
DataSet ds = new DataSet();
con.Open();
sdf.Fill(ds);
con.Close();
dataGrid.ItemsSource = GOG.QC_Bentonite_Phy_Tables.ToList();

}
}


please can someone help me?
I am using this method to filter data in datagrid

private void FetchData_Click(object sender, RoutedEventArgs e)
{
SelectedDate1 = datetimepicker1.SelectedDate.Value;
SelectedDate2 = datetimepicker1.SelectedDate.Value;
SqlDataAdapter sdf = new SqlDataAdapter("select * from QC_Bentonite_Phy_Tables where DATED between '" + SelectedDate1.ToString() + "' and '" + SelectedDate2.ToString() + "'", con);
DataSet ds = new DataSet();
con.Open();
sdf.Fill(ds);
con.Close();
dataGrid.ItemsSource = GOG.QC_Bentonite_Phy_Tables.ToList();

}

Answer

Try below

SqlDataAdapter sdf = new SqlDataAdapter("select * from QC_Bentonite_Phy_Tables where DATED between '" + SelectedDate1+ "' and '" + SelectedDate2+"'",con);