How to make text selection increment on textbox - c#

I need to finish a program on visual studio with forms, I have a textbox(txtUser), another textbox(txtKerko) and a button(btnKerko). So the program goes like this, the user write some text on txtUser and write any word or text on txtKerko and when btnKerko is clicked that word written on txtKerko should be selected on txtUser, if there are more than one of that word all the words should be selected on every btnKerko click. It's almost ready but I couldn't do the part when there are more than one word to increment one by one. This is the event code for btnKerko :
private void BtnKerko_Click(object sender, EventArgs e)
{
if (txtUser.Text.Contains(txtKerko.Text) == true)
{
txtUser.Focus();
string teksti = txtUser.Text;
txtUser.SelectionStart = teksti.IndexOf(txtKerko.Text);
txtUser.SelectionLength = txtKerko.TextLength;
}
else
{
MessageBox.Show("Nuk u gjet");
}
}

Yes, you can do it if you want to select the word one by one. You can use this code :
int lastIndex = 0;
private void BtnKerko_Click(object sender, EventArgs e)
{
txtUser.Focus();
int index = txtUser.Text.IndexOf(txtKerko.Text, lastIndex);
if (index != -1)
{
lastIndex = index + 1;
txtUser.SelectionStart = index;
txtUser.SelectionLength = txtKerko.TextLength;
}
}
As you can see, the variable lastIndex is holding the last selection in each click of the button. I guess you know that the second parameter of IndexOf method tells to start finding the index from that second parameter value.

Related

WinForm Button stops working after 1-2 uses

