【问题标题】:Getting error in ASP.Net page在 ASP.Net 页面中出现错误
【发布时间】:2012-08-22 21:31:59
【问题描述】:

能否请您告诉我为什么以下代码不起作用,当调试器通过变量“strStatus”时,我收到错误消息。错误消息是:“对象引用未设置为对象的实例。”你能帮忙吗?谢谢-Yagya

    protected void Button1_Click(object sender, EventArgs e)
    {
        if (Y0130_chkNew.Checked == true)
        {
            bool isChecked = true; // This is required for later retrieval.

            string strAction = "Reporting";
            string strFromRole = ddSelectRole.SelectedValue;

            string TxtBoxID = myProject.getTextBox(strAction, strPath);
            TextBox txtb = new TextBox();
            txtb = (TextBox)Page.FindControl(TxtBoxID);
            string strStatus = txtb.Text;

            string ddID = myProject.getDropDown(strAction, strPath);
            DropDownList ddLst = new DropDownList;
            ddLst = (DropDownList)Page.FindControl(ddID);
            string strForwardRole = ddLst.SelectedValue;

            // Call the function now
            my.updateXML(strFromRole, strAction, strStatus, strForwardRole, strPath);

        }

    }

【问题讨论】:

  • string TxtBoxID = myProject.getTextBox(strAction, strPath); 是什么意思?你能展示那个方法吗?除此之外,Page.FindControl(TxtBoxID); 返回 null 什么是您的异常的原因。 FindControl 不递归搜索控件,仅在给定的 NamingContainer 中搜索。

标签: asp.net


【解决方案1】:

Page.FindControl(TxtBoxID); 返回 null 你的异常的原因是什么。 FindControl 不递归搜索控件,仅在给定的 NamingContainer 中搜索。

如果控件没有嵌套在页面上的另一个NamingContainer 中(例如GridViewRow),则根本没有理由使用FindControl,因为您可以直接引用它:

string strStatus = TextBox1.Text; // assuming TextBox1 is declared on the aspx

如果您使用MasterPages,则ContentPage 中的控件NamingContainer 不是页面而是ContenPlaceHolder

Cannot find TextBox on Page

【讨论】:

  • 嗨 - 函数 getTextBox 从给定参数的 XML 文件中检索文本框的 ID。我仔细检查了该 ID 是否已成功检索并存在于网页中。另请注意,控件的 ID 在整个项目中是唯一的。不确定这里有什么问题。我使用母版页只是为了具有一致的外观和感觉以及用于站点导航目的。你有一个观点。让我检查在母版页中使用内容占位符是否可以解决此问题。感谢您的投入。
  • 最后它通过使用以下语句起作用:txtb = (TextBox)Page.Master.FindControl("ContentPlaceHolder1").FindControl(TxtBoxID);
【解决方案2】:

您正在寻找一个使用函数的控件,并且可能会返回一个在 page 上不存在的文本框 id。请尝试调试并查看您从 myProject.getTextBox 函数获得的文本框 id 以及页面上是否存在。

【讨论】:

    【解决方案3】:

    最终代码: if (Y0130_chkNew.Checked == true)
    {
    字符串 TxtBoxID = "Y0140_txtStatus"; 文本框 txtb = new TextBox();
    txtb = (TextBox)Page.Master.FindControl("ContentPlaceHolder1").FindControl(TxtBoxID);
    字符串 strStatus = txtb.Text;

                string ddID = "Y0150_ddOwnerRoleAssignment";
                DropDownList ddLst = new DropDownList();             
                ddLst = (DropDownList)Page.Master.FindControl("ContentPlaceHolder1").FindControl(ddID);            
                string strForwardRole = ddLst.SelectedValue;                       
            } 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-06-17
      • 2010-10-17
      • 1970-01-01
      • 1970-01-01
      • 2012-05-11
      • 2016-09-07
      • 2023-03-17
      • 2017-01-23
      相关资源
      最近更新 更多