0

while clicking on button it give me an error "System.NullReferenceException: Object reference not set to an instance of an object"

aspx Code

<body>
    <form id="form1" runat="server">
    <div id="choto">

    </div>
  <asp:Button ID="btn" runat="server" onclick="btn_Click" Text="Submit" />
</form>
</body>

JS code

  <script type="text/javascript">

        document.getElementById("choto").innerHTML = "<input name=txt1 type=\"text\" id=\"txt1\" ru" + "nat=\"server\" />";
</script>

C# code

 protected void btn_Click(object sender, EventArgs e)
        {
           // HtmlInputText txt = new HtmlInputText();
            HtmlInputText txt = (HtmlInputText)FindControl("txt1");
            txt.Value = "Shakeel";
        }
1
  • 1
    possible duplicate of What is a NullReferenceException and how do I fix it?. Obviously, there is no control named "txt1", but you will have to debug to figure out why there isn't when you thought there should be. See the duplicate question for helpful recommendations on how to do that. Commented Feb 22, 2015 at 6:59

1 Answer 1

1

Simply put, the input with the id "txt1" is not an ASP.NET control, therefore ASP.NET cannot find it. ASP.NET controls must be defined on the server, or the framework won't know about them.

<body>
    <form id="form1" runat="server">
    <div id="choto">
        <asp:TextBox ID="txt1" runat="server" style="display:none;" />
    </div>
  <asp:Button ID="btn" runat="server" onclick="btn_Click" Text="Submit" />
</form>
</body>

ASP.NET controls cannot be added via JavaScript, however, they can be made to be invisible/visible using JavaScript.

<script type="text/javascript">
    document.getElementById('<%# txt1.ClientID %>').style.display = "block";
</script>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.