Craig
Craig

Reputation: 18704

Buttons OnClick event in .aspx instead of .cs file

I'm creating a small asp.net app, and I'm facing an issue that may be pretty simple to fix.

On my masterpage, I have a 'Login' button. I've put the button on the form, double clicked it, and the OnClick event is placed within the .cs file as I am expecting.

protected void btnLogin_Click(object sender, EventArgs e)
{
    var u = new UserDto
        {
            Password = txtPassword.Text,
            Username = txtUsername.Text,
            validated = false
        };

    var us = new UserService().ValidateUser(u);
    if (us.validated)
    {
      // Etc etc
    }
}

I have now redirected to another page, which has a few gridviews and objectdatasources. I then added a new button to that form, the same way as I did on the login form:

<asp:Button ID="btnCreateProject" runat="server" Text="Create New Project" />

But now, when I double click the button in the designer, to create an OnClick event, the OnClick event gets created in the aspx file!

<script runat="server">

    protected void btnCreateProject_Click(object sender, EventArgs e)
    {

    }
</script>

Firstly, why is this happening? And secondly, how do I get this to go into my .cs file?

Upvotes: 0

Views: 7005

Answers (4)

Angwenyi
Angwenyi

Reputation: 329

Its worth mentioning also adding this to your .aspx page
AutoEventWireup="true" CodeFile="PageName.aspx.cs" Inherits="PageName"

Will bring the OnClick events to your .cs page.

Upvotes: 0

Jayesh Goyani
Jayesh Goyani

Reputation: 11154

Please check the "Please code in separate file" checkbox when you add new page in your project. For more information please check below screenshot.

enter image description here

Upvotes: 0

steve cook
steve cook

Reputation: 3214

When you click 'Add New Item' and select 'Web Form' to add the page to your project, you should notice a checkbox on the right hand side that says 'Place code in separate file'. Sounds like the second page didn't have this checked, which is why it tries to embed the code in the web page itself.

Upvotes: 1

gillyb
gillyb

Reputation: 8910

Just copy the method to your .cs file without the script tags and it should work.

Also, make sure you have the OnClick event on your button in the .aspx file:
<asp:Button ID="btnCreateProject" runat="server" Text="Create New Project" OnClick="btnCreateProject_Click" />

Upvotes: 0

Related Questions