I want to create a program which would show the flag in a picture box and a user would have to guess what flag it is. I have a problem that flags are repeating and I totally don't know how to fix it.
Here is a bit of my code:
private void button1_Click(object sender, EventArgs e)
{
Random random = new Random();
randomized = random.Next(0, 9);
//0 = Poland
//1 = France
//2 = Sweden
//3 = Germany
//4 = Portugal
//5 = Spain
//6 = Finland
//7 = Norway
//8 = Russia
//9 = Ukraine
if (randomized == 0)
{
ptbFlag.Image = Image.FromFile("C:/Users/Kacper/Desktop/FlagiDoGeo/Poland.png");
}
if (randomized == 1)
{
ptbFlag.Image = Image.FromFile("C:/Users/Kacper/Desktop/FlagiDoGeo/France.png");
}
if (randomized == 2)
{
ptbFlag.Image = Image.FromFile("C:/Users/Kacper/Desktop/FlagiDoGeo/Sweden.jpg");
}
if (randomized == 3)
{
ptbFlag.Image = Image.FromFile("C:/Users/Kacper/Desktop/FlagiDoGeo/Germany.png");
}
if (randomized == 4)
{
ptbFlag.Image = Image.FromFile("C:/Users/Kacper/Desktop/FlagiDoGeo/Portugal.png");
}
if (randomized == 5)
{
ptbFlag.Image = Image.FromFile("C:/Users/Kacper/Desktop/FlagiDoGeo/Spain.png");
}
if (randomized == 6)
{
ptbFlag.Image = Image.FromFile("C:/Users/Kacper/Desktop/FlagiDoGeo/Finland.png");
}
if (randomized == 7)
{
ptbFlag.Image = Image.FromFile("C:/Users/Kacper/Desktop/FlagiDoGeo/Norway.png");
}
if (randomized == 8)
{
ptbFlag.Image = Image.FromFile("C:/Users/Kacper/Desktop/FlagiDoGeo/Russia.png");
}
if (randomized == 9)
{
ptbFlag.Image = Image.FromFile("C:/Users/Kacper/Desktop/FlagiDoGeo/Ukraine.png");
}
}
If you want to show a different image every time, you may need to keep track of which images you've already shown.
private readonly Random _random = new();
private const string PathPrefix = "C:/Users/Kacper/Desktop/FlagiDoGeo/";
private static List<string> _flags = Reinitialize();
private void button1_Click(object sender, EventArgs e)
{
var randomized = _random.Next(0, _flags.Count);
var image = _flags[randomized];
// delete the image that will be displayed.
_flags.Remove(image);
// if all images are displayed, the game restarts from the beginning.
if (_flags.Count == 0)
{
_flags = Reinitialize();
}
ptbFlag.Image = PathPrefix + image;
}
private static List<string> Reinitialize()
{
return new List<string>
{
"Poland.png",
"France.png",
"Sweden.jpg",
"Germany.png",
// ...
};
}
Related
well I have the following problem I try to validate the RUC of the provider of my country, the question is that I have implemented the validation functions which are the following:
ID validation function
public class Verifica_Identificacion
{
internal static bool VerificaIdentificacion(string identificacion)
{
bool estado = false;
char[] valced = new char[13];
int provincia;
if (identificacion.Length >= 10)
{
valced = identificacion.Trim().ToCharArray();
provincia = int.Parse((valced[0].ToString() + valced[1].ToString()));
if (provincia > 0 && provincia < 25)
{
if (int.Parse(valced[2].ToString()) < 6)
{
estado = VC.VerificaCedula(valced);
}
else if (int.Parse(valced[2].ToString()) == 6)
{
estado = VSP.VerificaSectorPublico(valced);
}
else if (int.Parse(valced[2].ToString()) == 9)
{
estado = VPJ.VerificaPersonaJuridica(valced);
}
}
}
return estado;
}
}
This function depends on other validations that are carried out independently because there are some types of RUC, below the other three functions are shown
ID verification
public class VC
{
public static bool VerificaCedula(char[] validarCedula)
{
int aux = 0, par = 0, impar = 0, verifi;
for (int i = 0; i < 9; i += 2)
{
aux = 2 * int.Parse(validarCedula[i].ToString());
if (aux > 9)
aux -= 9;
par += aux;
}
for (int i = 1; i < 9; i += 2)
{
impar += int.Parse(validarCedula[i].ToString());
}
aux = par + impar;
if (aux % 10 != 0)
{
verifi = 10 - (aux % 10);
}
else
verifi = 0;
if (verifi == int.Parse(validarCedula[9].ToString()))
return true;
else
return false;
}
}
public sector verification
public class VSP
{
public static bool VerificaSectorPublico(char[] validarCedula)
{
int aux = 0, prod, veri;
veri = int.Parse(validarCedula[9].ToString()) + int.Parse(validarCedula[10].ToString()) + int.Parse(validarCedula[11].ToString()) + int.Parse(validarCedula[12].ToString());
if (veri > 0)
{
int[] coeficiente = new int[8] { 3, 2, 7, 6, 5, 4, 3, 2 };
for (int i = 0; i < 8; i++)
{
prod = int.Parse(validarCedula[i].ToString()) * coeficiente[i];
aux += prod;
}
if (aux % 11 == 0)
{
veri = 0;
}
else if (aux % 11 == 1)
{
return false;
}
else
{
aux = aux % 11;
veri = 11 - aux;
}
if (veri == int.Parse(validarCedula[8].ToString()))
{
return true;
}
else
{
return false;
}
}
else
{
return false;
}
}
}
verification of legal person
public class VPJ
{
public static bool VerificaPersonaJuridica(char[] validarCedula)
{
int aux = 0, prod, veri;
veri = int.Parse(validarCedula[10].ToString()) + int.Parse(validarCedula[11].ToString()) + int.Parse(validarCedula[12].ToString());
if (veri > 0)
{
int[] coeficiente = new int[9] { 4, 3, 2, 7, 6, 5, 4, 3, 2 };
for (int i = 0; i < 9; i++)
{
prod = int.Parse(validarCedula[i].ToString()) * coeficiente[i];
aux += prod;
}
if (aux % 11 == 0)
{
veri = 0;
}
else if (aux % 11 == 1)
{
return false;
}
else
{
aux = aux % 11;
veri = 11 - aux;
}
if (veri == int.Parse(validarCedula[9].ToString()))
{
return true;
}
else
{
return false;
}
}
else
{
return false;
}
}
}
What I would like is to use the "ID validation function" in a textbox that accepts the RUC as input so far the data entry and that is stored in the database I did it as follows, however, as you can see I can only enter the string of the ruc without the respective validation. I would like a help to use my validation function at the time of entering the ruc and save it, if the entry was correct, the message "Provider stored correctly" appears and if it was not entered successfully, exit the message "Wrong RUC re-enter data"
data entry code from stored procedure (data layer)
public void Insertar(string NombreProveedor, string rucProveedor)
{
comando.Connection = con.AbrirConexion();
comando.CommandText = "IngresarProveedor";
comando.CommandType = CommandType.StoredProcedure;
comando.Parameters.AddWithValue("#NombreProveedor", NombreProveedor);
comando.Parameters.AddWithValue("#rucProveedor", rucProveedor);
comando.ExecuteNonQuery();
comando.Parameters.Clear();
con.CerrarConexion();
}
data entry code (business cape)
private CD_RUC proveedor_cd = new CD_RUC();
public void InsertarProv(string NombreProveedor, string rucProveedor)
{
proveedor_cd.Insertar(NombreProveedor, rucProveedor);
}
save button settings (presentation layer)
private void btn_Guardar_Click(object sender, RoutedEventArgs e)
{
proveedorcn NPro = new proveedorcn();
NPro.InsertarProv(TXT_Nombre_Proveedor_P.Text, TXT_RUC.Text);
MessageBox.Show("Proveedor Ingresado Correctamente");
}
Is it good practice to use my code like this?
My code, basically generates a password with the length of 10(currently), and generates a password according to which checkboxes are checked:
Checkboxes:
- Special characters
- Numbers
- Capital letters
bool c_special = false;
bool c_numbers = false;
bool c_capitals = false;
private void btn_generate_Click(object sender, RoutedEventArgs e)
{
checkCheckboxes();
if(c_special && c_numbers && c_capitals)
{
txt_password.Text = generateWithCharactersAndNumbersAndCapitals(10);
}
else if(c_special && c_numbers && !c_capitals)
{
txt_password.Text = generateWithCharactersAndNumbers(10);
}
else if(c_special && !c_numbers && c_capitals)
{
txt_password.Text = generateWithCharactersAndCapitals(10);
}
else if(c_special && !c_numbers && !c_capitals)
{
txt_password.Text = generateWithCharacters(10);
}
else if(!c_special && c_numbers && !c_capitals)
{
txt_password.Text = generateWithNumbers(10);
}
else if(!c_special && c_numbers && c_capitals)
{
txt_password.Text = generateWithNumbersAndCapitals(10);
}
else if(!c_special && !c_numbers && c_capitals)
{
txt_password.Text = generateWithCapitals(10);
}
else if(!c_special && !c_numbers && !c_capitals)
{
txt_password.Text = generateNormalPassword(10);
}
}
/*
* Checks which checkboxes are checked
*/
private void checkCheckboxes()
{
if (cbox_special.IsChecked == true)
{
c_special = true;
}
else
{
c_special = false;
}
if (cbox_numbers.IsChecked == true)
{
c_numbers = true;
}
else
{
c_numbers = false;
}
if (cbox_capitals.IsChecked == true)
{
c_capitals = true;
}
else
{
c_capitals = false;
}
}
//Normal
public string generateNormalPassword(int length)
{
const string valid = "abcdefghijklmnopqrstuvwxyz";
StringBuilder res = new StringBuilder();
Random rnd = new Random();
while (0 < length--)
{
res.Append(valid[rnd.Next(valid.Length)]);
}
return res.ToString();
}
//Characters
public string generateWithCharacters(int length)
{
const string valid = "abcdefghijklmnopqrstuvwxyz!##$%^&*";
StringBuilder res = new StringBuilder();
Random rnd = new Random();
while (0 < length--)
{
res.Append(valid[rnd.Next(valid.Length)]);
}
return res.ToString();
}
public string generateWithCharactersAndNumbers(int length)
{
const string valid = "abcdefghijklmnopqrstuvwxyz0123456789!##$%^&*";
StringBuilder res = new StringBuilder();
Random rnd = new Random();
while (0 < length--)
{
res.Append(valid[rnd.Next(valid.Length)]);
}
return res.ToString();
}
public string generateWithCharactersAndCapitals(int length)
{
const string valid = "abcdefghijklmnopqrstuvwxyz!##$%^&*ABCDEFGHIJKLMNOPQRSTUVWXYZ";
StringBuilder res = new StringBuilder();
Random rnd = new Random();
while (0 < length--)
{
res.Append(valid[rnd.Next(valid.Length)]);
}
return res.ToString();
}
public string generateWithCharactersAndNumbersAndCapitals(int length)
{
const string valid = "abcdefghijklmnopqrstuvwxyz!##$%^&*ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
StringBuilder res = new StringBuilder();
Random rnd = new Random();
while (0 < length--)
{
res.Append(valid[rnd.Next(valid.Length)]);
}
return res.ToString();
}
//Numbers
public string generateWithNumbers(int length)
{
const string valid = "abcdefghijklmnopqrstuvwxyz0123456789";
StringBuilder res = new StringBuilder();
Random rnd = new Random();
while (0 < length--)
{
res.Append(valid[rnd.Next(valid.Length)]);
}
return res.ToString();
}
public string generateWithNumbersAndCapitals(int length)
{
const string valid = "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
StringBuilder res = new StringBuilder();
Random rnd = new Random();
while (0 < length--)
{
res.Append(valid[rnd.Next(valid.Length)]);
}
return res.ToString();
}
//Capitals
public string generateWithCapitals(int length)
{
const string valid = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
StringBuilder res = new StringBuilder();
Random rnd = new Random();
while (0 < length--)
{
res.Append(valid[rnd.Next(valid.Length)]);
}
return res.ToString();
}
private void btn_cancel_Click(object sender, RoutedEventArgs e)
{
MainWindow mw = new MainWindow();
mw.Show();
this.Hide();
}
}
}
I'm trying to learn better practice than this, I'd love to know your opinion how I have done this and where & how to improve.
Your code now has quite a lot of repetition. Mainly, this part is shared across all the generate... methods:
StringBuilder res = new StringBuilder();
Random rnd = new Random();
while (0 < length--)
{
res.Append(valid[rnd.Next(valid.Length)]);
}
return res.ToString();
Only the string valid is different.
One way to reduce this repetition is to have one generate method that takes flag arguments:
// rnd should be at class level so you don’t create a new one every time
Random rnd = new Random();
public string generateWith(int length, bool capitals, bool numbers, bool symbols) {
string valid = "abcdefghijklmnopqrstuvwxyz";
if (capitals) { // add the capitals to 'valid' }
if (numbers) { // add the numbers to 'valid' }
if (symbols) { // add the symbols to 'valid' }
StringBuilder res = new StringBuilder();
while (0 < length--)
{
res.Append(valid[rnd.Next(valid.Length)]);
}
return res.ToString();
}
And then you just have to pass the variables c_special, c_numbers and c_capitals into this method:
generateWith(10, capitals: c_capitals, numbers: c_numbers, symbols: c_special);
The Print Preview controller shows the first page not the 2n or 3rd.. pages.
Show_Page() method displays the all pages without problem in a list view.
The method that I use for changing the pages print preview controller is as below:
What should I change or add for displaying next and previous pages ?
private void nxtBtn_Click(object sender, EventArgs e)
{
if (PrevIndex < PgCount)
++PrevIndex;
if (PrevIndex == PgCount - 1)
nxtBtn.Enabled = false;
prvBtn.Enabled = true;
ppd.PrintPreviewControl.InvalidatePreview();
fName = GetFName();
if (PublicVariables.PrintData == 2)
Show_Page();
else
{
pd.DocumentName = fName;
ppd.Document = pd;
ppc.Document = pd;
ppc.Update();
}
label2.Text = (PrevIndex + 1).ToString();
}
private void ShowPage()
{
streamToRead = new StreamReader(fName, Encoding.UTF8);
string line;
int LineNbr = 0;
li.Items.Clear();
LineNbr = File.ReadAllLines(fName).Length;
li.View = View.Details;
int counter = 0;
ListViewItem Lvi = new ListViewItem();
char sep='|';
int ctr_limit=0;
if (PublicVariables.Grup_It == 0)
ctr_limit = 9;
else
ctr_limit = 7;
string[] tmp1 = new string[ctr_limit];
while (counter < LineNbr && (line = streamToRead.ReadLine()) != null)
{
if (PublicVariables.PrintData == 2 && counter < 3)
goto NextLine;
string[] tmp = line.Split(sep);
for (int i = 0; i < ctr_limit; ++i)
{
if (PublicVariables.Grup_It > 0)
tmp1[i] = tmp[i + 1];
else
tmp1[i] = tmp[i];
}
Lvi = new ListViewItem(tmp1);
li.Items.Add(Lvi);
NextLine:
++counter;
}
streamToRead.Close();
}
private void nxtBtn_Click(object sender, EventArgs e)
{
if (PrevIndex < PgCount)
++PrevIndex;
if (PrevIndex == PgCount - 1)
nxtBtn.Enabled = false;
prvBtn.Enabled = true;
ppd.PrintPreviewControl.InvalidatePreview();
fName = GetFName();
if (PublicVariables.PrintData == 2)
Show_Page();
else
{
pd.DocumentName = fName;
ppd.Document = pd;
ppc.Document = pd;
ppc.InvalidatePreview();
}
label2.Text = (PrevIndex + 1).ToString();
}
Instead of ppc.Update() I have to write ppc.InvalidatePreview();
That permits to show the next page.
As question indicates this is what I am trying to do can anyone see how been fiddling with it for a while. Currently it only shows the first 3 numbers in the text file, when I press the nextButton I want it to go to the next 3 but it does not seem to be working..
namespace GPSProject
{
public partial class Form1 : Form
{
private int count;
internal dataPoints myDataPoints;
public Form1()
{
myDataPoints = new dataPoints();
InitializeComponent();
}
private void buttonNext_Click(object sender, EventArgs e)
{
{
Button b = (Button)sender;
if (b.Name.Equals("buttonNext"))
{
count++;
if (count == (myDataPoints.Count))
count = 0;
}
else
{
count--;
if (count < 0)
count = myDataPoints.Count - 1;
}
dataPoint a = myDataPoints.getItem(count);
textBoxLatitude.Text = a.CurLatitude;
textBoxLongtitude.Text = a.CurLongtitude;
textBoxElevation.Text = a.CurElevation;
}
}
}
}
Above is my forms window and below is my dataPoints
namespace GPSProject
{
class dataPoints
{
public int Count { get { return Points.Count; } }
List<dataPoint> Points;
//string p;
public dataPoints(/*string path*/)
{
Points = new List<dataPoint>();
// p = path;
TextReader tr = new StreamReader(/*p*/"C:/Test.txt");
string input;
while ((input = tr.ReadLine()) != null)
{
string[] bits = input.Split(',');
dataPoint a = new dataPoint(bits[0], bits[1], bits[2]);
Points.Add(a);
}
tr.Close();
}
internal dataPoint getItem(int p)
{
if (p < Points.Count)
{
return Points[p];
}
else
return null;
}
}
}
You'll need to update your while loop to take your data items 3 at a time, something like this:
while ((input = tr.ReadLine()) != null)
{
string[] bits = input.Split(',');
for (int i = 0; i < bits.Length / 3; i++)
{
dataPoint a = new dataPoint(bits[3*i], bits[3*i+1], bits[3*i+2]);
Points.Add(a);
}
}
string input = "1,2,3,4,5,6,7,8,9,10,11,12";
//string input = File.ReadAllText(/*p*/"C:/Test.txt");
List<List<string>> all = input.Split(',')
.Select((s, i) => new { s, i })
.GroupBy(x => x.i / 3)
.Select(g => g.Select(x=>x.s).ToList())
.ToList();
foreach(var bits in all)
{
Console.WriteLine("{0} {1} {2}", bits[0], bits[1], bits[2]);
//dataPoint a = new dataPoint(bits[0], bits[1], bits[2]);
//Points.Add(a);
}
This would give an output
1 2 3
4 5 6
7 8 9
10 11 12
I'm trying to design a code where one guess a number. I defined the range which number to display in my listbox. I started to write Random(1,10) but if I enter 11, it still writes in my listbox. How can I just write the number selected from my range, which is 1-10?
Here is a part of my code:
private void btnOk_Click(object sender, EventArgs e)
{
string yourNumber;
yourNumber = textBox1.Text.Trim();
int returnNumber = RandomNumber(1, 10);
int.TryParse(textBox1.Text, out returnNumber);
listBox1.Items.Add(returnNumber);
}
Additional question
If I would like to display a range of number like for example 1-10, how could I do the following? The user will type 11 the program will not accept that.
I made something like this:
int returnNumber = RandomNumber(1, 10);
string yourNumber;
yourNumber = textBox1.Text.Trim();
if(Int32.TryParse(textBox1.Text>=1)) && (Int32.TryParse(textBox1.Text<=10));
{
listBox1.Items.Add(yourNumber);
textBox1.Text = string.Empty;
}
Something is wrong in the program.
Update
For Nathaniel, I tried this one:
int returnNumber=RandomNumber(1,10);
int counter=1;
int yourNumber;
Int32.TryParse(textBox1.Text.Trim(), out yourNumber);
if (yourNumber >=1 && yourNumber <= 10)
{
listBox1.Items.Add(yourNumber);
}
else
{
MessageBox.Show("Please enter a number between 1-10");
}
What I would like to do is design a program for guessing a number. So this is the first part.
Update
Here is my final code, can it be improved? I think the next thing I'll do is to limit the times the user types the input. That means, they can only guess the right number 3 times or 5 times. Not sure where to implement it
namespace Guessing_Game
{
public partial class Form1 : Form
{
private static int randomNumber;
private const int rangeNumberMin = 1;
private const int rangeNumberMax = 10;
public Form1()
{
InitializeComponent();
randomNumber = GenerateNumber(rangeNumberMin, rangeNumberMax);
}
private int GenerateNumber(int min,int max)
{
Random random = new Random();
return random.Next(min, max);
}
private void btnOk_Click(object sender, EventArgs e)
{
int yourNumber = 0;
Int32.TryParse(textBox1.Text.Trim(), out yourNumber);
if (yourNumber>= rangeNumberMin && yourNumber<=rangeNumberMax)
{
listBox1.Items.Add(yourNumber);
if (yourNumber > randomNumber)
{
listBox2.Items.Add("No the Magic Number is lower than your number");
}
if (yourNumber < randomNumber)
{
listBox2.Items.Add("No, the Magic Number is higher than your number");
}
if(yourNumber==randomNumber)
{
listBox2.Items.Add("You guessed the Magic Number!");
btnRestart.Enabled = true;
}
}
else
{
MessageBox.Show("Please enter a number between " + rangeNumberMin + " to " + rangeNumberMax);
}
}
private void btnRestart_Click(object sender, EventArgs e)
{
listBox2.Items.Clear();
listBox1.Items.Clear();
textBox1.Text = null;
randomNumber = GenerateNumber(rangeNumberMin, rangeNumberMax);
btnRestart.Enabled = false;
}
}
The line:
int returnNunmber = RandomNumber(1, 10);
does nothing, because in the next line returnNumber is used as an output variable and will be whatever number is in textBox1. Remove the
int.TryParse(textBox1.Text, out returnNumber);
line and it will add a random number from 1 to 10 to your listbox.
EDIT::::
To answer you additional question, try:
private void btnOk_Click(object sender, EventArgs e)
{
string yourNumber;
yourNumber = textBox1.Text.Trim();
int returnNumber;
int.TryParse(textBox1.Text, out returnNumber);
if( returnNumber < 1 || returnNumber > 10) {
returnNumber = RandomNumber(1, 10);
}
listBox1.Items.Add(returnNumber);
}
Some minor changes to your code, condensing a couple lines and adding the limit code, utilizing the list of guesses as the counter:
namespace Guessing_Game
{
public partial class Form1 : Form
{
private static int randomNumber;
private const int rangeNumberMin = 1;
private const int rangeNumberMax = 10;
private const int maxGuesses = 5;
public Form1()
{
InitializeComponent();
randomNumber = GenerateNumber(rangeNumberMin, rangeNumberMax);
}
private int GenerateNumber(int min,int max)
{
Random random = new Random();
return random.Next(min, max);
}
private void btnOk_Click(object sender, EventArgs e)
{
int yourNumber = 0;
if (Int32.TryParse(textBox1.Text.Trim(), out yourNumber) &&
yourNumber>= rangeNumberMin && yourNumber<=rangeNumberMax)
{
listBox1.Items.Add(yourNumber);
if (yourNumber > randomNumber)
{
listBox2.Items.Add("No the Magic Number is lower than your number");
}
else if (yourNumber < randomNumber)
{
listBox2.Items.Add("No, the Magic Number is higher than your number");
}
else
{
listBox2.Items.Add("You guessed the Magic Number!");
textBox1.Enabled = false;
btnOk.Enable = false;
btnRestart.Enabled = true;
}
//Will stop on the 5th guess, but guards the case that there were more than 5 guesses
if(listBox1.Items.Count >= maxGuesses && yourNumber != randomNumber)
{
listBox2.Items.Add("You are out of guesses!");
textBox1.Enabled = false;
btnOk.Enable = false;
btnRestart.Enabled = true;
}
}
else
{
MessageBox.Show("Please enter a number between " + rangeNumberMin + " to " + rangeNumberMax);
}
}
private void btnRestart_Click(object sender, EventArgs e)
{
listBox2.Items.Clear();
listBox1.Items.Clear();
textBox1.Text = null;
randomNumber = GenerateNumber(rangeNumberMin, rangeNumberMax);
btnRestart.Enabled = false;
textBox1.Enabled = true;
btnOk.Enable = true;
}
}
}
Editted to prevent the "You're out of guesses" message when the number is correctly guessed on the last guess.
Lets take that piece by piece:
int returnNumber = RandomNumber(1, 10);
There is no inbuilt RandomNumber function; note that with the Random class, the end value is exclusive, so for a number in a range, you'll need something like:
static readonly Random rand = new Random();
static int Random(int min, int max) {
if(max < min) throw new ArgumentOutOfRangeException("max");
lock(rand) {
return rand.Next(min, max + 1);
}
}
However, you then throw away this value completely:
int.TryParse(textBox1.Text, out returnNumber);
The use of out means that the previous value of returnNumber is ignored completely. I'm not sure what your intent is, but it seems like you just want to check the value:
if(int.TryParse(textBox1.Text, out returnNumber)
&& returnNumber >= 1 && returnNumber <= 10)
{
listBox1.Items.Add(returnNumber);
}
I've tried to look at the last example, but it really isn't clear what you are trying to do - can you clarify?
(edited after question edit and comments)
You would need a counter, which you increment for failed tries - something like:
using System;
using System.Drawing;
using System.Windows.Forms;
class MyForm : Form {
Button btn;
ListBox lst;
TextBox tb;
const int MaxTries = 3, MaxNumber = 10;
int targetNumber, guessCount = 0;
public MyForm() {
targetNumber = new Random().Next(1, MaxNumber + 1);
Text = "Guess a number";
Icon = SystemIcons.Question;
Controls.Add(lst = new ListBox {Dock=DockStyle.Fill});
Controls.Add(btn = new Button {Text="Guess",Dock=DockStyle.Top});
Controls.Add(tb = new TextBox {Dock=DockStyle.Top});
btn.Click += btn_Click;
}
void btn_Click(object sender, EventArgs e) {
int userNumber;
if (int.TryParse(tb.Text.Trim(), out userNumber)) {
if (userNumber < 1 || userNumber > MaxNumber) {
lst.Items.Add("Did I mention... between 1 and " + MaxNumber);
} else {
if (userNumber == targetNumber) {
lst.Items.Add("Well done! You guessed well");
btn.Enabled = false; // all done
} else {
lst.Items.Add(targetNumber < userNumber
? "Try a bit lower" : #"It is bigger than that");
if (++guessCount >= MaxTries) {
btn.Enabled = false;
lst.Items.Add("Oops, should have picked more wisely");
}
}
}
} else {
lst.Items.Add("Nice; now give me a number");
}
}
[STAThread]
static void Main() {
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new MyForm());
}
}