onClick Function for created button with parameters - c#

I've created a button and now I need to create an onClick function for it.
I've found this sollution:
btnEasyLvl.Click += new EventHandler(Game);
...
protected void Game(object sender, EventArgs e)
{
//some actions
}
But what if my Game function has to accept some parameters (e.g. n,m,k). So that I'll need to write:
btnEasyLvl.Click += new EventHandler(Game(n,m,k));
How to rewrite it?

You can not pass parameters to Game because it is an event, and those have the predefined parameters object sender and Eventargs e, what you must do is create a method that receives these parameters and call it from the event
btnEasyLvl.Click += new EventHandler(Game);
protected void Game(object sender, EventArgs e)
{
//Here call the method SomeActions
SomeActions(n, m ,k);
}
private void SomeActions(n, m, k)
{
//some actions
}

Related

C# - Switch button event dynamically

Hy there,
i'm trying to change the button event when the code it's executing. So this is my code:
// I will call this function in many places of my code and send a callback function.
// For example, when i click in the confirm button, the event that will be called it's the Callback()
void ShowModal<T>(string Title, IList<T> Data, Func<object, EventArgs, int> Callback)
{
this.lblTitle.Text = Title;
this.gvResults.DataSource = Data;
this.gvResults.DataBind();
// Executes the sended function when click
this.lkbConfirm.Click += new EventHandler(
(object sender, EventArgs e)
=> Callback(sender, e)
);
this.ModalBusca.Show();
}
// I call the ShowModal function
this.ShowModal("Search", data, CallbackSelect);
// This function will be execute
int CallbackSelect(object sender, EventArgs e)
{
// my code to execute
return 0;
}
But the CallbackSelect function is not called.
I'm using Asp.NET 4.7 web application, thanks!

Why XAML button can't invoke argumentless function

I have function in create.cs
private void FillGrid()
{
ClearingEntities CE = new ClearingEntities();
var Accountss = CE.Accounts;
DataGrid1.ItemsSource = Accountss.ToList();
}
I invoke this function from other .cs files just writing FillGrid(); without any arguments
but from xaml in button Click="FillGrid" gives error
click auto generated functions have
private void Button_Click(object sender, RoutedEventArgs e)
I don't want insert those object sender, RoutedEventArgs e arguments
if I insert those to my function's arguments then other calling should be changed
to
FillGrid([argument],[argument]);
note: it is not event handling function just fill data stuff
how to call FillGrid() from xaml? without changing create.cs
This is just the way Button Event's work.
Read more about EventHandler here
Why don't you just use this:
<Button Click="FillGridClicked" />
//sender = button, RoutedEventArgs = arguments of that event
private void FillGridClicked(object sender, RoutedEventArgs e)
{
FillGrid();
}
Every ClickEventHandler needs these arguments as it is a custom delegate defined that way. If you really want to emit this you need to extend the button and create a custom click handler for yourself. (see this for example)

How to use a single button click event to call a method with different parameters

I have multiple button click events:
private void button1_Click(object sender, EventArgs e)
{
Procedure(1);
}
private void button16_Click(object sender, EventArgs e)
{
Procedure(16);
}
However, I want to achieve something like this:
private void button[i]_Click(object sender, EventArgs e)
{
Procedure(i);
}
In Winforms, there is a call to InitializeComponent() in the class constructor.
In that method (it will take you to the form designer if you put the mouse cursor on the method and right click > goto definition or F12) you will see how events are hooked up:
button1_Click += button1_Click...
You can simply subscribe the buttons click event to your Procedure method.
button1_Click += CallToProcedure;
How do you work out which button was clicking then? You simply get it off the sender argument in the parameter:
private void CallToProcedure(object sender, EventArgs e)
{
Button btn = sender as Button;
int i = Convert.ToInt32(btn.Name.Replace("button", string.Empty));
Procedure(i);
}
You can store the parameter you're passing to your button (i in your example) in the Button's Tag property then use something like this:
var senderButton = sender as Button;
if (sender != null)
{
Procedure((int) senderButton.Tag);
}
If you can rely on the naming, then simple:
private void button_Click(object sender, EventArgs e)
{
Button btn = sender as Button;
int i = Convert.ToInt32(btn.Name.Replace("button", ""));
Procedure(i);
}
use button.Tag property, is designed for such cases.
read is doc / MSDN

No overload for 'dateTimePicker1_ValueChanged' matches delegate 'System.EventHandler'

