0

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.

3
  • this Request.Form[txtSeatNo.ClientID] may give you null??? Commented May 23, 2012 at 2:32
  • it is always good to perform a sanity check on your input form value before any manipulation. By the way, why you need to split the txtSeatNo ? Commented May 23, 2012 at 2:33
  • Why can't you access txtAmount.Text and txtSeatNo.Text? Why you need to get control values using form collection?? Commented May 23, 2012 at 2:33

2 Answers 2

2

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[] {','});
Sign up to request clarification or add additional context in comments.

1 Comment

This helped me trace back the code and solve the null value returning for Request.Form[txtSeatNo.ClientID]. Thank a lot.
0

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:

  1. txtSeatNo.ClientID
  2. Request.Form[txtSeatNo.ClientID]

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.