Object Reference not set to an instance of the object
An error 'object reference not set to an instance of an object' occurs when I'm using the class object cleave
below the for loop
private void dateTimePickertodate_ValueChanged(object sender, EventArgs e)
{
if (dateTimePickertodate.Value <=dateTimePickerfromdate.Value)
{
MessageBox.Show("Choose Correct date开发者_开发问答");
textBoxnumofdays.Clear();
}
else
{
cleave = new LeaveApplication(constr);
span = dateTimePickertodate.Value - dateTimePickerfromdate.Value;
Getdays();
if (Mode == 1)
{
textBoxnumofdays.Text = Convert.ToString(span.Days + 2);
}
else
{
textBoxnumofdays.Text = Convert.ToString(span.Days + 1);
}
for (int i = 0; i < daysofweek.Count; i++)
{
if (Mode == 1)
{
textBoxnumofdays.Text = Convert.ToString(span.Days + 2);
if (daysofweek[i].Equals(cleave.WeekDays[i]))
{
textBoxnumofdays.Text = Convert.ToString(span.Days - 1);
}
}
else
{
textBoxnumofdays.Text = Convert.ToString(span.Days + 1);
if (daysofweek[i].Equals(cleave.WeekDays[i]))
{
textBoxnumofdays.Text = Convert.ToString(span.Days - 1);
}
}
}
}
}
when iam using the class object cleave below the for loop
you don't show anything below the for
loop, and cleave
isn't declared in the method - so we infer that it is a field. We can therefore assume one of two things:
- the date selected wasn't a valid date, so
cleave
was never assignednew LeaveApplication(constr);
- the event hasn't fired,
dateTimePickertodate_ValueChanged
has never been invoked - so again,cleave
hasn't been assigned
Are you sure that the WeekDays
array is initialized in your LeaveApplication
constructor. If not, it will throw a NullReferenceException
in your statement:
if (daysofweek[i].Equals(cleave.WeekDays[i]))
Simply put an instance of cleave
hasn't been created by the time that you wish to use it.
Have you checked that it isn't null and that a non-null instance of cleave
has been created?
One of the problems here is that we have to assume that cleave
, constr
and span
are fields within your "form" and that they are of the correct type definition and that they are accessible and valid for the thread that your code is running on.
edit
Seeing more of your comments. If any of the data used on your form is pushed by code that is not running on the same thread as your GUI rather than retrieved by the form class then you'll need to define a delegate on your form that can be used by that code to update the data. By using "form class".Invoke(delegate function) type functionality.
精彩评论