简体   繁体   中英

NullReferenceException retrieving value from known Request.Form[key] elements in C#

I am trying to retrieve the values from a number of RadioButtonGroups on PostBack using the Request.Form keys like so:

string val = Request.Form["ControlName" + i].ToString();

But I keep getting a NullReferenceException.

I know the keys are a part of the collection, and if I replace the above code with:

Response.Write(Request.Form["RadioGroup" + i].ToString())

The value is displayed on the page.

Why does it throw a NullReferenceException if I try to assign it to a variable, but not when I write it to the browser?

Thanks

The reason why the second one works is probably because you changed the string from "ControlName" to "RadioGroup" .

In order to avoid the NullReferenceException you should avoid calling ToString . The indexer already returns a string so the call to ToString is unnecessary.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM