我如何处理此问题...显示空引用异常是由用户代码解除的 [英] How Can I Handle This Problem...showing null reference exception was unhandle by user code

查看:81
本文介绍了我如何处理此问题...显示空引用异常是由用户代码解除的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  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 the sender is a button, not a CheckBox.
So this line:

CheckBox ch = sender as CheckBox;

will set ch to null, 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 the sender parameter.


这篇关于我如何处理此问题...显示空引用异常是由用户代码解除的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