Courtesy of
Migrating Java Source Code To C# -
Java code:
Code:
ActionListener al;
al = new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
try
{
double value = Double.parseDouble(
txtDegrees.getText());
double result = (value-32.0)*5.0/9.0;
lblResult.setText("Celsius = "+result);
}
catch (NumberFormatException nfe)
{
JOptionPane.showMessageDialog(
null, "Bad input");
}
}
};
final JButton btnToC = new JButton("To Celsius");
btnToC.addActionListener(al); C# code:
Code:
Button btnToC = new Button();
btnToC.Text = "To Celsius";
btnToC.Location = new Point(
ANCHORX,
lblResult.Location.Y+lblResult.Height*2);
btnToC.Size = btnToC.PreferredSize;
btnToC.Click += new EventHandler(btnToC_Click);
// skipping a few lines
public void btnToC_Click(object ob, EventArgs e)
{
double degrees = 0.0;
try
{
degrees = Double.Parse(txtDegrees.Text);
}
catch (Exception) // Unlike Java, an exception
// variable is not needed if
// it will not be used by the
// exception handler.
{
MessageBox.Show("Bad input",
"Tempverter", MessageBoxButtons.OK,
MessageBoxIcon.Exclamation);
return;
}
lblResult.Text = "Celsius = "+((degrees-32.0)*5.0/9.0);
} From what I can see, you add a new event handler to the Click property of the button (note the
+= operator on the line
btnToC.Click += new EventHandler(btnToC_Click);, hence the reason why I typed "add" rather than "set").
btnToC_Click is the name of the method that is used as the event handler. You then create the method.
I'm hope that helps you with your question!
Edit: I found that by using the Google search query "ActionListener Java to C#" (without the quotes). I recommend trying something similar. It worked well for me, so maybe it will help you!