Reputation: 3
I have the following code:
protected void btnSave_Click(object sender, EventArgs e)
{
StarBusModel.BookingDetail1 objBooking = new StarBusModel.BookingDetail1();
objBooking.TourID = tourID;
objBooking.Name = txtName.Text;
objBooking.Phone = txtPhone.Text;
objBooking.Amount = Convert.ToDecimal(Request.Form[txtAmount.ClientID]);
string [] seats = Request.Form[txtSeatNo.ClientID].Split(new char[] {','});
for (int i = 0; i < seats.Length; i++)
objBooking.SeatDetails.Add(new StarBusModel.SeatDetail1() {SeatID = Convert.ToInt32(seats[i])});
objEntities.BookingDetail1.AddObject(objBooking);
objEntities.SaveChanges();
BindSeats();
}
I get the error
System.NullReferenceException: Object reference not set to an instance of an object.
at the following code:
string [] seats = Request.Form[txtSeatNo.ClientID].Split(new char[] {','});
Please advise where I am wrong. I searched for various answers but cannot pinpoint where I am wrong.
Upvotes: 0
Views: 2357
Reputation: 119
NullReferenceException is a very headache excpetion. Even though you can know the line where the exception happen by see the stacktrace. But it may also include more than 1 possibilities.
Your case is an example.
string [] seats = Request.Form[txtSeatNo.ClientID].Split(new char[] {','});
In fact in this line, there are 2 place can cause null exception. They are:
Normally the second is most possible.
So it is better to write the code in multiple lines and check the value before you use it. I think Jacob Abrahams gave a very good example.
Upvotes: 0
Reputation: 995
Request.Form[txtSeatNo.ClientID]
is clearly null. In general, a NameValueCollection
(like Request.Form
) will return a null string if the given key is not defined.
You should do a check:
string seatString = Request.Form[txtSeatNo.ClientID];
string [] seats = String.IsNullOrEmpty(seatString) ? new char[]{} :
seatString.Split(new char[] {','});
Upvotes: 2