CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 6 of 6
  1. #1
    Join Date
    Apr 2004
    Location
    Austria
    Posts
    43

    Create Buttons from Source and add Events

    Hi. I have got a problem and I hoped you would help me.

    I use this function to create a button within an application

    private void AddButton(string Text)
    {
    Button cmdTest = new Button();
    pnlContainer.Controls.Add(cmdTest);
    }

    I was wondering why C# wasn't complaining there are multiple buttons with the same name.. but there seems to be no problem.

    So my next problem is that I need to have buttons created at runtime (that's the point) that should trigger an event (a simple example would do .. I am not quite too familiar with events and delegates).

    greetings UNI

  2. #2
    Join Date
    Apr 2004
    Posts
    17

    Here you go

    Code:
    private void AddControl()
    {
    Button btn = new Button();
    btn.click += new EventHandler(Button_Click);
    pnlControls.Controls.Add(btn);
    }
    
    private void Button_Click(object sender, EventArgs e)
    {
    //Do some stuff
    }
    you can also use the -= to remove an eventhandler.

  3. #3
    Join Date
    Apr 2004
    Location
    Austria
    Posts
    43
    thanks a ton

    greetings UNI

  4. #4
    Join Date
    Apr 2004
    Location
    Austria
    Posts
    43
    additional question.

    How can I access the object that was clicked?

    sender has only got the equals, gettype and tostring functions, i need to access things like height, width, text and tag of that commandbutton.

    I tried already

    Button cmdTest = sender;
    but that doesn't work

    greetings UNI

  5. #5
    Join Date
    Apr 2004
    Posts
    17

    object sender

    Sorry its taken so long to reply internet has been playing up..

    you need to cast the object as a button..


    Code:
    private void Button_Client(object sender, EventArgs e)
    {
    Button btn = (Button)sender;
    btn.Text = "This is the nuts";
    //You can also do it like this..
    ((Button)sender).Text = "Yeah Baby !!";
    }
    Cool ?

  6. #6
    Join Date
    Apr 2004
    Location
    Austria
    Posts
    43
    perfect.. I love you

    sorry.. but my deadline is 17:45 and I just had the problem how to cast a form..

    god I should have listened to what the guy at university told us about Java.. it's the same there

    greetings UNI

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured