我如何处理此问题...显示空引用异常是由用户代码解除的 [英] How Can I Handle This Problem...showing null reference exception was unhandle by user code
本文介绍了我如何处理此问题...显示空引用异常是由用户代码解除的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
protected void btnsubmit_Click(对象发件人,EventArgs e)
{
string strSelectOptions = string 跨度> .Empty;
CheckBox ch = sender as CheckBox;
if (ch.Checked)
strSelectOptions + = ch.Text + ,;
if (strSelectOptions!= string .Empty)
{
strSelectOptions = strSelectOptions.Remove(strSelectOptions.Length - 1 );
int pos = strSelectOptions.LastIndexOf( ,跨度>);
if (pos!= -1)
{
strSelectOptions = strSelectOptions.Remove(pos, 1 跨度>);
strSelectOptions = strSelectOptions.Insert(pos, &);
}
lblresult.Text = 选择的选项: + strSelectOptions;
}
else
{
lblresult.Text = 未选择选项;
}
}
解决方案
看看你的代码:
protected void btnsubmit_Click( object sender,EventArgs e)
{
string strSelectOptions = string 跨度> .Empty;
CheckBox ch = sender as CheckBox;
if (ch.Checked)
hat是一个按钮点击事件处理程序,所以很有可能发件人
是一个按钮,而不是一个CheckBox。
所以这一行:
< pre lang =c#> CheckBox ch = sender as CheckBox;
将
ch
设置为null
,以及任何使用属性的尝试或者方法将因空引用异常而失败。
可能你需要重新思考你在做什么,或者直接使用CheckBox名称而不是试图使用发件人
参数。
protected void btnsubmit_Click(object sender, EventArgs e)
{
string strSelectOptions = string.Empty;
CheckBox ch = sender as CheckBox;
if (ch.Checked)
strSelectOptions += ch.Text + ",";
if (strSelectOptions != string.Empty)
{
strSelectOptions = strSelectOptions.Remove(strSelectOptions.Length - 1);
int pos = strSelectOptions.LastIndexOf(",");
if (pos != -1)
{
strSelectOptions = strSelectOptions.Remove(pos, 1);
strSelectOptions = strSelectOptions.Insert(pos, " & ");
}
lblresult.Text = "Selected Options:" + strSelectOptions;
}
else
{
lblresult.Text = "No Option Selected";
}
}
解决方案
Look at your code:
protected void btnsubmit_Click(object sender, EventArgs e) { string strSelectOptions = string.Empty; CheckBox ch = sender as CheckBox; if (ch.Checked)
hat is a button click event handler, so the chances are that thesender
is a button, not a CheckBox.
So this line:
CheckBox ch = sender as CheckBox;
will set
ch
tonull
, and any attempt to use a property or method will fail with a null reference exception.
Probably, you need to re-think what you are doing, or use the CheckBox name directly instead of trying to use thesender
parameter.
这篇关于我如何处理此问题...显示空引用异常是由用户代码解除的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文