Call button click event on pressing Enter - c# [duplicate] - c#

This question already has answers here:
C# How do I click a button by hitting Enter whilst textbox has focus?
(13 answers)
Closed 9 years ago.
I am new to c# - I want to trigger button click event on pressing enter. My code not working properly -
issue is that when i press enter on submitting some value, it displays messagebox which it should show but on pressing Enter for OK button of Messagebox, it automatically triggers button click event again even i don't press enter or enter any other value.
public partial class Form1 : Form
{
int n1, n2 = 0;
private static readonly Random getrandom = new Random();
private static readonly object syncLock = new object();
public int GetRandomNumber(int min, int max)
{
lock (syncLock)
{ // synchronize
return getrandom.Next(min, max);
}
}
public int tQuestion()
{
n1 = GetRandomNumber(2, 11);
n2 = GetRandomNumber(2, 11);
string tQues = n1 + " x " + n2 + " = ";
label1.Text = tQues;
return 0;
}
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
tQuestion();
}
private void label1_Click(object sender, EventArgs e)
{
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
textBox1.KeyDown += new KeyEventHandler(tb_KeyDown);
}
public void button1_Click(object sender, EventArgs e)
{
string tAns = textBox1.Text;
int answer = n1 * n2;
string tOrgAns = answer.ToString();
if (tAns == tOrgAns)
MessageBox.Show("Your answer is Corect", "Result", MessageBoxButtons.OK,MessageBoxIcon.Exclamation );
else
MessageBox.Show("Your answer is WRONG", "Result", MessageBoxButtons.OK, MessageBoxIcon.Stop);
textBox1.Text = "";
textBox1.Focus();
tQuestion();
}
static void tb_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
button1_Click(sender, e);
}
}
Moreover, code only works if i remove static from static void tb_KeyDown(object sender, KeyEventArgs e) - otherwise it gives error:
An object reference is required for the non-static field, method, or
property
Please help me - i am new to c# & .Net

Extract button click event handler into separate method (e.g. VerifyAnswer) and call it from both places:
public void button1_Click(object sender, EventArgs e)
{
VerifyAnswer();
}
// NOTE: static modifier removed
private void tb_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
VerifyAnswer();
}
private void VerifyAnswer()
string tAns = textBox1.Text;
int answer = n1 * n2;
string tOrgAns = answer.ToString();
if (tAns == tOrgAns)
MessageBox.Show("Your answer is Corect", "Result", MessageBoxButtons.OK,MessageBoxIcon.Exclamation );
else
MessageBox.Show("Your answer is WRONG", "Result", MessageBoxButtons.OK, MessageBoxIcon.Stop);
textBox1.Text = "";
textBox1.Focus();
tQuestion();
}
Don't try to manually execute event handlers - their purpose is handling events only.

You are calling while textbox is focused. Better option is to create a separate function and call that from both.
I have made changes to your code. It's working for me. You need to link tb_keyDown event with keyDown property in Textbox Properties.
Try this code:
public partial class Form1 : Form
{
int n1, n2 = 0;
private static readonly Random getrandom = new Random();
private static readonly object syncLock = new object();
public int GetRandomNumber(int min, int max)
{
lock (syncLock)
{ // synchronize
return getrandom.Next(min, max);
}
}
public int tQuestion()
{
n1 = GetRandomNumber(2, 11);
n2 = GetRandomNumber(2, 11);
string tQues = n1 + " x " + n2 + " = ";
label1.Text = tQues;
return 0;
}
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
tQuestion();
}
private void label1_Click(object sender, EventArgs e)
{
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
//make it empty. You need to attach tb_KeyDown event in properties
}
public void button1_Click(object sender, EventArgs e)
{
CheckAnswer();
}
void tb_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
CheckAnswer();
}
}
private void CheckAnswer()
{
string tAns = textBox1.Text;
int answer = n1 * n2;
string tOrgAns = answer.ToString();
if (tAns == tOrgAns)
MessageBox.Show("Your answer is Corect", "Result", MessageBoxButtons.OK,MessageBoxIcon.Exclamation );
else
MessageBox.Show("Your answer is WRONG", "Result", MessageBoxButtons.OK, MessageBoxIcon.Stop);
textBox1.Text = "";
textBox1.Focus();
tQuestion();
}
}

You might want to use a static parameterless keylistener, which you could have running separately in the static method to check for key input. And then parse the key inputs there

That's because of this code:
static void tb_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
button1_Click(sender, e);
}
}
Remove that handler and set the AcceptButton of the Form to button1. The AcceptButton is a property you can simply set in the designer.

