I have a Search function with them I can Search a string inside my richtextbox from the beginning of the text to the end. When I found the last accordance it start from begin.
Here the code:
#region Search
private void txtSearch_KeyPress(object sender, KeyPressEventArgs e)
{
start = 0;
end = 0;
}
//Searchfield
private void toolStripTextBoxSearch_Click(object sender, EventArgs e)
{
}//end TextBoxSearch
public int FindMyText(string txtToSearch, int searchStart, int searchEnd)
{
// Set the return value to -1 by default.
int retVal = -1;
// A valid starting index should be specified.
if (searchStart >= 0)
{
// A valid ending index
if (searchEnd > searchStart || searchEnd == -1)
{
// Find the position of search string in RichTextBox
indexOfSearchText = richTextBox.Find(txtToSearch, searchStart, searchEnd, RichTextBoxFinds.None);
// Determine whether the text was found in richTextBox1.
if (indexOfSearchText != -1)
{
// Return the index to the specified search text.
retVal = indexOfSearchText;
}
}
}
return retVal;
}//end FindMyText
private void buttonSearch_left_Click(object sender, EventArgs e)
{
}
private void buttonSearch_right_Click(object sender, EventArgs e)
{
int startindex = 0;
if (txtSearch.Text.Length > 0)
{
startindex = FindMyText(txtSearch.Text, start, richTextBox.Text.Length);
}
// If string was not found report it
if (startindex < 0 )
{
if (stringfoundflag==1)
{
startindex = FindMyText(txtSearch.Text, 0, richTextBox.Text.Length); //Start at Pos. 0
}
else
{
MessageBox.Show("Not found in Textfield", "Search", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}//end if
if (startindex >= 0)
{
stringfoundflag = 1;
// Set the highlight color as red
//richTextBox.SelectionColor = Color.Red;
// Find the end index. End Index = number of characters in textbox
int endindex = txtSearch.Text.Length;
// Highlight the search string
richTextBox.Select(startindex, endindex);
// mark the start position after the position of
// last search string
start = startindex + endindex;
}
}
// Reset the richtextbox when user changes the search string
private void textBox1_TextChanged(object sender, EventArgs e)
{
start = 0;
indexOfSearchText = 0;
}
private void txtSearch_Enter(object sender, EventArgs e)
{
if (txtSearch.Text == "Search")
{
txtSearch.Text = "";
}
}
private void txtSearch_Leave(object sender, EventArgs e)
{
if (txtSearch.Text == "")
{
txtSearch.Text = "Search";
}
}
#endregion
I have two button one search right and one left, the right works like the description at the start.
Question:
Can I reverse the searchfunction from button right to left with my solution, or must I change the whole search function?
Example: Start at first accordance and jump than to the last accordance and then next-to-last and so on.
I found a solution for my problem.
Code:
public int FindMyTextleft(string txtToSearch, int searchStart, int searchEnd)
{
// Set the return value to -1 by default.
int retVal = -1;
// A valid starting index should be specified.
if (searchStart >= 0)
{
// A valid ending index
if (searchEnd > searchStart || searchEnd == -1)
{
// Find the position of search string in RichTextBox
indexOfSearchText = richTextBox.Find(txtToSearch, searchStart, searchEnd, RichTextBoxFinds.Reverse);
// Determine whether the text was found in richTextBox1.
if (indexOfSearchText != -1)
{
// Return the index to the specified search text.
retVal = indexOfSearchText;
}
}
}//end FindMyTextleft
return retVal;
}//end FindMyText
private void buttonSearch_left_Click(object sender, EventArgs e)
{
int startindex = 0;
if (txtSearch.Text.Length > 0 & stringfoundflag == 1)
{
startindex = FindMyTextleft(txtSearch.Text, startindex, end);
}
else if (txtSearch.Text.Length > 0)
{
startindex = FindMyTextleft(txtSearch.Text, start, richTextBox.Text.Length);
}
// If string was not found report it
if (startindex < 0)
{
if (stringfoundflag == 1)
{
startindex = FindMyTextleft(txtSearch.Text, 0, richTextBox.Text.Length); //Start at Pos. 0
}
else
{
MessageBox.Show("Not found in Textfield", "Search", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}//end if
if (startindex >= 0)
{
stringfoundflag = 1;
// Set the highlight color as red
//richTextBox.SelectionColor = Color.Red;
// Find the end index. End Index = number of characters in textbox
int endindex = txtSearch.Text.Length;
// Highlight the search string
richTextBox.Select(startindex, endindex);
// mark the start position after the position of
// last search string
end = startindex;
}
}//buttonSearch_left_Click
Related
I want to search for a string in a list of strings and get its index
List<string> list;
int index;
private void button1_Click(object sender, EventArgs e)
{
index = list.FindIndex(x => x.Contains(textBox1.Text));
if (index >= 0)
{
listView1.Items[index].Selected = true;
}
}
Now if the user hits the button another time, the index should be the next occurrence of the search item in the list. How can I do this starting from the previous index index?
You can use the overload of FindIndex with the start-index:
int index = -1;
private void button1_Click(object sender, EventArgs e)
{
if (index == list.Count - 1)
index = -1;
if (index >= 0)
index = list.FindIndex(index + 1, x => x.Contains(textBox1.Text));
else
index = list.FindIndex(x => x.Contains(textBox1.Text));
if (index >= 0)
{
listView1.Items[index].Selected = true;
}
}
or shorter:
private void button1_Click(object sender, EventArgs e)
{
if (index == list.Count - 1)
index = -1;
index = list.FindIndex(++index, x => x.Contains(textBox1.Text));
if (index >= 0)
listView1.Items[index].Selected = true;
}
This is my code on finding text in my richtextbox and highlighting it:
int start = 0;
int indexOfSearchText = 0;
private void button1_Click(object sender, EventArgs e)
{
int startindex = 0;
if (textBox1.Text.Length > 0)
startindex = FindMyText(textBox1.Text.Trim(), start, richTextBox1.Text.Length);
// If string was found in the RichTextBox, highlight it
if (startindex >= 0)
{
// Set the highlight color as red
richTextBox1.SelectionBackColor = Color.Red;
// Find the end index. End Index = number of characters in textbox
int endindex = textBox1.Text.Length;
// Highlight the search string
richTextBox1.Select(startindex, endindex);
richTextBox1.ScrollToCaret();
// mark the start position after the position of
// last search string
start = startindex + endindex;
}
else
{
MessageBox.Show("0 occurence in richtextbox");
}
}
public int FindMyText(string txtToSearch, int searchStart, int searchEnd)
{
// Unselect the previously searched string
if (searchStart > 0 && searchEnd > 0 && indexOfSearchText >= 0)
{
richTextBox1.Undo();
}
// Set the return value to -1 by default.
int retVal = -1;
// A valid starting index should be specified.
// if indexOfSearchText = -1, the end of search
if (searchStart >= 0 && indexOfSearchText >= 0)
{
// A valid ending index
if (searchEnd > searchStart || searchEnd == -1)
{
// Find the position of search string in RichTextBox
indexOfSearchText = richTextBox1.Find(txtToSearch, searchStart, searchEnd, RichTextBoxFinds.None);
// Determine whether the text was found in richTextBox1.
if (indexOfSearchText != -1)
{
// Return the index to the specified search text.
retVal = indexOfSearchText;
}
}
}
return retVal;
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
start = 0;
indexOfSearchText = 0;
}
}
}
The problem is, when it reaches the end of the richtextBox1, it did not restart at the beginning again! I want to loop it again to the start after reaching the end of the richtextBox1.text.
What about this?
if (textBox1.Text.Length > 0)
{
startindex = FindMyText(textBox1.Text.Trim(), start, richTextBox1.Text.Length);
if(startindex == -1 && start > 0) // Not found string and not searching from beginning
{
// Wrap search
int oldStart = start;
start = 0;
startindex = FindMyText(textBox1.Text.Trim(), start, oldStart);
}
}
The below code is useful for searching a text in richtextbox and highlighting the text in round direction.I was using textbox in richtextbox.i,m entering the search text in textbox and pressing enter button for find next.Initially i,m declaring two values as 0 for start and indexOfSearchText.
int start = 0;
int indexOfSearchText = 0;
private void textBox1_KeyDown(object sender, KeyEventArgs e)
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
int startindex = 0;
if (textBox1.Text.Length > 0)
{
startindex = FindMyText(textBox1.Text.Trim(), start, richTextBox1.Text.Length);
if (startindex == -1 && start >= 0) // Not found string and not searching from beginning
{
// Wrap search
// int oldStart = start;
start = 0;
startindex = FindMyText(textBox1.Text.Trim(), start, richTextBox1.Text.Length);
}
}
// If string was found in the RichTextBox, highlight it
if (startindex >= 0)
{
// Set the highlight color as red
richTextBox1.Select(startindex, textBox1.TextLength);
richTextBox1.SelectionBackColor = Color.Yellow;
// richTextBox1.SelectionColor = Color.Red;
// Find the end index. End Index = number of characters in textbox
int endindex = textBox1.Text.Length;
// Highlight the search string
richTextBox1.Select(startindex, endindex);
// mark the start position after the position of
// last search string
start = startindex + endindex;
}
}
}
public int FindMyText(string txtToSearch, int searchStart, int searchEnd)
{
// Unselect the previously searched string
if (searchStart > 0 && searchEnd > 0 && indexOfSearchText >= 0)
{
richTextBox1.Undo();
}
// Set the return value to -1 by default.
int retVal = -1;
// A valid starting index should be specified.
// if indexOfSearchText = -1, the end of search
if (searchStart >= 0 && indexOfSearchText >= 0)
{
// A valid ending index
if (searchEnd > searchStart || searchEnd == -1)
{
// Find the position of search string in RichTextBox
indexOfSearchText = richTextBox1.Find(txtToSearch, searchStart, searchEnd, RichTextBoxFinds.None);
// Determine whether the text was found in richTextBox1.
if (indexOfSearchText != -1)
{
// Return the index to the specified search text.
retVal = indexOfSearchText;
}
else
{
start = 0;
indexOfSearchText = 0;
//return indexOfSearchText;
}
}
}
return retVal;
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
start = 0;
indexOfSearchText = 0;
string temp = richTextBox1.Text;
richTextBox1.Text = string.Empty;
richTextBox1.Text = temp;
richTextBox1.SelectionBackColor = Color.White;
}
In my RichtextBox, if I have written as below.
This is my pen,
his pen is beautiful.
Now I search word "is" then
output would be as below.
All "is" should be highlighted.
What about:
static class Utility {
public static void HighlightText(this RichTextBox myRtb, string word, Color color) {
if (word == string.Empty)
return;
int s_start = myRtb.SelectionStart, startIndex = 0, index;
while((index = myRtb.Text.IndexOf(word, startIndex)) != -1) {
myRtb.Select(index, word.Length);
myRtb.SelectionColor = color;
startIndex = index + word.Length;
}
myRtb.SelectionStart = s_start;
myRtb.SelectionLength = 0;
myRtb.SelectionColor = Color.Black;
}
}
Looks like this would do it.
http://www.dotnetcurry.com/ShowArticle.aspx?ID=146
int start = 0;
int indexOfSearchText = 0;
private void btnFind_Click(object sender, EventArgs e)
{
int startindex = 0;
if(txtSearch.Text.Length > 0)
startindex = FindMyText(txtSearch.Text.Trim(), start, rtb.Text.Length);
// If string was found in the RichTextBox, highlight it
if (startindex >= 0)
{
// Set the highlight color as red
rtb.SelectionColor = Color.Red;
// Find the end index. End Index = number of characters in textbox
int endindex = txtSearch.Text.Length;
// Highlight the search string
rtb.Select(startindex, endindex);
// mark the start position after the position of
// last search string
start = startindex + endindex;
}
}
public int FindMyText(string txtToSearch, int searchStart, int searchEnd)
{
// Unselect the previously searched string
if (searchStart > 0 && searchEnd > 0 && indexOfSearchText >= 0)
{
rtb.Undo();
}
// Set the return value to -1 by default.
int retVal = -1;
// A valid starting index should be specified.
// if indexOfSearchText = -1, the end of search
if (searchStart >= 0 && indexOfSearchText >=0)
{
// A valid ending index
if (searchEnd > searchStart || searchEnd == -1)
{
// Find the position of search string in RichTextBox
indexOfSearchText = rtb.Find(txtToSearch, searchStart, searchEnd, RichTextBoxFinds.None);
// Determine whether the text was found in richTextBox1.
if (indexOfSearchText != -1)
{
// Return the index to the specified search text.
retVal = indexOfSearchText;
}
}
}
return retVal;
}
// Reset the richtextbox when user changes the search string
private void textBox1_TextChanged(object sender, EventArgs e)
{
start = 0;
indexOfSearchText = 0;
}
This will show all the searched criteria at the same time.
Using: 1 Textbox (to enter the text to search for) and 1 Button (to Run the Search).
Enter your search criteria inside the textbox and press search button.
// On Search Button Click: RichTextBox ("rtb") will display all the words inside the document
private void btn_Search_Click(object sender, EventArgs e)
{
try
{
if (rtb.Text != string.Empty)
{// if the ritchtextbox is not empty; highlight the search criteria
int index = 0;
String temp = rtb.Text;
rtb.Text = "";
rtb.Text = temp;
while (index < rtb.Text.LastIndexOf(txt_Search.Text))
{
rtb.Find(txt_Search.Text, index, rtb.TextLength, RichTextBoxFinds.None);
rtb.SelectionBackColor = Color.Yellow;
index = rtb.Text.IndexOf(txt_Search.Text, index) + 1;
rtb.Select();
}
}
}
catch (Exception ex) { MessageBox.Show(ex.Message, "Error"); }
}
}
}
If you only want to match the whole word you can use this, note that this ignores case and also the |s\b means that plurals get highlighted e.g. Cat matches cats but not caterpiller :
public static void HighlightText(RichTextBox myRtb, string word, Color color)
{
if (word == string.Empty)
return;
var reg = new Regex(#"\b" + word + #"(\b|s\b)",RegexOptions.IgnoreCase);
foreach (Match match in reg.Matches(myRtb.Text))
{
myRtb.Select(match.Index, match.Length);
myRtb.SelectionColor = color;
}
myRtb.SelectionLength = 0;
myRtb.SelectionColor = Color.Black;
}
private void button3_Click(object sender, EventArgs e)
{
if (textBox1.Text != "")
{
for (int i = 0; i < richTextBox1.TextLength; i++)
{
richTextBox1.Find(textBox1.Text, i, RichTextBoxFinds.None);
richTextBox1.SelectionBackColor = Color.Red;
}
}
else
{
for (int i = 0; i < richTextBox1.TextLength; i++)
{
richTextBox1.SelectAll();
richTextBox1.SelectionBackColor = Color.White;
}
}
}[lets make it!][1]
I would do it like that because all the other answers highlight the text, but doesnt change it back after you searched again.
Use the RichText Find Method to find the starting index for the searching word.
public int FindMyText(string searchText, int searchStart, int searchEnd)
{
int returnValue = -1;
if (searchText.Length > 0 && searchStart >= 0)
{
if (searchEnd > searchStart || searchEnd == -1)
{
int indexToText = richTextBox1.Find(searchText, searchStart, searchEnd, RichTextBoxFinds.MatchCase);
if (indexToText >= 0)
{
returnValue = indexToText;
}
}
}
return returnValue;
}
Use a Button or TextChangeListener and Search for your word.
private void button1_Click(object sender, EventArgs e)
{
// Select the first char in your Richtextbox
richTextBox1.SelectionStart = 0;
richTextBox1.SelectionLength = richTextBox1.TextLength;
// Select until the end
richTextBox1.SelectionColor = Color.Black;
// Make the Text Color black
//Use an Inputfield to add the searching word
var word = txtSearch.Text;
//verify the minimum length otherwise it may freeze if you dont have text inside
if (word.Length > 3)
{
int s_start = richTextBox1.SelectionStart, startIndex = 0, index;
while ((index = FindMyText(word, startIndex, richTextBox1.TextLength)) != -1)
{
// goes through all possible found words and color them blue (starting index to end)
richTextBox1.Select(index, word.Length);
richTextBox1.SelectionColor = Color.Blue;
startIndex = index + word.Length;
}
// Color everything between in color black to highlight only found words
richTextBox1.SelectionStart = startIndex;
richTextBox1.SelectionLength = 0;
richTextBox1.SelectionColor = Color.Black;
}
}
I would highly recommend to set a minimum word length to avoid freezing and high memory allocation.
I have a RichTextBox with for example this piece of text:
Hi, my name is {name}!
When I put my cursor between the brackets I want my richtextbox to select the entire word between brackets and also the brackets.
so when I do this: ('|'is the cursor)
Hi, my name is {n|ame}!
I want to select '{name}'
How can I do this?
I have made this to extend the selection in a WPF RichTextBox. I'm new to WPF so I don't know if it's the best way to do it.
private TextRange ExtendSelection(LogicalDirection direction)
{
TextRange tr = new TextRange(CaretPosition, CaretPosition.GetInsertionPosition(direction));
bool found = false;
while (!found)
{
if (tr == null)
{
break;
}
else
{
// If we are not at the end of the document (or at the beginning)
TextPointer next = null;
if (LogicalDirection.Forward.CompareTo(direction) == 0 && tr.End.CompareTo(Document.ContentEnd) == -1)
{
next = tr.End.GetNextInsertionPosition(direction);
}
else if (LogicalDirection.Backward.CompareTo(direction) == 0 && tr.Start.CompareTo(Document.ContentStart) == 1)
{
next = tr.Start.GetNextInsertionPosition(direction);
}
// Be careful with boundaries!
if (next != null)
{
TextRange trNext = new TextRange(CaretPosition, next);
char[] text = trNext.Text.ToCharArray();
for (int i = 0; i < text.Length; i++)
{
if (Char.IsWhiteSpace(text[i]) || Char.IsSeparator(text[i]))
{
found = true;
break;
}
}
if (!found)
{
tr = trNext;
}
}
else
{
break;
}
}
}
return tr;
}
private void MyRichTextBox_PreviewMouseDoubleClick(object sender, MouseButtonEventArgs e)
{
TextRange left = ExtendSelection(LogicalDirection.Backward);
TextRange right = ExtendSelection(LogicalDirection.Forward);
if (!left.IsEmpty && !right.IsEmpty)
{
Selection.Select(left.Start, right.End);
Console.WriteLine("Highlight: '" + Selection.Text + "'");
}
}
I write something you can work on (the code below only works with a single line RTB):
private void richTextBox1_PreviewMouseUp(object sender, MouseButtonEventArgs e)
{
TextPointer oldpointer = richTextBox1.CaretPosition; //current caret position
int startposition = richTextBox1.Document.ContentStart.GetOffsetToPosition(richTextBox1.CaretPosition.GetPositionAtOffset(0, LogicalDirection.Forward));
if (startposition > 2)
{ //get RTB text
richTextBox1.SelectAll();
string wholetext = richTextBox1.Selection.Text;
//reset the caret back
richTextBox1.CaretPosition = oldpointer;
//split text by the caret
string starthalf = wholetext.Substring(0, startposition - 2);
string endhalf = wholetext.Remove(0, startposition - 2);
//get position of "{" and "}"
int seleStart = starthalf.LastIndexOf('{');
int seleEnd = endhalf.IndexOf('}') < 0 ? -1 : endhalf.IndexOf('}') + starthalf.Length + 1;
//select the pattern
if (seleStart >= 0 && seleEnd > 0)
{
richTextBox1.Selection.Select(richTextBox1.Document.ContentStart.GetPositionAtOffset(seleStart + 2), richTextBox1.Document.ContentStart.GetPositionAtOffset(seleEnd + 2));
}
}
}
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());
}
}