Putting alternate elements of an array into a combobox - c#

I have a certain number of elements in an array(statsname).
they are in fact as follows
x[1] A_NAME
x[2] A_CATEGORY
x[3] ANOTHER_NAME
x[4] A_CATEGORY
I want the categories in a combobox.
I did
int up =1;
foreach (string things in statsname)
{
//if the stat name doesnot contains TIME
//Only then we add it to the combobox.
if ((Convert.ToString(things[up]) == "CurrentNumber") || (Convert.ToString(things[up]) == "TotalNumber"))
{
tcomboBox1.Items.Add(things[up-1]);
}
up++;
if (up != statsname.Count())
{
tcomboBox1.Items.Add(things[up - 1]);
}
}
However I get an error saying
Array out of bound
Why is it so ?
Where Did I go wrong ?

Problem : you are comapring the character with String, it will never become true.
Solution : if you just want to get all the Categories added in array at odd positions like 1,3,5..etc.,
you can get the odd value out from array and assign the value to combobox.
EDIT : if you want you can get Even value out from array and assign the value to combobox.
Try This:
string [] statsname=new string[] {"A_NAME1","Cat1","A_NAME2","Cat2","A_NAME3","Cat3","A_NAME4","Cat4"};
for(int i=0;i<statsname.Length;i++)
{
if(i%2==0)
tcomboBox1.Items.Add(statsname[i]);
}

An IndexOutOfRangeException has occurred. This happens in C# programs that use array types. This exception will typically occur when a statement tries to access an element at an index greater than the maximum allowable index.
for (int i = 0; i < type.Length; i++)
{
form.comboBox1.Items.Add(type[i]);
}

Related

c# list index 0 showing value as -1

I am creating a basic program in unity where I check a list array index carry out a certain action depending on the value, I then increment the index.The problem I am having is that the array always stores in index 0 and always equals -1.
public class numGen(){
int val;
int i = 0;
System.Random rnd = new System.Random();
val = rnd.Next(1, 5);
arrayList.Add(val);
Debug.Log("val"+val);
Debug.Log("array"+arrayList.IndexOf(i));
if (arrayList.IndexOf(i) == 1)
{
Debug.Log("action1");
i++;
}
else if (arrayList.IndexOf(i) == 2)
{
Debug.Log("action2");
i++;
}
//and so on
}
I have used debug in the log, so val will output a expected value, e.g. 2, gets added into the array when I check the value stored in the index it's -1.
Not sure how or why the int value is changing.
The problem here is a misunderstanding how ArrayList and IndexOf() works.
ArrayList.IndexOf()
Searches for the specified Object and returns the zero-based index of the first occurrence within the range of elements in the ArrayList that starts at the specified index and contains the specified number of elements.
So your exception comes from:
The zero-based index of the first occurrence of value within the range of elements in the ArrayList that starts at startIndex and contains count number of elements, if found; otherwise, -1.
I think your are looking for something like this:
ArrayList.Item()
Gets or sets the element at the specified index.
Also it's possible to
This property provides the ability to access a specific element in the collection by using the following syntax: myCollection[index].
An example in your case:
if (arrayList[i] == 1)
{
// if true..
}
arrayList.IndexOf(i) gives the index of any element with the value of i. If you want the value at index i, you must use arrayList[I] instead.
IndexOf gives the index of the value you give. If there is no equal value found in the array it returns -1
ArrayList arr = new ArrayList();
arr.Add(5);
arr.Add(2);
var isMinusOne = arr.IndexOf(0); //Is -1
var isZero = arr.IndexOf(5); //Is 0

IndexOutOfRange Exception Thrown on Setting Int value to Array

On my app a teacher can have several classes, and when I exclude a teacher's profile I have to, first, delete his classes. I'm trying to put each class_id of this teacher on an int array, to later delete all classes which the id is contained inside this array.
This is my code so far:
int x = 0;
int[] count = new int[x];
while (reader_SelectedClasses.Read())
{
if(x != 0)
{
x++;
count = new int[x];
}
count[x] = _class.Class_id = reader_SelectedClasses.GetInt16("class_id");
}
And this is what
reader_SelectedClasses.Read()
does:
select class_id from tbl_class where user_id = " + id + ";
And this is the return, when I try this on MySQL:
But it gives me back an IndexOutOfRangeException when I run the code on my DAO class. What am I missing? Already went here but didn't quite understand. Can someone please explain on few words and post and fixed code for this?
You need to learn how to use a debugger and step through your program.
count = new int[x]; discards what was in count and creates a new array that contains zeroes. This array's indexes go from 0 to x - 1.
count[x] = ... sets the array element at index x which according to the previous line is one past the end of the array.
You need to set count = new int[x] only once, at the beginning of your program, and set count[x] = ... only if x >= 0 and x < count.Length.
You are getting IndexOutOfRange Exception because you are trying to access element from array which is out of range.
At first line you are setting x = 1. Hoping that controller enters while loop and as x is 1 it doesn't enter if loop and it executes next statement. But count[1] (x = 1) is not allowed as you have created array with only one element and that you can access with count[0]. (Array indexing starts from 0)
You are trying to achieve a List behavior with an array.
Obviously, the IndexOutOfRangeException is because you initialize an empty array and then try to add values to it in a non-existing cell.
Try to convert to List<int>:
List<int> count = new List<int>();
while (reader_SelectedClasses.Read())
{
int classId = _class.Class_id = reader_SelectedClasses.GetInt16("class_id");
count.Add(classId);
}
If you really need an array out of it you can do:
int[] countArray = count.ToArray()

How do i make this button's event handler to add multiple values into an array?

