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
    possible duplicate of [What is a NullReferenceException and how do I fix it?](http://stackoverflow.com/questions/4660142/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. – Peter Duniho Feb 22 '15 at 06:59

1 Answers1

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>
NightOwl888
  • 55,572
  • 24
  • 139
  • 212