I'm trying to write a Fahrenheit to Celsius converter but nothing happens when I click the button
and I have no idea why. Please help me.
It's written in C# and I have a form with a label, a button, a textbox for input, and a multiline textbox for output.
namespace _14._6
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click( object sender, EventArgs e)
{
int farenhait;
int celsius;
farenhait = Convert.ToInt32(textbox2.Text);
celsius = Convert.ToInt32(5.0 / 9.0 * (farenhait - 32));
textBox1.Text = farenhait + "grader på farenhait skalan motsvarar \n " + celsius + "grader celsius";
}
}
}
Assuming the statement:
but nothing happends when i klick the button...
is literally true (i.e. when placing a breakpoint on the first line in the handler button1_Click it doesn't hit the breakpoint) then something happened to the handler. So, go to the Form Designer and double-click the button again to hookup the handler.
Is the event wired up?
Click on the button in the designer and look in the properties window (bottom-right underneath your file list), then click the events button (looks like a little lightning bolt) and scroll down until you find Click, then type button1_Click in there if it isn't already in there, that will wire the event up.
Alternatively, you can add it manually in the form's constructor:
public Form1()
{
InitializeComponent();
this.button1.Click += new EventHandler(button1_Click);
}
What exactly does the debugger tell you is wrong?
Not to deviate to far from your original question, I would suggest to use a technique called abstraction. An example of this would be to create a separate class, which will take parameters that will accomplish a task.
public class TemperatureConverter
{
public void Convertion(int fahrenheit, int celsius)
{
// Input your conversion syntax here.
}
}
Now with that particular class can handle the conversion, on your form within your button you can provide the necessary Error Handling then you can actually call it with those values.
private void button1_click(object sender, EventArgs e)
{
// Error Handling
TemperatureConverter tc = new TemperatureConverter();
tc.Conversion(textbox1.Text, textbox2.Text);
}
In this example which is quite poor, you'll have to cast the string to a integer otherwise it will error. But this is an example to help better adhere to Object-Orientation.
Your other issue: "nothing happens when I click the button". This leads me to believe the EventHandler has been broken. Follow these steps:
Go into Designer Mode
Select your Button
Open Properties
You'll see a button with almost a lightning bolt, click it
Locate your on click, and ensure the EventHandler is wired correctly.
This is a designer approach to the coded approach that Sean provided.
Hopefully this helps.
Related
I would like to help with my new clicker game that I'm working on and I've stumbled upon a problem with adding a value to the "playerPoints" which is from launch 0. You need to click a button which is called "button_click" which will add +1 (++) to your "playerPoints". But there is a bug when you click the button and then hold the enter button it will act like a little auto clicker which I don't want. Is there a way how to prevent the enter key to add value when it is pressed or held down? Thanks in exchange.
int playerPoints = 0;
public void button_click_Click(object sender, EventArgs e) // main click button
{
playerPoints++;
label_points.Text = playerPoints.ToString() + " BITS";
}
The problem has been solved by an great idea by: Dan Byström
If you don't want to make the button respond to keys like enter.
Use a simple image or label and link that function to the image_click or label_click
again thanks alot guys!
When you click on the subject Button, it becomes the form's ActiveControl. As part of the form's internal processing in setting the ActiveControl, the Form.UpdateDefaultButton Method is called.
Remarks
The UpdateDefaultButton method determines which button on the form raises its Click event when the user presses ENTER, according to the following priority:
To avoid having the subject button becoming the Default Button, override the form's UpdateDefaultButton method with something like this:
protected override void UpdateDefaultButton()
{
if (ActiveControl == button_click)
{
return;
}
else
{
base.UpdateDefaultButton();
}
}
Hook the KeyDown event instead of the Click event.
https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.control.keydown
Button.KeyDown += Button_KeyDown;
// Handle the KeyDown event
private void Button_KeyDown(object sender, KeyEventArgs e)
{
//increment your counter
}
I have just a little problem with reading text from label, but...
I have two forms. Form_1, and Form_2.
Form_1 is sending (on demand) text from "label_one" directly to "label_two" in Form_2.
But in Form_2 i have another label called "label_reader" that need to show any changes done in "label_two" text.
I must (dynamically?) read any changes from "label_two" and show it in label_reader.
Never had a similar problem, and have no idea how to do that. It can't be done with the use of a button.
Any help will be greatly appreciated!
You can use the TextChanged event of label_two. Subscribe to that event (most likely in the constructor of your Form_2) and set the text of label_reader when the event is raised:
public partial class Form_2 : Form
{
//...
public Form_2()
{
InitializeComponent();
// your other code
label_two.TextChanged += label_two_TextChanged;
}
// the event handler
private void label_two_TextChanged(object sender, EventArgs e)
{
label_reader.Text = label_two.Text; // or what ever you want to do
}
}
Not sure what I'm doing wrong since this doesn't work at all. TextChanged, KeyDown or any function that is listening on a text box.
Can you advise how to create a listener to perform functions XYZ when text is entered on txtSearch textbox?
public Form1()
{
InitializeComponent();
}
void txtSearch_TextChanged(object sender, EventArgs e)
{
cmboxCountry.SelectedIndex = 1;
}
Make sure that this method is set to event you are expecting. This line should be added somewhere after InitialiseComponent() to be sure that TextBox has been already initialised.
txtSearch.TextChanged += txtSearch_TextChanged;
You can set it either in a code, or in Designer class. To add this line at designer class, you can use Event tab page at properties window of text box, by double click on Event you like to add.
Have you hooked up the event either in the designer file or somewhere else in code e.g.
public Form1()
{
InitializeComponent();
this.txtSearch.TextChanged += txtSearch_TextChanged;
}
I created a new Event in my user control (SearchControl) like this:
//Event which is triggered on double click or Enter
public event EditRecordEventHandler EditRecord;
public delegate void EditRecordEventHandler(object sender, EventArgs e);
//Supressing the events
private bool _raiseEvents = true;
private void OnEditRecord(System.EventArgs e)
{
if (_raiseEvents)
{
if (this.SearchResultGridView.FocusedRowHandle > -1)
{
if (EditRecord != null)
{
EditRecord(this, e);
}
}
}
}
Now this Event is called when user double click a row in a grid. So from the properties window I selected the MouseDoubleClick Event of the grid view and called the above created EditRecord event.
private void SearchResultListGridControl_MouseDoubleClick(object sender, MouseEventArgs e)
{
// Check whether the user clicked on a real and not a header row or group row
DevExpress.XtraGrid.Views.Grid.ViewInfo.GridHitInfo info = SearchResultGridView.CalcHitInfo(e.Location);
if (info.InRow && !SearchResultGridView.IsGroupRow(info.RowHandle))
{
OnEditRecord(e);
}
}
Now the issue I am facing is every time I double click a row in grid view it calls the SearchResultListGridControl_MouseDoubleClick() which then calls OnEditRecord(), however the value of EditRecord is everytime null.
To solve this I checked the designer file of the Main Control which has SearchControl and could not find the EditRecord Event entry in this. So I manually created it like this:
this.MySearchControl.EditRecord += new performis.BA.Merkmalsleisten.Search.SearchControl.EditRecordEventHandle(this.MySearchControl_EditRecord);
Now the things are working fine, but my question is why it did not create it automatically at the first place? And as far I know it is not recommendable to add anything manually to the designer file..is there any other way I can do it?
Thanks
When you create event it has to be used in the form designer similar to how you are using MouseDoubleClick for the Grid (so you need to find event in the Misc category, because you didn't define CategoryAttribute, double clicked there, etc).
If I understand it right you want to subscribe to event automatically, when form is created. You can do this in the control constructor (find parent form control.Parent or control.FindForm()) or perhaps in the special method, which you have to call from the form constructor, which in turn is basically similar to wiring event manually (which you did in the designer created file, but, instead, you can do in the form file, which is totally ok to edit) Up to you.
Sure.
A better practice would be to add your binding line:
this.MySearchControl.EditRecord += new performis.BA.Merkmalsleisten.Search.SearchControl.EditRecordEventHandle(this.MySearchControl_EditRecord);
To the form's constructor. something like:
public MyForm()
{
this.MySearchControl.EditRecord += new performis.BA.Merkmalsleisten.Search.SearchControl.EditRecordEventHandle(this.MySearchControl_EditRecord);
//The rest of your constructor.
}
I created a Windows Application with a form and few buttons on it. I need to fire the button click event automatically some times based on the parameter value passed to the application.
static class SensexPrediction
{
static void Main(string[] Args) <---- Modified this so accepting arguments.
{
Application.Run(new Sensex_Prediction_Form(Args)); <--- Passing Args to Form.
}
}
Below is the Code for Sensex_Prediction_Form method.
public Sensex_Prediction_Form(String[] Args)
{
InitializeComponent();
if (Args.Length != 0) //There is atleast one argument.
{
this.Invoker = Args[0]; <-----Invoker is the name of the data member of the class.
}
}
Now on form load if Invoker == "X" i need to perform button1_Click event code. For that i wrote the following...
private void Sensex_Prediction_Form_Load(object sender, EventArgs e)
{
if(Inovker == "x")
{
predict_butn.performclick();
}
}
But click is not happening automatically even though argument passed is X.
What i couldn't understand is the button name in the solution explorer is predict_butn but when i click on the button the event code is in a function named button1_click. Is this the reason?
Please help. Thanks.
After the suggestions i separated the event code and actual logic in a separate method named prediction.
private void Sensex_Prediction_Form_Load(object sender, EventArgs e)
{
if (Invoker == "Scheduler")
{
prediction();
}
}
And i initialized the data variable of the class with Scheduler as below..
public string Invoker = "Scheduler";
Even then when i load the form the method is not being invoked.
As suggested i corrected the connection between button name and even method name etc.
thank q
Suprisingly..(for me :-))
if (Invoker == "Scheduler")
{
MessageBox.Show("Testing");
prediction();
MessageBox.Show("OK");
}
Testing message is getting executed but after that it just displays the form. so what could be the reason?
Understood the issue..I am getting an exception object reference not set..because i have a line that says
ActiveForm.Text = "Sensex Prediction System ";
At this point form has not been loaded so it can't set the text.
------> Now the issue is how to call a method automatically after loading the form? because the method will have code that will modify the form while executing.
Got it...using the "shown" event for the form able to do what i wanted. Thanks.
Promote the code within button1_click to a method. Then once the form is loaded and if the parameter match your filter, call the method.
private void Button1_Click(object sender, EventArgs e)
{
DoSomething();
}
private void Sensex_Prediction_Form_Load(object sender, EventArgs e)
{
if(Inovker == "X")
{
DoSomething();
}
}
private void DoSomething()
{
...
}
Extract the code out of the button event into it's own method that is called in the button click. Now you just need to call that new extracted method instead of trying to invoke a ui button click.
First you can use Environment.GetCommandLineArgs() instead of passing the args to the constructor of the form.
Second you may assign the wrong event handler to the click. reassign the predict_butn.Click to its correct event handler instead of the current one which is button1_click
Double click button to generate event handler(for example button1_Click(object sender, System.EventArgs e)), and then you want to trigger that method just call button1_Click(null, null)
Of course better solution is to create one function with your logic and then call that function in button click event and when Invoker == "X".
First of all, you're not checking whether Invoker == 'X', but Invoker == 'x'. This may be part of the problem. Comparing strings with == is not good practice, however. You should use
if (Invoker.Equals('X', StringComparison.InvariantCulture))
Is the action performed if you click the button with your mouse? If so, the problem is not the event handler.
If it is not performed, the event handler and the button's event are not connected. You can check in the button's properties whether the event handler is attached to the button's click event.
What happens if you double-click the button in the designer? Is a new event handler created? If so, move the code from button1_click to the new event handler and delete the button1_click event handler.
Event handlers and control events are not automatically associated. You need to do this in the control's properties.