private void dateTimePicker1_ValueChanged(object sender, Series myseries, int multiplier, EventArgs e)
{
if (datelimitsset == 1) {
var dt1 = dateTimePicker1.Value;
chart1.Series.Clear();
for (int i = 0; i < multiplier; i++)
{
config();
myseries.Points.AddXY(Convert.ToString(date[i]), Convert.ToDouble(array[i]));
string[] rowi = { Convert.ToString(date[i]), Convert.ToString(array[i]) };
dataGridView1.Rows.Add(rowi);
}
}
}
This is giving me the error:
No overload for 'dateTimePicker1_ValueChanged' matches delegate 'System.EventHandler'
I do not fully understand event handlers, can anyone give me advice?
The signature for System.EventHandler is (object sender, EventArgs e) so you either need to change your method signature to this:
private void dateTimePicker1_ValueChanged(object sender, EventArgs e)
Or keep your current signature and use a lambda expression as a delegate adapter when you subscribe to the event:
dateTimePicker1.ValueChanged += (object sender, EventArgs e) =>
dateTimePicker1_ValueChanged(sender, [your Series variable], [your int multiplier variable], e);
When you use a lambda expression as a delegate adapter, you are essentially creating a delegate which conforms to the System.EventHandler signature (it is passed an object and an EventArgs argument), which then calls your original handler method passing all of the arguments required to satisfy your dateTimePicker1_ValueChanged method.
The reference documentation for the System.EventHandler delegate.
EDIT: documentation for an example handler for the DateTimePicker.ValueChanged event
It's because your handler must have the same signature specified by the EventHandler delegate.
That is, you'll have to remove your two middle parameters:
private void dateTimePicker1_ValueChanged(object sender, EventArgs e)
{
}
In terms of a workaround for passing these parameters into the function, you have a few options...
Generate the event handler as an anonymous function (as per James' answer)
Store and retrieve them from instance variables
Store them on the DateTimePicker control's Tag property and resolve them in the handler
The second option should be obvious enough...
The third option might look like:
// In control initialization somewhere
dateTimePicker1.Tag = new DateTimePickerParams() { Series = myseries, Multiplier = multiplier }; // Where DateTimePickerParams is your own private class/struct defined explicitly for this purpose...
private void dateTimePicker1_ValueChanged(object sender, EventArgs e)
{
var ctl = sender as DateTimePicker;
var parameters = ctl.Tag as DateTimePickerParams;
var mySeries = parameters.Series;
var multiplier = parameters.Multiplier;
// Execute...
}
You can't add arbitrary parameters to the event handler like that, the method signature must match the event delegate. How would the DateTimePicker know what to pass for the myseries and multiplier parameters?

Calling click event of a button serverside

How can I click or load the click() event of a button in codebehind?
I already tried
btn.Click();
but this gives an error. I am using ASP.NET
I will assume that you have a button called Button1
and that you have double clicked it to create an event handler.
To simulate the button click in code, you simply
call the event handler:
Button1_Click(object sender, EventArgs e).
e.g. in your Page Load Event
protected void Page_Load(object sender, EventArgs e)
{
//This simulates the button click from within your code.
Button1_Click(Button1, EventArgs.Empty);
}
protected void Button1_Click(object sender, EventArgs e)
{
//Do some stuff in the button click event handler.
}
If you don't need the context provided by the sender and eventargs then you can just refactor to create a method (eg DoStuff()) and make your event handler just call that. Then when you want to call the same functionality from elsewhere you can just call DoStuff(). It really depends on whether you want to actually simulate a click or not. If you want to simulate a click then other methods are better.
Do you wish to call all the event handlers attached to the button, or just one?
If just one, call the handler:
btn.btn_Click(btn, new EventArgs());
If all of them, trigger the event:
var tmpEvent = btn.Click;
if (tmpEvent != null)
tmpEvent(btn, new EventArgs());
Try this:
YourButton_Click(sender, e);
Edit try this:
protected void Page_Init(object sender, EventArgs e)
{
Button1.Click += new EventHandler(Button1_Click);
}
void Button1_Click(object sender, EventArgs e)
{
}
in the .cs page
Just call the buttons click function.
http://forums.asp.net/t/1178012.aspx
Instead of trying to call the event just call the function that event uses.
Example: btn.Click() calls
btn_Click(object sender, EventArgs e)
so you should call the function btn_Click(btn,new
EventArgs());
It's been a long time ago, but here is my solution
You can use:
btn.PerformClick();
protected void Page_Load(object sender, EventArgs e)
{
functionName();
}
protected void btn_Click(object sender, EventArgs e)
{
functionName();
}
public void functionName()
{
//function code goes here, and call this function where ever you want
}
try this one.......
YourButton.RaiseEvent(new RoutedEventArgs(Button.ClickEvent));
This works for me.

Categories

Resources