I'm trying to remove to selected index in my Listbox but I get an error:
System.ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection. (Parameter 'index')
Please help me, I'm a newbie to C#.
public void listBoxName_SelectedIndexChanged(object sender, EventArgs e)
{
int index = listBoxName.SelectedIndex;
labelName.Text = clients[index].Name;
labelAge.Text = clients[index].Age.ToString();
labelPhone.Text = clients[index].Phone;
labelAddress.Text = clients[index].Address;
}
private void buttonClearFields_Click(object sender, EventArgs e)
{
textBoxName.Text = "";
textBoxAge.Text = "";
textBoxPhone.Text = "";
textBoxAddress.Text = "";
}
private void buttonRemove_Click(object sender, EventArgs e)
{
listBoxName.Items.RemoveAt(listBoxName.SelectedIndex);
}
int index = listBoxName.SelectedIndex;
if (index < 0 || index > clients.Length) return;
listBoxName.Items.RemoveAt requires the passed index to be in the range 0..(n-1), where n is the number of items currently in listBoxName.
It looks like in your case listBoxName.SelectedIndex returns a negative value.
It could be either because listBoxName is empty, or it contains items but none is selected.
A possible fix would be:
private void buttonRemove_Click(object sender, EventArgs e)
{
int selIdx = listBoxName.SelectedIndex;
if (selIdx < 0 || selIdx >= listBoxName.Items.Count) return;
listBoxName.Items.RemoveAt(selIdx);
}
Related
I'm working on a project in Visual Studios 2015 (Visual c#).
I have a textbox in which is introduced a number beetween 0 and 11.So if the number isn't beetween 0 and 11 or in the textbox1 is introduced a char or string value, a Message Box will pop up saying that the value introduced it's incorrect.
But , if I delete the numbers from the textbox1 or introduce a char character ,press space - the application chrases.
Here is the code :
private void textBox1_TextChanged(object sender, EventArgs e)
{
int a;
a = Convert.ToInt32(textBox1.Text);
if (textBox1.Text == null)
{
MessageBox.Show("incorrect");
}
else
if (a < 0 || a > 11)
{
MessageBox.Show("incorrect");
}
}
I need to find a method that doesn't crashes when I introduce a char or string value ,or a number that isn't between 0 and 11.
(the numbers introduced in the textbox1 are always int)
Your app crashes because you are trying to convert TextBox.Text value to int and it is possible that this value cannot be converted to int so, you get exception. If this value is non-number or empty string then Convert.ToInt32() crashes (throws exception and this exception in not handled - crash).
In your case it will be better to use int.TryParse() method instead of Convert.ToInt32() - if int.TryParse() returns true then it is number and you can check if value is in needed range, if int.TryParse() returns false then value cannot be parsed to int(it is some non-digit string):
private void textBox1_TextChanged(object sender, EventArgs e)
{
int a;
bool parsed = int.TryParse(textBox1.Text, out a);
if (!parsed || a < 0 || a > 11)
{
MessageBox.Show("incorrect");
}
}
Try This
private void textBox1_TextChanged(object sender, EventArgs e)
{
int a;
int = 0;
try
{
a = Convert.ToInt32(textBox1.Text);
}
catch(Exception exc){
MessageBox.Show("incorrect exception thrown");
}
if (textBox1.Text == null)
{
MessageBox.Show("incorrect");
}
else
if (a < 0 || a > 11)
{
MessageBox.Show("incorrect");
}
}
The try parse equivelant:
private void textBox1_TextChanged(object sender, EventArgs e)
{
int a;
bool succes = int.TryParse(textBox1.Text, out a);
if(!succes)
{
MessageBox.Show("incorrect");
return;
}
if (a < 0 || a > 11)
{
MessageBox.Show("incorrect");
}
// ... Do stuff to a?
}
Your conversion is not correct
private void textBox1_TextChanged(object sender, EventArgs e)
{
int a;
bool result= int.TryParse(textBox1.Text, out a);
if (textBox1.Text == null || res)
{
MessageBox.Show("incorrect");
}
else
if (a < 0 || a > 11)
{
MessageBox.Show("incorrect");
}
}
My application should get user input as well as a number of repetitions.
After it's verified as positive data, it should display results in a list box.
Results should be phrase # of reps entered.
I know I need to use a while loop but where am I going wrong. Below is what I have so far:
private void btnDisplay_Click(object sender, EventArgs e)
{
// Delcare variables
int Numberofreps;
int Count = 1;
string Phrase = txtPhrase.Text;
//Get the inputs
if (int.TryParse(txtNumberofreps.Text, out Numberofreps))
{
if (txtPhrase.Text == Phrase)
{
lstDisplay.Items.Add(txtPhrase.Text);
}
//Check to make sure its a positive value
while(Count >= 1)
{
//Display the number of reps
lstDisplay.Items.Add(txtPhrase.Text);
}
}
else
{
MessageBox.Show("Not a Positive Value");
}
You have in infinite loop since you are not changing the value of Count inside.
I would probably change the code to this:
private void btnDisplay_Click(object sender, EventArgs e)
{
// Delcare variables
int Numberofreps;
//Get the inputs
if (int.TryParse(txtNumberofreps.Text, out Numberofreps) && Numberofreps > 0)
// Note I've added a check that the Numberofreps is a positive integer.
{
while(Numberofreps > 0)
{
//Display the number of reps
lstDisplay.Items.Add(txtPhrase.Text);
Numberofreps--; // Note this line.
}
}
else
{
MessageBox.Show("Not a Positive Integer");
}
}
I suggest using for loop instead of while:
private void btnDisplay_Click(object sender, EventArgs e) {
int Numberofreps;
if (!int.TryParse(txtNumberofreps.Text, out Numberofreps))
MessageBox.Show("Not a integer Value");
else if (Numberofreps <= 0)
MessageBox.Show("Not a Positive Value");
else {
for (int i = 0; i < Numberofreps; ++i)
lstDisplay.Items.Add(txtPhrase.Text);
}
}
If you insist on while loop:
int i = 0;
while (i < Numberofreps) {
lstDisplay.Items.Add(txtPhrase.Text);
i += 1;
}
count in initially 0.
array list contain 3 questions at 0 1 2 index.
using click event on button it shows only the 0 index value whenever i click on button.
i want that whenever i click on button array index incremented and show the next question.
public void Button1_Click(object sender, EventArgs e)
{
if (count != 3)
{
lbl_question.Text = question_list[count].ToString();
rdb_op1.Text = op1_list[count].ToString();
rdb_op2.Text = op2_list[count].ToString();
rdb_op3.Text = op3_list[count].ToString();
rdb_op4.Text = op4_list[count].ToString();
count = count + 1;
}
declare a static variable so that it doesn't reset when you load the page
public static int count { get; set; }
and then use it in your event
public void Button1_Click(object sender, EventArgs e)
{
if (count != 3)
{
lbl_question.Text = question_list[count].ToString();
rdb_op1.Text = op1_list[count].ToString();
rdb_op2.Text = op2_list[count].ToString();
rdb_op3.Text = op3_list[count].ToString();
rdb_op4.Text = op4_list[count].ToString();
count = count + 1;
}
else
{
count = 0;
}
This button is populate which means click on this button will auto generate random numbers .
This is my code:
protected void Button1_Click(object sender, EventArgs e)
{
int rid = RandomNumber(-111, 999);
int rid1 = RandomNumber(-111, 999);
int rid2 = RandomNumber(-222, 888);
int rid3 = RandomNumber(-333, 777);
int rid4 = RandomNumber(-222, 777);
int rid5 = RandomNumber(-333, 444);
int rid6 = RandomNumber(-555, 888);
int rid7 = RandomNumber(444, 999);
int rid8 = RandomNumber(111, 222);
int rid9 = RandomNumber(222, 333);
txt1.Text = rid.ToString();
txt2.Text = rid1.ToString();
txt3.Text = rid3.ToString();
txt4.Text = rid4.ToString();
txt5.Text = rid5.ToString();
txt6.Text = rid6.ToString();
txt7.Text = rid7.ToString();
txt8.Text = rid8.ToString();
txt9.Text = rid9.ToString();
}
The second button is sort list.
How to take all the numbers and follow acceding to put back in the 9 different textbox ?
This is the coding for button sortlist:
protected void Button2_Click(object sender, EventArgs e)
{
int no1;
int no2;
int no3;
int no4;
int no5;
int no6;
int no7;
int no8;
int no9;
//int answer;
no1 = int.Parse(txt1.Text);
no2 = int.Parse(txt2.Text);
no3 = int.Parse(txt3.Text);
no4 = int.Parse(txt4.Text);
no5 = int.Parse(txt5.Text);
no6 = int.Parse(txt6.Text);
no7 = int.Parse(txt7.Text);
no8 = int.Parse(txt8.Text);
no9 = int.Parse(txt9.Text);
int[] a = new int[] {no1,no2,no3,no4,no5,no6,no7,no8,no9 };
Array.Sort(a);
foreach (var str in a)
{
MessageBox.Show(str.ToString());
}
}
I can display sort ACS in MessageBox but I can't put the number ACS into textbox
But still can't get the answer, where was wrong?
Thank you for help.
You could throw the generated numbers into a list, sort the list and assign the numbers accordingly. Thus, txt1.Text = sortedRandList[0]; and so on for the rest.
To get slightly cleaner code, you could consider also throwing all the text boxes within a list, and eventually end up doing textBoxesList[i] = sortedRandList[i];. That should clean up the code a little bit.
You can create List of ints and then sort it like this :
List<int> rids = null;
protected void Button1_Click(object sender, EventArgs e)
{
rids = new List<int>()
{
RandomNumber(-111, 999),
RandomNumber(-111, 999),
RandomNumber(-222, 888),
RandomNumber(-333, 777),
RandomNumber(-222, 777),
RandomNumber(-333, 444),
RandomNumber(-555, 888),
RandomNumber(444, 999),
RandomNumber(111, 222),
RandomNumber(222, 333)
};
DisplayValues(); // use it if you want to show your values in UI
}
protected void sortButton_Click(object sender, EventArgs e)
{
rids.Sort();
DisplayValues()
}
private void DisplayValues()
{
for (int i = 0; i < Controls.Count; i++)
{
if (Controls[i] is TextBox) if(Controls[i]).ID.Contains("txt"))
(Controls[i] as TextBox).Text = rids[Int32.Parse(Controls[i].ID.Replace("txt", "")) - 1].ToString();
}
}
I would like to see label6 display the number of correct times the user chooses the number. And label7 display the number of times the user choose incorrectly. Its not incrementing by one.
Error 1 Operator '++' cannot be applied to operand of type 'string'
Error 2 Operator '++' cannot be applied to operand of type 'string'
private void button1_Click(object sender, EventArgs e)
{
string correct="0";
string incorrect="0";
RandomNumber(0,99);
button2.Enabled = true ;
button1.Enabled = false;
label3.Visible = true;
if (textBox1.Text == label1.Text)
label3.Text=("Winner");
label6.Text = correct +1;
if (textBox1.Text != label1.Text)
label7.Text = incorrect= +1;
label3.Text=(string.Format("Sorry - You Lose, The number is {0}", label1.Text));
}
Edit (From OP's answer to his own question):
I have tried the ways your suggesting but the number doesnt increase by one everytime I guess wrong.
private void button1_Click(object sender, EventArgs e)
{
int correct=0;
int incorrect=0;
RandomNumber(0,99);
button2.Enabled = true ;
button1.Enabled = false;
label3.Visible = true;
if (textBox1.Text == label1.Text)
{
label3.Text = ("Winner");
label6.Text = (++correct).ToString();
}
else if (textBox1.Text != label1.Text)
{
label7.Text = (incorrect+1).ToString();
label3.Text = (string.Format("Sorry - You Lose, The number is {0}", label1.Text));
}
}
It doesn't look like you're persisting the correct and incorrect
Create Properties:
public int Correct { get; set; }
public int Incorrect { get; set;}
Then:
private void button1_Click(object sender, EventArgs e)
{
RandomNumber(0,99);
button2.Enabled = true ;
button1.Enabled = false;
label3.Visible = true;
if (textBox1.Text == label1.Text)
{
label3.Text=("Winner");
label6.Text = (++this.Correct).ToString();
}
else
{
label3.Text=(string.Format("Sorry - You Lose, The number is {0}", label1.Text));
label7.Text = (++this.Incorrect).ToString();
}
}
You are storing your correct and incorrect variables as string.
Use int instead like this:
int correct = 0;
int incorrect = 0;
and change your code to:
correct++;
label6.Text = correct.ToString();
and:
incorrect++;
label7.Text = incorrect.ToString();
Adding to strings, correct and incorrect will just append the string representation of what's added. You have to convert it to an integer type, then increment, then convert back to string. However it would be easier to just keep these variables as integer instance variables. That way incrementing is trivial and you are actually keeping the correct count and not resetting every time the button gets clicked. (There are actually a number of problems with the code)
// instance variables
private int correct = 0;
private int incorrect = 0;
private void button1_Click(object sender, EventArgs e)
{
RandomNumber(0,99);
button2.Enabled = true ;
button1.Enabled = false;
label3.Visible = true;
if (textBox1.Text == label1.Text)
{
label3.Text=("Winner");
label6.Text = (++correct).ToString(); // convert int to string
}
// indentation does not indicate the block
else //if (textBox1.Text != label1.Text)
{
label3.Text=(string.Format("Sorry - You Lose, The number is {0}", label1.Text));
label7.Text = (++incorrect).ToString();
}
}
Or you can use:
correct = correct + 1; ( I think this is what you were trying to achieve)
incorrect = incorrect + 1;
OR
correct += 1;
incorect += 1;
label6.Text = correct +1;
only sets label6's value to correct + 1; it does not change the value of correct. If you use:
int correct;
label6.Text = (++correct).ToString();
you should see what you want.