Reputation: 47
I am trying to get data in gridview on the basis of the date that is entered in dateTimePicker. But, I am getting null reference runtime error on if condition where I have used equals
function to compare two strings.
ReportFrom.cs
private void button1_Click(object sender, EventArgs e)
{
string date = dateTimePicker.Value.ToShortDateString();
reportLayer.MakeDailyReport(date, dataGridViewReport);
}
ReportLayer.cs
private SqlConnection con = new SqlConnection("Data Source=CHAMP-PC;Initial Catalog=ProcessSale;Integrated Security=True");
private SqlCommand cmd;
private SqlDataAdapter adapt;
public void MakeDailyReport(string givenDate, DataGridView view)
{
try
{
con.Open();
DataTable dt = new DataTable();
cmd = new SqlCommand("SELECT Date FROM FinalSales where Date = @datePicker", con);
cmd.Parameters.AddWithValue("@datePicker", givenDate);
cmd.ExecuteNonQuery();
object dateObject = cmd.ExecuteScalar();
string dateObjectstring = Convert.ToString(dateObject);
string givenDateString = Convert.ToString(givenDate);
// string DBdate = dateObject.ToString();
if (dateObject.Equals(givenDate))
{
adapt = new SqlDataAdapter("SELECT Date FROM FinalSales where Date = " + givenDate + "", con);
if (adapt != null)
{
adapt.Fill(dt);
view.DataSource = dt;
}
else
{
MessageBox.Show("No Record found againts that date");
con.Close();
}
}
else
{
con.Close();
}
}
catch (Exception a)
{
MessageBox.Show(a.Message);
con.Close();
}
}
Upvotes: 0
Views: 1087
Reputation: 1165
Have a look here: Handling ExecuteScalar() when no results are returned
Additionally: Be careful with the call to Equals(). Currently you are comparing two strings. One with a ShortDate value One with the default ToString().
Event if the dates are equal, this might return false.
A better solution would be handling both values as DateTime and use the == operator.
Thomas
Upvotes: 1