Reputation: 181
Such a method gives me what I want, but do not know if I am writing ugly code. This method tries to convert textbox value to int,if fails it throws an error. if an error it return false which means it can not be converted to int.
namespace icol
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
AllUse myMethods = new AllUse();
if (myMethods.isThisInt(textBox1.Text))
{
MessageBox.Show(textBox1.Text);
// if this int, you can keep writing further your program's logic
}
else {
MessageBox.Show("This textbox value can not be converted to int!");
}
}
}
public class AllUse{
public bool isThisInt(string x) {
try {
Convert.ToInt32(x);
return true;
}
catch (Exception err ){
string y = err.Message; // do not know what to do with err
return false;
}
} //method
} // class
}
Upvotes: 0
Views: 242
Reputation: 42383
You can use int.TryParse()
, which returns a boolean saying whether the value was parsed correctly and an out parameter with the value. This method is faster than doing try/catch.
int number;
bool result = Int32.TryParse(value, out number);
if (result)
{
Console.WriteLine("Converted '{0}' to {1}.", value, number);
}
else
{
if (value == null) value = "";
Console.WriteLine("Attempted conversion of '{0}' failed.", value);
}
Upvotes: 4
Reputation: 14401
int number;
bool result = Int32.TryParse(textBox1.Text, out number);
if (result)
{
// Do something
}
else
{
// Do something else
}
http://msdn.microsoft.com/en-us/library/f02979c7.aspx
Upvotes: 0
Reputation: 115859
There's a Int32.TryParse
method which does almost the same.
Upvotes: 0