You cannot access instance members from static members
Either you have to
Make the method an instance method (remove the static keyword)
Make the field/method a static (add the static keyword)
The one you choose will depend on whether the field should be shared across all instances or not.
Hope it will help

Are you looking for that
button1.PerformClick()

Don't attempt to trigger a button click. Essentially what you should do is refactor your code so that the event handlers are separated from the actual implementation. e.g.
ButtonClick(...)
{
ExecuteMethod();
}
KeyDown(...)
{
ExecuteMethod();
}
ExecuteMethod()
{
// Actual implementation.
}
This disassociates the event you are subscribing to from the implementation. That way, in the future, if you wish to add new buttons or change around event handlers, your actual logical implementation remains unchanged.

please, check below options:
(1)Can you not use AcceptButton in for the Forms Properties Window? This sets the default behaviour for the "Enter" key press, but you are still able to use other shortcuts.
(2)
static void tb_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == (char)13)
{
button1_Click(sender, e);
}
}

Related

Call method inside a Form

Hi I am learning C# and struggling with a Form in which a btnCalc_click event should call a method calcArea and produce the output in a textBox1.text
the error is in row: textBox1.Text = calcArea.ToString();
who can help with with the correct syntax ?
namespace Meetkunde
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void txbLengte_TextChanged(object sender, EventArgs e)
{
double length = 0;
length = double.Parse(txbLength.Text);
}
private void txbBreedte_TextChanged(object sender, EventArgs e)
{
double width = 0;
width = double.Parse(txbWidth.Text);
}
public double calcArea(double length, double width)
{
double area = 0;
area = (length * width);
return area;
}
private void label3_Click(object sender, EventArgs e)
{
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void btnCalc_Click(object sender, EventArgs e)
{
textBox1.Text = calcArea.ToString();
}
}
}
As I mentioned above - you need to pass the method the parameters as you defined them in the method. You don't need Text Changed events for this either - plus they aren't doing anything.
Try changing your code to something like (not real sure of what exactly you named textboxes):
private void btnCalc_Click(object sender, EventArgs e)
{
double width = Convert.ToDouble(txbBreedte.Text);//txbWidth.Text?
double length= Convert.ToDouble(txbLengte.Text);//txbLength.Text?
textBox1.Text = calcArea(length, width).ToString();
}
calcArea.ToString();
when you are calling this, you aren't calling the function, you are referencing the function, not the return
do
calcArea(parameters).ToString();
replace parameters with what you want to calculate.

How I can Invoke method from UserContol?

