button events vb vs c#

J

jhcorey

I've typically been working with VB.Net. When I want to create code
that runs when a button is clicked, I'll go to the code-behind, find
the button in the dropdown in the top left, then select the click event
in the dropdown in the top right. The ide then creates an empty
function and I type in my code.


Now I'm working with C#. I found that I could create the skeleton of
the function by clicking on the button in the design view of the page.
But now it seems it's messing things up.

For one thing, sometimes InitializeComponent gets cleared out.

Otherwise, I have some buttons working, but right now I'm trying to put
a button on a user control and load the control into a placeholder.

Here is code from the user control:

protected System.Web.UI.WebControls.Button btnRetrieve;
.....
private void InitializeComponent()
{
this.btnRetrieve.Click += new
System.EventHandler(this.btnRetrieve_Click);
this.Load += new System.EventHandler(this.Page_Load);
}
private void btnRetrieve_Click(object sender, System.EventArgs e)
{
}

When I try to run this, I get "Object reference not set to an instance
of an object" in the first line in InitializeComponent.

Any explanation would be appreciated.
TIA,
Jim
 
J

jhcorey

Most certainly.
Except that it's in my ascx. All of this is in a user control
(VendorsCtl.ascx).
In my page I have:
VendorsCtl myVendors = new VendorsCtl();
PlaceHolder1.Controls.Add(myVendors);

Jim
 
M

Marina

You should call LoadControl to load your .ascx:

VendorCtl myVendors = LoadControl("VendorsCtl.ascx")

A .ascx isn't just a class - it has a visual portion that is defined in the
..ascx. Just instantiating the class is not the same as having asp.net run
through the .ascx file itself, and create all the objects in the
corresponding class, etc.
 
K

Kevin Spencer

I don't see any code in your InitializeComponent() method that creates an
instance of the button and assigns it to the btnRetrieve field.

--
HTH,

Kevin Spencer
Microsoft MVP
..Net Developer
Everybody picks their nose,
But some people are better at hiding it.
 
J

jhcorey

Thanks,

I got there thanks to your suggestions.
This is what worked:
PlaceHolder1.Controls.Add(LoadControl("VendorsCtl.ascx"));

Jim
 
K

Kevin Spencer

Yeah, I caught the reference ot the User Control in the replies and related
correspondence. Good show!

--
HTH,

Kevin Spencer
Microsoft MVP
..Net Developer
Everybody picks their nose,
But some people are better at hiding it.
 

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

Top