I have a program that quizzes the user by naming a Country (from a list) and asks the user to input it's Capital. If they get it correct, a counter for correct answers is shown with +1 added to it. If it is wrong, the same thing goes but for the incorrect counter. I finished the code for it, but whenever I use the Check Answer button, it doesn't verify the input from the TextBox anymore, and none of the counters (correct or incorrect) change at all. If the first one is right and the second is wrong, it counts both 1 for correct and 1 for incorrect. After that the code under the Check Answer button doesn't execute anymore. If I got 2 right or 2 wrong it only counts the first 1 and stops working after.
{
// Declare structure
struct Country
{
// Declare strings
public string countryName;
public string capital;
}
public partial class Form1 : Form
{
// Create List for CourseInfo
private List<Country> countryList = new List<Country>();
Country currentCountry;
public Form1()
{
InitializeComponent();
}
private void ReadFile()
{
try
{
// Call StreamReader to use imported file
StreamReader inputFile;
string line;
Country entry = new Country();
// Delimiter to separate values in text file
char[] delim = { ',' };
// Open text file
inputFile = File.OpenText("countries.txt");
while (!inputFile.EndOfStream)
{
line = inputFile.ReadLine();
// Tokenize the strings separated by the delimiter ','
string[] tokens = line.Split(delim);
entry.countryName = tokens[0]; // Tokenized entry for COUNTRY
entry.capital = tokens[1]; // Tokenized entry for CAPITAL
countryList.Add(entry);
}
}
catch (Exception ex)
{
// Shows error message
MessageBox.Show(ex.Message);
}
}
private void DisplayCountry()
{
// Create random variable
Random rand = new Random();
// Country us randomly chosen from the list
int countryPosition = rand.Next(countryList.Count);
// Selected country
currentCountry = countryList[countryPosition];
// Show selected country in Label
countryAnswerLabel.Text = currentCountry.countryName;
}
private void ExitButton_Click(object sender, EventArgs e)
{
// Closes the form
this.Close();
}
private void Form1_Load(object sender, EventArgs e)
{
// Call method to load StreamReader with the file
ReadFile();
}
private void QuizButton_Click(object sender, EventArgs e)
{
// Call method to show random country
DisplayCountry();
}
private void CheckAnswerButton_Click(object sender, EventArgs e)
{
// Declare integer variables for the counters and set to 0
int correctCounter = 0;
int incorrectCounter = 0;
// If the input is correct, +1 for the correct counter
if (currentCountry.capital == capitalAnswerTextBox.Text)
{
correctCounter++;
correctLabel.Text = correctCounter.ToString();
}
// If the input is incorrect, +1 for the incorrect counter
else
{
incorrectCounter++;
incorrectLabel.Text = incorrectCounter.ToString();
}
}
private void NextQuestionButton_Click(object sender, EventArgs e)
{
// Clears input TextBox
capitalAnswerTextBox.Text = string.Empty;
DisplayCountry();
}
}
Notice that whenever CheckAnswerButton_Click is executed, the variables correctCounter and incorrectCounter are initialised to 0. So every time you press the button, you start counting the answers from 0 again. So you will always be setting one of label's Text to "1". In case that label already shows "1", it would seem like it's "not doing anything".
Therefore, you should move the declarations of correctCount and incorrectCounter to outside the CheckAnswerButton_Click method:
// Declare integer variables for the counters and set to 0
int correctCounter = 0;
int incorrectCounter = 0;
private void CheckAnswerButton_Click(object sender, EventArgs e)
{
// If the input is correct, +1 for the correct counter
if (currentCountry.capital == capitalAnswerTextBox.Text)
{
correctCounter++;
correctLabel.Text = correctCounter.ToString();
}
// If the input is incorrect, +1 for the incorrect counter
else
{
incorrectCounter++;
incorrectLabel.Text = incorrectCounter.ToString();
}
}
This way, they will retain their value after CheckAnswerButton_Click has returned.

Circular show with previous and next buttons

Say I have a list: 1 5 6 10
When I click on next and the List item showed is already 10.. I want to bring the user back to 1 and same in the other way when I click previous and the List item showed is already 1.. I want to bring the user back to 10.. Here is what I tried but I always get that the "i (contor) can't be negative or greater than List.Count" :
public int i = 0;
private void nextbutton_Click(object sender, EventArgs e)
{
++i;
if (sweaterclicked)
{
if(SweatersList.Count != 1)
if (i >= SweatersList.Count - 1)
{
i = 0;
pictureBox1.Image = SweatersList[i];
}
else pictureBox1.Image = SweatersList[i];
}
}
private void previousbutton_Click(object sender, EventArgs e)
{
--i;
if (sweaterclicked)
{
if (SweatersList.Count != 1)
{
if (i < 0)
{
i = SweatersList.Count;
pictureBox1.Image = SweatersList[i];
}
else pictureBox1.Image = SweatersList[i];
}
}
}
Array or list indexes in C# start at zero, so the largest in-range index is one less than the count of items in the collection. Therefore, SweatersList.Count, hence i, is out of range here:
i = SweatersList.Count;
pictureBox1.Image = SweatersList[i];
So when you want to start over at the last valid index, you need to subtract one from SweatersList.Count:
i = SweatersList.Count - 1;
I don't know why you're incrementing and decrementing outside the if (sweaterclicked) blocks, but I presume you do.

Error: (using List class) Index was outside the bounds of array

I'm working on a project and I'm a beginner in programming in c#, and somehow there is a problem that I cannot solve. How it happened: In executing the code, the application launches successfully but an exception
shows that the "Index was outside the bounds of array". Afterwards, I was able to click items on a listbox and it shows the second object on the textbox. So... It seems like it works(clicking on listbox's item) but I cannot figure out why it would throw an exception about the array. Beneath is the current code that I have.
**Update:I sincerely apologize. I uploaded the wrong code. It is suppose to be this code:
Code:
struct studentInfo
{
public string studentID;
public string major;
}
public partial class Form1 : Form
{
private List<studentInfo> studentList = new List<studentInfo>();
public Form1()
{
InitializeComponent();
}
private void ReadInputFile()
{
try
{
StreamReader inputFile;
string line = "";
studentInfo student = new studentInfo();
char[] delimiter = { ',' };
inputFile = File.OpenText("Student Info.txt");
while (!inputFile.EndOfStream)
{
line = inputFile.ReadLine();
string[] token = line.Split(delimiter);
student.studentID = token[0];
student.major = token[1];
studentList.Add(student);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void DisplaystudentID()
{
foreach (studentInfo student in studentList)
{
studentInfoListBox.Items.Add(student.studentID);
}
}
private void DisplayNames()
{
}
private void button1_Click(object sender, EventArgs e)
{
ReadInputFile();
DisplaystudentID();
}
private void studentInfoListBox_SelectedIndexChanged(object sender, EventArgs e)
{
int index = studentInfoListBox.SelectedIndex;
majorTextBox.Text = studentList[index].major;
}
private void button3_Click(object sender, EventArgs e)
{
Application.Exit();
}
}
My guess would be that SelectedIndexChanged is ran at the start (before you select anything) and at that point nameListBox.SelectedIndex would be -1 and you can't get the "negative 1 position's item" in a list. I would make sure that the selected index is valid
https://msdn.microsoft.com/fr-fr/library/system.windows.forms.listbox.selectedindex(v=vs.110).aspx
"A zero-based index of the currently selected item.A value of negative one (-1) is returned if no item is selected."
I would change the code as such:
private void nameListBox_SelectedIndexChanged(object sender, EventArgs e)
{
int index = nameListBox.SelectedIndex;
if(index !=-1)
{
phoneLabel.Text = phoneList[index].phone;
}
// else do nothing, the selected item didn't really change, it's just called for the first time, think of it as the control saying "hey i just got created and i'm notifying you that the selected item is now nothing"
}
You have to guard SelectedIndex, when controls are initially created SelectedIndex is set to -1
private void nameListBox_SelectedIndexChanged(object sender, EventArgs e)
{
if(nameListBox.SelectedIndex >=0)
{
int index = nameListBox.SelectedIndex;
phoneLabel.Text = phoneList[index].phone;
}
}
The only array handling you have in your program is this:
entry.name = tokens[0];
entry.phone = tokens[1];
Therefore the reason is that one of the lines in your text file does not have a comma, so tokens does not have 2 parts.
A common reason for this is simply having a file that has a linefeed after the final real entry, thereby having an empty line as the last line.
I would simply handle this here:
if (tokens.Length < 2)
continue;
You didn't let us know where exactly the exception is occurred but as I see it might be in this part
line = inputFile.ReadLine();
string[] tokens = line.Split(delim);
entry.name = tokens[0];
entry.phone = tokens[1];
If your line is empty or doesn't have "," you will get exception in the next line
Also you need to check the access to list in the index location in nameListBox_SelectedIndexChanged.
"Index was outside the bounds of array" exception occurs when you try to access an element which is not exits in the list. I believe you are getting this exception when you are click on the last item on your list.
In your nameListBox_SelectedIndexChanged method you one of following.
int index = nameListBox.SelectedIndex -1;
or
phoneLabel.Text = phoneList[index-1].phone;

Replace string one by one at run-time in datagridview c#

I have managed to replace all the strings in the datagridview at run-time.Now i want to replace the string one by one on the click of the button.This is the code for the replacement of all the strings on a single button click.
private void button9_Click_1(object sender, EventArgs e)
{
var original = ((DataTable)dataGridView1.DataSource);
var clone = original.Clone();
var ordinal = original.Columns["Stringtext"].Ordinal;
var tra = original.Columns[6].Ordinal;
var che = original.Columns[10].Ordinal;
for (int i = 0; i < original.Rows.Count; i++)
{
var values = original.Rows[i].ItemArray;
if (Convert.ToBoolean(values[tra].ToString()) && Convert.ToBoolean(values[che].ToString()))
{
values[ordinal] = ((values[ordinal].ToString()).ToLower())
.Replace(textBox6.Text.ToLower(), textBox7.Text);
clone.Rows.Add(values);
}
else
{
values[ordinal] = values[ordinal];
clone.Rows.Add(values);
}
}
dataGridView1.DataSource = clone;
string filterBy;
filterBy = "Stringtext Like '%" + textBox7.Text + "%'";
((DataTable)dataGridView1.DataSource).DefaultView.RowFilter = filterBy;
}
I want to replace a single string in a row on the click of a button then on the next button click the next string in the row is replaced.etc.any ideas?
the easy way to do what you want is to keep a counter on how many times did the user pressed the button. that way you can tell this is the 1st, 2end or 3rd time the user clicked the button and by so replace the needed cell
private int counter = 0;
private void button1_Click(object sender, EventArgs e)
{
// change the cell = counter
counter++;
}

Search items in the listbox using index

I am doing a project that uses listbox, I can add items, delete items, update items but I can't search,
this is my code for search
string search = Person.listperson[listBox1.SelectedIndex].lastname;
foreach (String s in search)
{
if (s.Equals(textBox6.Text))
{
//show searched items
MessageBox.Show("Success!");
}
}
can you help me with this?
thanks :)
I have here a code for search,
But it does not apply in the button, how can I apply this on the button?
private void textBox6_TextChanged(object sender, EventArgs e)
{
int index = listBox1.FindString(this.textBox6.Text);
if (0 <= index)
{
listBox1.SelectedIndex = index;
}
}
Try something like this, add a click event to your button and put your code in it. This works for me.
private void button1_Click(object sender, EventArgs e)
{
int index = listBox1.FindString(textBox6.Text);
if (index > -1)
{
listBox1.SelectedIndex = index;
}
}
Not sure what you're trying to do exactly, but here's some samples.
Also, start giving variables useful names. If you come back to this code in a month you'll have no idea what's going on there or what textBox6 is.
To find a string (textBox6) in the entire listperson collection:
var list = Person.listperson.Where(p => p.lastname.Contains(textBox6.Text));
To check if a specific item in listperson has a partial textBox6 value:
var search = Person.listperson[listBox1.SelectedIndex].lastname;
bool success = search.Contains(textBox6.Text);
Or if you'd rather compare the values:
bool success = (search == textBox6.Text);
you can foreach char in a string
string s = "Blippy you";
foreach (char item in s)
{
}
but anywho. try Text.RegularExpressions for string matching.
private void button1_Click(object sender, System.EventArgs e)
{
if (listBox1.FindString("Your String in Textbox 6") != -1)
{
MessageBox.Show("Success!");
}
}

Categories

Resources