Search code examples
asp.netfunctionvariableswebformsbehind

ASP.NET passing variables from web form to code behind


i'm developing a web application for my company, but i'm coming up against a very simple problem that i don't now how to resolve. I search a lot on internet but i can't find anything. I need to call a code behind method from an asp.net controls passing variables.

This is the method in the code behind (file.aspx.cs):

protected void SayHello(object sender, EventArgs e, String RandomName)
{
  Response.Write(PrintedString);
 }

And this is a asp.net control that call the method through OnLoad event :

<asp:Label ID="Label1" runat="server" Text="Hello" OnLoad="Visibility('ciao mamma')"></asp:Label>

What's wrong with this simple thing? Where i'm wrong?

Please answer to this simple question, it's driving me crazy...Thanks.


Solution

  • You can pass an argument to the event handler by the following way, but please note it will work for only asp button.

    <asp:Button ID="btn" runat="server" Text="Click" OnCommand="btn_Command" CommandArgument="YourArgumentValue"/>
    

    and then in the code behind file you do like this :

    protected void btn_Command(object sender, CommandEventArgs e)
    {
       Response.Write(e.CommandArgument);
    }
    

    It will work for only asp button because they have a onCommand attribute with them.

    whenever you will click on the button this code behind file code gets executed.

    Hope this helps.