简体   繁体   English

NullReferenceException从C#中的已知Request.Form [key]元素检索值

[英]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: 我正在尝试使用Request.Form键从PostBack上的许多RadioButtonGroups中检索值,如下所示:

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

But I keep getting a NullReferenceException. 但是我一直收到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? 为什么在尝试将其分配给变量时却抛出NullReferenceException而不是在将其写入浏览器时抛出该异常?

Thanks 谢谢

The reason why the second one works is probably because you changed the string from "ControlName" to "RadioGroup" . 第二个之所以起作用,可能是因为您将字符串从"ControlName"更改为"RadioGroup"

In order to avoid the NullReferenceException you should avoid calling ToString . 为了避免NullReferenceException您应该避免调用ToString The indexer already returns a string so the call to ToString is unnecessary. 索引器已经返回了一个string因此不需要调用ToString

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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