Terrii
Terrii

Reputation: 385

If number is greater than in textbox

Ok I need help if I have this code and I wanted to know if there was a way to detect if the number is greater than the one in the textbox?

if (textbox1.text == "2")
{
     //code
}

and I was wondering is there anyway to detect if the number is greater than that so say textbox1.text = "5" it is greater than 2 so therefore it does the code from the if command?

Upvotes: 0

Views: 23679

Answers (4)

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236228

int value;
if (Int32.TryParse(textbox1.Text, out value))
{
   if (value > 2)
     // code
}
else
{
    // not a number in textbox
}

Sample for your real application:

TimeSpan timeOfDay = DateTime.Now.ToLocalTime().TimeOfDay;

if (8 < timeOfDay.Hours && timeOfDay.Hours < 16)
{
    // day
}
else
{
    // night
}

You can create extension method:

public static bool IsDayTime(this DateTime date)
{
    TimeSpan timeOfDay = date.TimeOfDay;
    return 8 < timeOfDay.Hours && timeOfDay.Hours < 16;
}

And use it this way:

var date = DateTime.Now.ToLocalTime();
var file = Path.Combine(Folder, date.IsDayTime() ? "Day.bmp" : "Night.bmp");
picThumbnail.ImageLocation = file;
picThumbnail.SizeMode = PictureBoxSizeMode.Zoom;
SystemParametersInfo(20, 0, file, 0x01 | 0x02);
var rkWallPaper = Registry.CurrentUser.OpenSubKey("Control Panel\\Desktop", true);
rkWallPaper.SetValue("WallpaperStyle", 2);
rkWallPaper.SetValue("TileWallpaper", 0);
rkWallPaper.Close();

Upvotes: 9

mcalex
mcalex

Reputation: 6778

You need to parse the text as a number and then you can do what you want.

C#'s Int32 class has a TryParse method that you use like so:

bool result = Int32.TryParse(textbox1.text, out number);

if (number > 2)
{
  ...
}

This is a method that has an input value and an output value. The bool result is actually an indicator of whether the attempt (the 'Try') to parse the input value has worked, and you can use it defensively as follows:

bool result = Int32.TryParse(textbox1.text, out number);

if (result)
{
  // the parse worked
  // do something with 'number'
}
else
{
    Messagebox.Show(string.Format("Could not convert {0} to a number", textbox1.text));
}

Upvotes: 1

Theodoros Chatzigiannakis
Theodoros Chatzigiannakis

Reputation: 29213

if(Int32.Parse(textbox1.text) < number)
{
   // code
}

and catch any exceptions for the case of invalid values. Or use TryParse which has an out argument and returns whether a number was actually parsed.

Upvotes: 2

Hmxa Mughal
Hmxa Mughal

Reputation: 394

Parse the text value and then check it...

if(Convert.ToInt32(Textbox.Text) > 2) { //Do something here }

Upvotes: 2

Related Questions