这段代码给我错误(System.NullReferenceException:对象引用未设置为对象的实例.) [英] This code give me error( System.NullReferenceException: Object reference not set to an instance of an object.)

查看:109
本文介绍了这段代码给我错误(System.NullReferenceException:对象引用未设置为对象的实例.)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

private void ReadTextBoxes()
{
    string strValue = string.Empty;
    int n = NumberOfControls;
    Panel pnl = (Panel)Page.FindControl("Panel1");

    for (int i = 0; i <= NumberOfControls; i++)
    {
        //:confused: This line Give me error please give me solution
        string boxName = "TextBoxID" + (i + 1).ToString();


        TextBox tb = pnl.FindControl(boxName) as TextBox;
        strValue += tb.Text + "\n";

    }
    Response.Write(strValue);

}

推荐答案

您要么将Panel Object值获取为null,要么将Textbox Object值获取为null.


原因1:
错误行必须为:
strValue + = tb.Text +"\ n";

我看到的Issue1:
Either you are getting Panel Object value as null or textbox Object value as null.


REASON 1:
Error line must be:
strValue += tb.Text + "\n";

Issue1 to me looks at:
strValue += tb.Text + "\n";



看起来您在这里获取tb值的"null":



Looks like you are getting "null" for tb value here:

TextBox tb = pnl.FindControl(boxName) as TextBox;



原因:



Reason:

string boxName = "TextBoxID" + (i + 1).ToString();




原因2:
错误行必须为:
TextBox tb = pnl.FindControl(boxName)作为TextBox;

如果pnl值为null,则此行将引发错误.

我看到的Issue2:




REASON 2:
Error line must be:
TextBox tb = pnl.FindControl(boxName) as TextBox;

If pnl value is null, then this line would throw an error.

Issue2 to me looks at:

TextBox tb = pnl.FindControl(boxName) as TextBox;



看起来您在这里获取"null"的pnl值:



Looks like you are getting "null" for pnl value here:

Panel pnl = (Panel)Page.FindControl("Panel1");



检查您是否有名为"Panel1"的面板.

===========
我认为您指定的位置肯定不会出错.



Check that you have "Panel1" named Panel with you.

===========
I don''t think you must be getting error at the location specified by you.

string boxName = "TextBoxID" + (i + 1).ToString();



这句话没有错.



There is nothing wrong with this statement.


这篇关于这段代码给我错误(System.NullReferenceException:对象引用未设置为对象的实例.)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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