Fire button event manually - c#

I have a search text box on my WPF Windows. Whenever, the user presses enter key after writing some query in the textBox, the process should start.
Now, I also have this Search button, in the event of which I perform all this process.
So, for a texBox:
<TextBox x:Name="textBox1" Text="Query here" FontSize="20" Padding="5" Width="580" KeyDown="textBox1_KeyDown"></TextBox>
private void queryText_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Return)
{
//how do I fire the button event from here?
}
}

It is possible but rather move your search logic into a method such as DoSearch and call it from both locations (text box and the search button).

Are you talking about manually invoking buttonSearch_onClick(this, null);?

You can Create a Common Method to do search for ex
public void MySearch()
{
//Logic
}
Then Call it for diffetnt places you want like...
private void queryText_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Return)
{
MySearch();
}
}
private void buttonSearch_onClick(object sender, EventArgs e)
{
MySearch();
}

A event can not be fired/raised from outside the class in which it is defined.(Using reflection you can definitely do that, but not a good practice.)
Having said that, you can always call the button click event handler from the code as simple method call like below
private void queryText_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Return)
{
OnSearchButtonClick(SearchButton, null);
}
}

Related

C# Try to fire an event to call function

When I press enter, which enables the buttonEditClient_PressEnter function,
the buttonEditClient_ButtonClick function should be called.
private void buttonEditClient_PressEnter(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
//fire buttonEditClient_ButtonClick function
}
}
private async void buttonEditClient_ButtonClick(object sender, ButtonPressedEventArgs e)
{
//buttonEditClient_ButtonClick activated
}
In the Designer:
this.buttonEditClient.ButtonClick += new DevExpress.XtraEditors.Controls.ButtonPressedEventHandler(this.buttonEditClient_ButtonClick);
this.buttonEditClient.KeyDown += new System.Windows.Forms.KeyEventHandler(this.buttonEditClient_PressEnter);
If I try this:
private void buttonEditClient_PressEnter(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
buttonEditClient_ButtonClick(sender, e)
}
}
I get this error:
cannot convert from 'System.Windows.Forms.KeyEventArgs' to 'DevExpress.XtraEditors.Controls.ButtonPressedEventArgs'
How can I activate the buttonEditClient_ButtonClick function?
A click event is inherently different from a keyboard event (e.g., one includes information about the pressed mouse button and cursor position, the other about the pressed key), so you can't pass your KeyEventArgs to the click handler, which expects a ButtonPressedEventArgs.
You have a few simple options here:
Move your code from the button click handler to an extra function, and call that from both your handlers.
Find a way to create a new ButtonPressedEventArgs instance inside the key handler, and then pass that instead of the KeyEventArgs. This would be a very slipshod solution, as you're literally making stuff up (what cursor position are you going to give it?).
The first solution could look something like this:
private void buttonEditClient_PressEnter(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
buttonEditClientSubmit();
}
}
private async void buttonEditClient_ButtonClick(object sender, ButtonPressedEventArgs e)
{
buttonEditClientSubmit();
}
private void buttonEditClientSubmit()
{
// your code...
}
It depends on if you actually need anything from the ButtonPressedEventArgs. If you don't need anything from ButtonPressedEventArgs, you could just have both events call one function.
private void Handle_buttonEditClient()
{
// Do what you want to do when the button is pressed or has the "Enter"
// key pressed on it.
}
private void buttonEditClient_PressEnter(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
Handle_buttonEditClient();
}
}
private void buttonEditClient_ButtonClick(object sender, ButtonPressedEventArgs e)
{
Handle_buttonEditClient();
}
Note
I made buttonEditClick_ButtonClick synchronous, but if you leave it async the same thing applies. Just have both events call the same function.
If you need the ButtonPressedEventArgs, then it's like Anas Alweish says. You'll have to create an instance of ButtonPressedEventArgs. I'm not familiar with DevExpress, so I don't know how you'd do that. Maybe something like new ButtonPressedEventArgs(buttonEditClient)?;
DevExpress Docs on ButtonPressedEventArgs