My program allows the user to input values of hours and minutes into an array of predefined length.
I want to have this button called add for a form I'm creating to allow multiple inputs from the user until the array is fully inhabited. Then when it's done, to call a sortArray() method They way it is now it only allows one input then it throws an exception. How do I go about this?
private void addButton_Click(object sender, EventArgs e)
{
int index = 0;
try
{
while (index <= array.Length)
{
minutes = Int32.Parse(minutesTextBox.Text);
hours = Int32.Parse(hoursTextBox.Text);
MessageBox.Show("You have successfully entered a time!");
array[index] = new RandomClass.Time(hours, minutes);
index = index + 1;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.GetType().FullName);
MessageBox.Show("Please only input integer numbers. Start again from the beginning");
hoursTextBox.Text = null;
minutesTextBox.Text = null;
array = null;
arrayLength = null;
}
MessageBox.Show("Please choose what order you want arrange the sort!");
FileA.RandomClass.sortArray(array);
}
You haven't shown how large the array is, but this line:
while (index <= array.Length)
will cause a problem when you get to the end of your array because the indices of an array go from zero to one less than the length of the array.
So you need to change this line to either:
while (index < array.Length)
It might safer to loop like this:
foreach (ver element in array)
{
// do stuff
element = new RandomClass.Time(hours, minutes);
}
as this way there is no way you can loop beyond the end of the array.
Dont use this line. You will get IndexOutOfRangeException exception where index will be equal to array length.
while (index <= array.Length)
You should use like this.
while (index < array.Length)
One more this, you can use int.TryParse to get rid of exception id text is null or emptry.
I am basing my answer on the assumption that the add button has to be clicked for every new value of hours and minutes.
Currently I see the following problems in your code
int index = 0;
You are setting the index to zero every time the add button is clicked, due to this array values are overwritten on every click of the add button. Initialize index at a more appropriate place in your code.
while (index <= array.Length)
Let's assume the array is of length 5 and the value of index=5, then this line will cause an error as arrays are zero indexed in c#
minutes = Int32.Parse(minutesTextBox.Text);
Int32.Parse method returns a bool, which represents whether the conversion succeeded or not. A more appropriate way to use int32.Parse would be
Int32.Parse(minutesTextBox.Text, out minutes);
Now, since the new values are added per Add button click you can change the while to if and else. i.e.,
if(index < array.Length)
//Parse, add to array and increment the index
else
//Reset index (if required) and Call the sortArray() method.

index out of range checker not working

So I would only like to assign the value to 'originalCOlumName' if there is a value in dataStore.DataSourceDef.Rows[columnIndex].ItemArray[3].ToString(); if it is NULL or out of range, doesnt exist etc...I want to skip this part.
Ive tried looking at another example on Preventing Index Out of Range Error
but NULL checkers didnt work also tried
if(string.IsNullOrEmpty(dataStore.DataSourceDef.Rows[columnIndex].ItemArray[3].ToString())
You would need to check the length of both the Rows and the ItemArray collections to ensure they have enough elements to index into... Remembering that to get element number 3, the array must contain 4 items since numbering starts at 0. This would look something like;
var rowsLength = dataStore.DataSourceDef.Rows.Count;
if (rowsLength >= columnIndex + 1){
var itemArrayLength = dataStore.DataSourceDef.Rows[columnIndex].ItemArray.Count;
if (itemArrayLength >= 4){
var theString = dataStore.DataSourceDef.Rows[columnIndex].ItemArray[3].ToString();
}
}

Getting element of enum in array

I need to figure out how to get an element on an enum in an array.
Basically, I have a grid of 9x9 buttons. I have two multi-dimensional arrays that houses these values. One houses their names (if the name is 43) it means 5 down, 4 across (because they start at 0). The name is also the same as the ELEMENT of itself in the array.
string[,] playingField = new string[9, 9];
enum CellType { Empty, Flag, Hidden, Bomb }
CellType[,] cells = new CellType[9, 9];
the names of the buttons are held in playingField.
the status of each cell is held in cells (if it is empty, has a bomb, etc.)
Credit to AbdElRaheim for giving the above. The reason I'm doing this is so I can get a button name (exactly the same as the element name) which will be the same in both arrays.
For example: I can do this:
string dim1 = Convert.ToString(btn.Name[0]);
string dim2 = Convert.ToString(btn.Name[1]);
if (cells[Convert.ToInt32(dim1), Convert.ToInt32(dim2)] == CellType.Bomb)
(please excuse my terrible converting. i'll fix that up later ;)) and what the above does is it allows me to see if a cell that you click has a bomb under it.
However, what I need to do now, is essentially reverse of this. In the above I know the element name that I want to compare it to, because the element name is the same as the button name. However, now what I need to do is FIND the element name (button name) by getting the element of all elements that are Bomb in cells.
I'm not sure how to do this, I tried:
foreach (CellType Bomb in cells)
{
but it doesn't do anything. I need to find all 'bomb' in 'cells' and return the element name. That way I can use that element name, convert it to string, and use my StringToButton method to create a reference to the button.
This is the way I'm currently doing it, for reference, and to help you understand a little better, but take note this is NOT the way I want to continue doing it. I want to do it the way I asked about above :)
foreach (string i in minedNodes)
{
Button buttonName = StringToButton(Convert.ToString(i));
buttonName.Image = new Bitmap(dir + "mine.png");
}
Thanks!
If you are looking for a way to traverse your cells array, you would do this:
int oi, ii;
for (oi = 0; oi <= cells.GetUpperBound(0); ++oi)
{
for (ii = 0; ii <= cells.GetUpperBound(1); ++ii)
{
System.Diagnostics.Debug.WriteLine(
"Checking: " + oi + "," + ii + " : " + cells[oi, ii].ToString()
);
}
}
You can then save a list of references to cells[oi, ii] contents which match your desired value.

Categories

Resources