开发者

asp.net object reference not set error

I am trying to find the label control from aspx page.

Label labelmessageupd开发者_如何学Goate;
          labelmessageupdate = (System.Web.UI.WebControls.Label )FindControl("updateMessage1");

if i set labelmessageupdate.Text ="something"

it returns object reference exception.

and the label control is within the update panel could that be the problem.


Just check for null. Always check null condition so that it doesn't end up showing Object Reference error.

if (labelmessageupdate != null)
{
     labelmessageupdate.Text ="something"
}


I think its not able to find the label control you specified

if(FindControl("updateMessage1") is Label)
{
    labelmessageupdate = FindControl("updateMessage1") as Label;
    labelmessageupdate.Text="This shoould work if available";
}


Try this, and the control your trying to find could be in a another user control.

To use

Label updateMessage = FindChildControl<Label>(base.Page, "updateMessage1");
if (updateMessage!=null) 
{
   updateMessage.Text = "new text";
}

/// <summary>     
/// Similar to Control.FindControl, but recurses through child controls.
/// Assumes that startingControl is NOT the control you are searching for.
/// </summary>
public static T FindChildControl<T>(Control startingControl, string id) where T : Control
{
    T found = null;

    foreach (Control activeControl in startingControl.Controls)
    {
        found = activeControl as T;

        if (found == null || (string.Compare(id, found.ID, true) != 0))
        {
            found = FindChildControl<T>(activeControl, id);
        }

        if (found != null)
        {
            break;
        }
    }

    return found;
} 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