Is there something similar in C# to fflush() from C?

My problem is:
The user can search an address. If there was nothing found, the user sees an messagebox. He can close it by pressing ENTER. So far, so good. Calling SearchAddresses() can also be started by hitting ENTER. And now the user is in an endless loop because every ENTER (to let the messagebox disappear) starts an new search.
Here the codebehind:
private void TxtBoxAddress_KeyUp(object sender, KeyEventArgs e)
{
if (e.Key == Key.Enter)
btnSearch_Click(sender, e);
}
private void queryTask_Failed(object sender, TaskFailedEventArgs e)
{
//throw new NotImplementedException();
MessageBox.Show("*", "*", MessageBoxButton.OK);
isMapNearZoomed = false;
}
And here the xaml code:
<TextBox Background="Transparent" Name="TxtBoxAddress" Width="200" Text="" KeyUp="TxtBoxAddress_KeyUp"></TextBox>
<Button Content="Suchen" Name="btnSearch" Click="btnSearch_Click" Width="100"></Button>
How can I handle this endless loop in C#?
Lol. Thats a funny infinate loop. Theres lots of answers.
Try adding a global string, _lastValueSearched.
private string _lastValueSearched;
private void TxtBoxAddress_KeyUp(object sender, KeyEventArgs e)
{
if (e.Key == Key.Enter && _lastValueSearched != TxtBoxAddress.Text)
{
//TxtBoxAddress.LoseFocus();
btnSearch_Click(sender, e);
_lastValueSearched = TxtBoxAddress.Text;
}
}
private void queryTask_Failed(object sender, TaskFailedEventArgs e)
{
//throw new NotImplementedException();
MessageBox.Show("*", "*", MessageBoxButton.OK);
isMapNearZoomed = false;
}
So on the first enter insider the TxtBoxAddress, the lastSearchValue becomes the new search value. When they press enter on the messagebox, if the TxtBoxAddress text hasn't changed, the if statement will not trigger.
Alternativly, the line commented out, TxtBoxAddres.LoseFocus() may work by itself. This should take the focus off of the TextBox, so when the user presses enter on the messagebox, the TextBox KeyDown shouldn't fire.
Use KeyPress event instead of KeyUp:
private void textBox_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == 13) // handle 'Enter' key
MessageBox.Show("test");
}

Why it is not Possible to call textBox1_KeyPress() event from some Button Click event.?

public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btn0_Click(object sender, EventArgs e)
{
MessageBox.Show("called btn 0 click..");
KeyPressEventArgs e0 = new KeyPressEventArgs('0');
textBox1_KeyPress(sender, e0);
}
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
MessageBox.Show("called txtbox_keypress event...");
}
}
Am sorry if this is a silly question,I have just started to learn windows forms, I still find material on the internet confusing.I want to implement calculator. So when number button is pressed it should be filled in textbox. So I thought calling textBox1_keypress() event from button click event would work??? but its not working,
I can manually write the logic in button click event to fill text in text box but if i do so, i have to do the same thing in button1_KeyPress event too. so it would be duplication of code right??...so i thought solution was to call textBox1_KeyPress() event from both button click event and button key press event...but its not working .So what should i do???..is there any other approach which should i follow.
so it would be duplication of code right??
Yes, it would be. So you can do
private void btn0_Click(object sender, EventArgs e)
{
CommonMethod(e);
}
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
CommonMethod(e);
}
private void CommonMethod(EventArgs e)
{
//Your logic here.
}
The TextBox KeyPress event handler (textBox1_KeyPress) is called after the user presses a key. The KeyPressEventArgs parameter includes information such as what key was pressed. So calling it from your btn0_Click method isn't going to set the text for the TextBox.
Rather, you want to (probably) append whatever number the user pressed to the text already present in the TextBox. Something like
private void btn0_Click(object sender, EventArgs e)
{
textBox1.Text += "0";
}
might be closer to what you're trying to accomplish.
You could put the logic in an extra function like so:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btn0_Click(object sender, EventArgs e)
{
NumberLogic(0),
}
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
// I don't know right now if e contains the key pressed. If not replace by the correct argument
NumberLogic(Convert.ToInt32(e));
}
void NumberLogic(int numberPressed){
MessageBox.Show("Button " + numberPressed.ToString() + " pressed.");
}
}
You don't want to tie the events together like that.
A key-press is one thing, handled in one way.
A button click is something totally different and should be handled as such.
The basic reason is this,
The button doesn't know what number it is, you need to tell it that.
A key-press on the other hand, knows what number was pressed.
If you REALLY want to, for some reason, you could use SendKeys to trigger your key-press event in a round-about way, from the button.
SendKeys.SendWait("0");
I can suggest to you to use an Tag Property of the Buttons. Put in it the value of each button in Design mode or in Constructor, create one button event handler for all buttons and use Tag value:
Constructor:
button1.Tag = 1;
button2.Tag = 2;
button1.Click += buttons_Click;
button2.Click += buttons_Click;
Event hadler:
private void buttons_Click(object sender, EventArgs e)
{
textBox1.Text = ((Button)sender).Tag.ToString();
}

