Hello everyone,
i am having problems in passing arguments to the event handler which i am trying from the past 2 days and not able to solve it.

my code looks like this below. I try to Create a button for the tabpages dynamically.Lets say we have 4 tabpages and i have created 4 buttons for each of these tabpages. When i click on the button of the 2nd tab page i would like to send the name of the this tabpage to my event handler in order to send it as an argument for the method(addform) that i call in the event handler..however tp.text takes always the last tabpage name in the event handler and not the 2nd tabpage.

would be gratefull for any help


thank u

public bool CreateButton(TabPage tp, Object parentobj)
{
Button button = new Button();
button.Location = new System.Drawing.Point(250,440);

globalTabname= tp.Text;
tp.Controls.Add(button);
parentglobalobj = parentobj;
button.Click += new EventHandler(handler1);
return true;
}

public void handler1(object sender, EventArgs e)
{
// i need to also get the tp.text to send it as an argument to the method addform
test.addform(parentglobalobj);
}

ive edited the handler1... plz dont refer to the previous handler which i posted


public void handler1(object sender, EventArgs e)
{
// tp.text takes the last tabpage name n not the tabpage from where the respective button was created
test.addform(parentglobalobj, tp.text);
}

Problem is, that the tp variable you created as a param for your create button function is not valid in the event handler.

Outside of the method, tp either doesn't exist, or refers to a variable at a higher up scope.

to point to which tab control fired the button you would want you handler to check what button was pressed using the events sender object, then check what control it lies on.

Happy Coding

well more specifically you must cast the sender to its actual type. which is a button, then get its parent object. here you go, i will just write it for you.

public void handler1(object sender, EventArgs e)
{//create a button variable to hold pointer to button that called event
Button mb = (Button)sender;
//create var to hold its parent container, this case the 2nd tab page
string btnParentText = mb.Parent.Text;
// tp.text takes the last tabpage name n not the tabpage from where the respective button was created
test.addform(parentglobalobj, btnParentText);
}

Sorry no one helped you sooner, 2 days is a long time to be stuck.

thank you for ur help ..i however solved it

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.