There are many UserControls in my program. Only one user control (default) is visible without entering a password.
When there is a need to see other Users Controls, then the user must enter the password, and after that, another form should immediately appear (the button on which the call was clicked by the user).
For the model, we have 2 user controls.
The first one opens immediately at startup, and to open the second we have to click on its launch button, then a password entry will appear, and (if the password is correct) the required form will be opened.
In the last code display is my problem.
I have UserLeftPanel that dispalyed always as a left panel and a MainForm(in code Form1).
In LeftUserPanel are many buttons clicked on, Form1 will uploud some UserControl.
I don't understand how to get the method from the base class (Form1) correctly.
Specifically to my program:
And if all the user logic of the calls is wrong, I'll be happy to see the right one.
Every UserControl that displayed by clicked on has this construction
private static UserMainPanel_Saved instanse;
public static UserMainPanel_Saved Instanse
{
get
{
if(instanse==null)
instanse =new UserMainPanel_Saved();
return instanse;
}
}
Code inside UserLeftPanel
public delegate void Handler(object sender,EventArgs e, int control) ;
public event Handler ButtonClick;
protected void ButtonSavedMessages_Click(object sender, EventArgs e)
{
int formnumber = 0;
this?.ButtonClick(this, e,formnumber);// There are ButtonClick Event in Form1
}
Code inside Form1
private void userLeftPanel1_Load(object sender, EventArgs e)
{
userLeftPanel1.ButtonClick += UserControl_ButtonClick;
UserControl_ButtonClick(sender, e, 0);//to display form without password by default
}
public void UserControl_ButtonClick(object sender, EventArgs e,int number)
{
UserControl con=null ;
if (number == 0)
con = UserMainPanel_Saved.Instanse;
else
{
if (UserPassword.Password)
{
if (number == 1)
con = UserMainDaybook.Instanse;
}
else
{
con = UserPassword.Instanse;
}
}
if (!MainPanel.Controls.Contains(con))
{
MainPanel.Controls.Add( con);
con.Dock = DockStyle.Fill;
con.BringToFront();
}
else
{
con.BringToFront();
}
}
Code inside 'UserPassword'
private void button1_Click(object sender, EventArgs e)
{
Password = true;// In this place will be Some Logic
//And my idea is to Invoke there UserControl_ButtonClick( ... ) method, but I don't know how
}
You could try separating the event from the method with the logic (notice two different methods: UserControl_ButtonClick and UserControlClick:
public void UserControl_ButtonClick(object sender, EventArgs e, int number)
{
UserControlClick(number);
}
public void UserControlClick(int number)
{
UserControl con=null ;
if (number == 0)
con = UserMainPanel_Saved.Instanse;
else
{
if (UserPassword.Password)
{
if (number == 1)
con = UserMainDaybook.Instanse;
}
else
{
con = UserPassword.Instanse;
}
}
if (!MainPanel.Controls.Contains(con))
{
MainPanel.Controls.Add( con);
con.Dock = DockStyle.Fill;
con.BringToFront();
}
else
{
con.BringToFront();
}
}```
And then in UserPassword:
private void button1_Click(object sender, EventArgs e)
{
Password = true;// In this place will be Some Logic
Form1.Instance.UserControlClick(0);
//And my idea is to Invoke there UserControl_ButtonClick( ... ) method, but I don't know how
}
This way, you won't need to send object sender, EventArgs e, int number, you can just send the number.

Login form using collection list methods

here when I press login
and here when I press yes
am doing an ATM project using C# and it was required from my teacher to complete this task with out using a database so I created a class which contains a list to store all the data in while creating a new account, but the problem is that I cant use the data for login (I don't know how to do the bool coding thing to determines if the item is in the list)
Note:in login you should enter your name and pin code to login
here is my create account form code
public partial class NewAccountForm : Form
{
public NewAccountForm()
{
InitializeComponent();
}
Accounts account1;
private void btnCreate_Click(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
}
private void button2_Click(object sender, EventArgs e)
{
Form1 login = new Form1();
this.Hide();
login.Show();
}
private void btncreate_Click(object sender, EventArgs e)
{
int interest = 0;
char type = '0';
double amount = 0 ;
double balance = 0;
switch (cboType.SelectedIndex)
{
case 0: type = '1'; break;
case 1: type = '2'; break;
}
Saveing account1 = new Saveing(interest, txtName.Text, txtContact.Text,
txtpinCode.Text, type, amount,balance);
Data.CSaveing.Add(account1); //SList shows because its static if remove static will not appears
}
private void NewAccountForm_Load(object sender, EventArgs e)
{
}
}
and this is my login form
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
Data Accounts;
bool validCode = false;
private void Form1_Load(object sender, EventArgs e)
{
}
private void label1_Click(object sender, EventArgs e)
{
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
Accounts.name = txtname.Text;
Accounts.code = txtCode.Text;
if (string.IsNullOrWhiteSpace(txtname.Text))
{
MessageBox.Show("Please Type your full name");
}
if (string.IsNullOrWhiteSpace(txtCode.Text))
{
MessageBox.Show("Please Enter a correct account Pin Code");
}
else if ((Accounts.name == txtname.Text)) ;
else if ((Accounts.code != txtCode.Text)) ;
{
int i;
progressBar1.Maximum = 100;
progressBar1.Minimum = 0;
progressBar1.Step = 1;
timer1.Start();
for (i = 0; i <= 50; i++)
progressBar1.Value = i;
}
}
private void button2_Click(object sender, EventArgs e)
{
NewAccountForm naf = new NewAccountForm();
this.Hide();
naf.Show();
}
private void timer1_Tick(object sender, EventArgs e)
{
progressBar1.PerformStep();
if (progressBar1.Value == 99)
{
LoginForm login = new LoginForm();
this.Hide();
login.Show();
}
}
private void label3_Click(object sender, EventArgs e)
{
}
private void label4_Click(object sender, EventArgs e)
{
}
}
This question is missing a lot of necessary information. It isn't clear at all what you are required to do.
However, that said, if you need to store the data but you are not allowed to use a database, you could put it into a text file. You could even encrypt the data to make it more "secure".
If you only need to hold the data per user session, then it doesn't matter when you first run the application that the class containing your users is empty. In fact it makes things easier because the first time you run the application you know that your user class will be empty.
I suggest that you have a login form containing a List<UserClass> usersList. When your user clicks login, first check whether the list contains any entries:
if(usersList.Any()) { ... }
If there are no values in the list show a form to create a new user. When you've validated the values in the create user form add a new instance of your UserClass to the List, and show the logged in form, whatever that may be.
I also suggest you read one of the many introductory tutorials on .NET and C# because this probably isn't the right place to ask such basic questions :)

Set an 'int' in one event and use it in another event

I'm making a little something in Windows Form (C# Visual Studio)
But I need to know how I can set an int and then to use it in another event. For example, :
private void BtnYes_Click(object sender, EventArgs e)
{
int yes = 1;
int no = 0;
timer1.Start();
}
private void timer1_Tick(object sender, EventArgs e)
{
if (yes == 1) {
//EVENT
}
}
When I do this I get some errors. Can anyone help me with this? Or just tell me how to do something like this using a different technique?
U need to use a field for this:
private int _yes;
private void BtnYes_Click(object sender, EventArgs e)
{
_yes = 1;
int no = 0;
timer1.Start();
}
private void timer1_Tick(object sender, EventArgs e)
{
if (_yes == 1) {
//EVENT
}
}
The variable "yes" you are declaring is only visible in the scope of the method. By making it a field of class, this would make it visible to all methods in the class (when private).
class YourClass
{
private int yes = 1;
private int no = 0;
private void BtnYes_Click(object sender, EventArgs e)
{
//Remove the type declaration here to use the class field instead. If you leave the type declaration, the variable here will be used instead of the class field.
yes = 1;
no = 0;
timer1.Start();
}
private void timer1_Tick(object sender, EventArgs e)
{
if (yes == 1) {
//EVENT
}
}
}

create a control assigner menu for games

I am trying to build a windows application using WinForms and C#, in one of the forms i want the user to be able to assign keys for each movement (i.e. left , right , up ,down motion etc.). That is something similar to
On the left hand side column the moves will be listed and the user should be able to assign a key for every move. I am very new to windows forms and am unable to figure out what control to use for the left hand side things, i tried using buttons with KeyDown event but in this the event does not trigger for enter/return key, for rest of the keys it works fine. So what control along with what event should be used so that the user can assign any key of his choice for any motion/control.
EDIT: this was the initial code.
namespace ControllerWinServe
{
public partial class Form2 : Form
{
static string[] array = new string[6];
public Form2()
{
InitializeComponent();
}
private void Form2_Load(object sender, EventArgs e)
{
}
private void button_d_Click(object sender, EventArgs e)
{
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
}
private void button_u_KeyDown(object sender, KeyEventArgs e)
{
MessageBox.Show("Form.KeyPress: '" + e.KeyCode.ToString() + "' pressed.");
}
private void button_d_KeyDown(object sender, KeyEventArgs e)
{
MessageBox.Show("Form.KeyPress: b2 '" +e.KeyCode.ToString() + "'pressed.");
}
}
}
AFTER Trying to use user17753 's suggestion.
namespace ControllerWinServe
{
public class EnterTextBox : TextBox
{
protected override bool IsInputKey(Keys key)
{
if (key == Keys.Enter)
return true;
return base.IsInputKey(key);
}
}
public partial class Form2 : Form
{
static string[] array = new string[6];
public Form2()
{
InitializeComponent();
}
private void Form2_Load(object sender, EventArgs e)
{
}
private void button_d_Click(object sender, EventArgs e)
{
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
}
private void button_u_KeyDown(object sender, KeyEventArgs e)
{
MessageBox.Show("Form.KeyPress: '" + e.KeyCode.ToString() + "' pressed.");
}
private void button_d_KeyDown(object sender, KeyEventArgs e)
{
MessageBox.Show("Form.KeyPress: b2 '" +e.KeyCode.ToString() + "'pressed.");
}
}
}
If you're talking about hitting enter in a TextBox it isn't triggered by default. You can create a new one called for example EnterTextBox that is derived from TextBox that overrides IsInputKey to allow enter to trigger the event.
One such implementation could be:
public class EnterTextBox : TextBox
{
protected override bool IsInputKey(Keys key)
{
if (key == Keys.Enter)
return true;
return base.IsInputKey(key);
}
}
With this class in your project's namespace you'll be able to add EnterTextBox from the Toolbox under your project's namespace category.
Then you can add a method that is triggered by the KeyDown event on the EnterTextBox such as this:
private void button1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
e.Handled = true;
//stuff to do after enter is pressed
}
}

Categories