I have a question about a small practice program I'm working on. I have almost no experience with C#, and a little bit of experience with Visual Basic. The problem I'm having has to do with only allowing numbers in the text box. I succeeded in doing so in another program, but for some reason it isn't working with relatively the same code. Here is the code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnCalculate_Click(object sender, EventArgs e)
{
Double TextBoxValue;
TextBoxValue = Convert.ToDouble(txtMinutes.Text);
TextBoxValue = Double.Parse(txtMinutes.Text);
{
Double Answer;
if (TextBoxValue > 59.99)
{
Answer = TextBoxValue / 60;
}
else
{
Answer = 0;
}
{
lblAnswer.Text = Answer.ToString();
}
}
}
private void txtHours_KeyPress(object sender, KeyPressEventArgs e)
{
if (char.IsNumber (e.KeyChar) && Char.IsControl(e.KeyChar))
{
e.Handled = true;
}
}
}
}
If there are other errors in my code that anyone here can correct me on, that is also appreciated. Thanks in advance.
Your logic is incorrect. It states "if the pressed key is a number and a control character.. then i've handled it". What you want is "if the pressed key is NOT a number, I've handled it".
You've got the checks inverted. What your code does is to cancel input if the new character is a number AND if it's a control character.