Do logic on keypress down of textbox

I need to do some logic but only from a specific textbox. Trying to do some search it appears that there is no event for KeyDown or PreviewKeyUp for a textbox but for the entire window. So in XAML I have this
PreviewKeyUp="keyPressLogic"
Then have a method that looks like this;
private void keyPressLogic(object sender, KeyEventArgs e)
{
if ((e.Key == Key.Down) && (check focus command ) )
{
//My logic
return;
}
}
As you can see I cannot figure out the check focus command. So either I am missing the key check on the textbox or got to find the focus command
thanks
To get the textbox you pressed you should:
TextBox textbox = (TextBox)sender;
and then you can:
private void keyPressLogic(object sender, KeyEventArgs e)
{
if ((e.Key == Key.Down) && (textbox.IsFocused))
{
//My logic
return;
}
}
System.Windows.Controls.TextBox has an event caleed. Here you can find it.
It will trigger the KeyDown event only for the textbox you add it on.
Here is how you add it into your XAML
<TextBox x:Name="MyTextbox" KeyDown="MyTextbox_KeyDown" />
And here is how your event handler should look like
private void MyTextbox_KeyDown(object sender, System.Windows.Input.KeyEventArgs e)
{
if(e.Key == Key.Down)
{
// Add your logic here
}
}

Wire _KeyDown event of textbox to a _click event of button control

I have a form with a textbox called 'tbWO.' This field is used to enter a Purchase Order Number. I also have a button control called 'btnFill.' When btnFill is clicked, it fills a dataset with a parameter from 'tbWO.'
I would like to be able to press 'ENTER' in the 'tbWO' textbox (after a Purchase Order # is entered) and have it fire the btnFill_Click event I mentioned above.
I tried with this bit of errant, badly written code - but, it's just not working properly, i.e., at all, or how I think it should work. Anyway, the code is below; in all it's glory.
private void txtWO_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
btnFill.Click += new EventHandler(btnFill_Click);
}
}
I will admit confusion on using 'new EvenHandler( ?? ). Fairly new to C# (as is probably blantantly obvious.)
Any help, links, suggestions - all are greatly appreciated.
Thanks.
Jasoomian
you could do this...
private void txtWO_KeyUp(object sender, KeyEventArgs e) {
if (e.KeyCode == Keys.Enter) {
btnFill_Click();
}
}
As a rule, I abhor mapping one event handler to another. Instead, write a separate function, and have both event handlers invoke that separate function. Something like this:
private void txtWO_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
AcceptInput();
}
}
private void btnFill_Click(object sender, EventArgs e)
{
AcceptInput();
}
private void AcceptInput()
{
// Do clever stuff here when the user presses enter
// in the field, or clicks the button.
}
Granted, you may feel differently, but it accomplishes the same thing, but with (IMO) far more readable code. But it's been my experience that criss-crossing event handlers is very sloppy and leads to maintenance headaches out the wazoo.

Categories