Can't Access to TextBox threw WebControl

N

Nimrod Rotner

Hi All,
I can't understand what is the problem. I am using web control wich has a text box ob it and a public property that set and get that TextBox text value.

The compilation pass but when i try to get or set that property, i get: "Object Reference no set to an instance of an object."

Here is my Code:
----------------
public class WebUserControl1 : System.Web.UI.UserControl
{
private string num;
protected System.Web.UI.WebControls.TextBox txtName;
public string txt
{
get
{
return txtName.Text;
}
set
{
txtName.Text=value;
}
}

private void Button1_Click(object sender, System.EventArgs e)
{

WebUserControl1 ctl=new WebUserControl1();

Response.Write(ctl.txt);
 
P

PlatinumBay

Nimrod,

While your code may compile, you are creating a new WebUserControl1 object.
Unless the constructor of that object instantiates the txtName object, you
will get the Object Reference exception trying to access the Text property
of the txtName object.

Hope this helps,


Steve
 
N

Nimrod Rotner

Hi,
Thanks for your fast reply. Can you tell me how should i write that init
code for the text box in the constructor ?


Thanks
 
M

marss

Nimrod said:
WebUserControl1 ctl=new WebUserControl1();

Hi,
I guess txtName is the TextBox control that is defined elsewhere in
the WebUserControl1.ascx file.
It is not initialized because you use incorrect method to create
instance of the user control.
Creation by means of "new" operator is suitable for a web control but
not for a user control.
Use next approach:

WebUserControl1 ctl = (WebUserControl1)LoadControl("~/.../
WebUserControl1.ascx");

Regards, Mykola
http://marss.co.ua
 
P

PlatinumBay

Nimrod,

Your initialization in the constructor would look like:

public WebUserControl1
{
this.txtName = new System.Web.UI.WebControls.TextBox();
// possibly set a default value
this.txtName.Text = "";
}

Hope this helps,


Steve
 
P

PlatinumBay

Nimrod,

You can also initialize it when it is declared, for example:

protected System.Web.UI.WebControls.TextBox txtName = new
System.Web.UI.WebControls.TextBox();

Hope this helps,


Steve
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top