1

I am trying to convert my HTML String to control in C# asp.net and I am getting this below error "Exception Details: System.NullReferenceException: Object reference not set to an instance of an object."

I did searching since last five-6 hours. Already go through so many answers in the internet including Stackoverflow. But non of answers solved my query. Thanks in advance for replay

protected TextBox t2;
protected override void OnInit(EventArgs e)
{

String Str ="<input  type="text" id="txtID" class="form-control" runat="server"  />";
LiteralControl lt = new LiteralControl();
lt.Text = Str;
t1.Controls.Add(lt);
t2 = (TextBox)t1.FindControl("txtID");
t2.Text = "Maddsf";
}
Gagandeep
  • 59
  • 2
  • 10
  • That is definitely your code? I am surprised it compiles. – mjwills Jan 19 '19 at 12:31
  • When you debug through it, is `t2` null? – mjwills Jan 19 '19 at 12:31
  • The short answer is that `LiteralControl` is not what you want to use here. I think you have misunderstood what it is for. See the duplicate I suggest. – mjwills Jan 19 '19 at 12:32
  • You can't generate a control that runs at the server side by adding a string to your document. Instead, why don't you just declare it in your markup and selectively hide/show it? – mason Jan 19 '19 at 14:26

1 Answers1

0

The following line will give you the error:

t2.Text = "Maddsf";

Cause: Because the FindControl() method gives you a web control. However, txtID is not a web control and that's why FindControl() method fails to return a web control (TextBox in this case) and instead returns a null value. What you have assigned to the Text property of the Literal control lt is an input text field which would be successfully rendered by the browser. However, ASP.NET has no knowledge that the control exists.

Solution: For this very same reason, you would be able to get a reference to the control in JavaScript. Something like this:

document.getElementById("txtID").value = "Maddsf";
Tanveer Yousuf
  • 386
  • 1
  • 3
  • 16