c# 循环变量问题

weixin_44949408 2019-09-26 09:13:45
for (int i = 1; i < 5; i++)
{
var name = "radioButton" + i;
string n = this.Controls[name].Tag.ToString();

if (n == "Number")
{

MessageBox.Show("1111");

}
这句为什么报错“System.NullReferenceException”类型的未经处理的异常?
...全文
203 11 打赏 收藏 转发到动态 举报
写回复
用AI写文章
11 条回复
切换为时间正序
请发表友善的回复…
发表回复
qzjsmile 2019-10-10
  • 打赏
  • 举报
回复
好厉害的样子
瀚娃娃 2019-10-10
  • 打赏
  • 举报
回复

this.Controls[name]


这个地方验证一下
牧歌ing 2019-10-09
  • 打赏
  • 举报
回复
string n = this.Controls[name].Tag.ToString();
断点
Bridge_go 2019-09-26
  • 打赏
  • 举报
回复
就是tag有为空的了
正怒月神 2019-09-26
  • 打赏
  • 举报
回复
你调试一下就知道啦。 肯定是this.Controls[name]为null
ManBOyyy 2019-09-26
  • 打赏
  • 举报
回复
引用 5 楼 weixin_44949408 的回复:
[quote=引用 4 楼 ManBOyyy 的回复:]
[quote=引用 3 楼 weixin_44949408 的回复:]
[quote=引用 2 楼 ManBOyyy 的回复:]
radioButton某個控件的tag是NULL,或者沒有4個radioButton

我手动给tag赋值了 但是string n 的值还是null[/quote]
首先呢?你刪除所有radioButton,然後就保留radioButton1,然後賦值radioButton1的Tag值,然後
for (int i = 1; i <2; i++)
這樣子能不能成功[/quote]
这样可以 这是什么原理?[/quote]
判斷一下NULL值啊
for (int i = 1; i < 5; i++)
{
var name = "radioButton" + i;
if (this.Controls[name] != null)
{
if (this.Controls[name].Tag != null)
{
string n = this.Controls[name].Tag.ToString();
if (n == "Number")
{
MessageBox.Show("1111");
}
}
}

}
weixin_44949408 2019-09-26
  • 打赏
  • 举报
回复
引用 4 楼 ManBOyyy 的回复:
[quote=引用 3 楼 weixin_44949408 的回复:] [quote=引用 2 楼 ManBOyyy 的回复:] radioButton某個控件的tag是NULL,或者沒有4個radioButton
我手动给tag赋值了 但是string n 的值还是null[/quote] 首先呢?你刪除所有radioButton,然後就保留radioButton1,然後賦值radioButton1的Tag值,然後 for (int i = 1; i <2; i++) 這樣子能不能成功[/quote] 这样可以 这是什么原理?
ManBOyyy 2019-09-26
  • 打赏
  • 举报
回复
引用 3 楼 weixin_44949408 的回复:
[quote=引用 2 楼 ManBOyyy 的回复:]
radioButton某個控件的tag是NULL,或者沒有4個radioButton

我手动给tag赋值了 但是string n 的值还是null[/quote]
首先呢?你刪除所有radioButton,然後就保留radioButton1,然後賦值radioButton1的Tag值,然後
for (int i = 1; i <2; i++)
這樣子能不能成功
weixin_44949408 2019-09-26
  • 打赏
  • 举报
回复
引用 2 楼 ManBOyyy 的回复:
radioButton某個控件的tag是NULL,或者沒有4個radioButton
我手动给tag赋值了 但是string n 的值还是null
ManBOyyy 2019-09-26
  • 打赏
  • 举报
回复
radioButton某個控件的tag是NULL,或者沒有4個radioButton
exception92 2019-09-26
  • 打赏
  • 举报
回复
http://www.cnblogs.com/alexis/archive/2010/11/06/1870519.html调试一下,目测this.Controls[name].Tag这句的问题。

110,537

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