Getting element of enum in array - c#

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.

Related

Attempting to load int from file into 2d array, receiving "Input string was not in a correct format" error

I've been trying to complete an assignment for my game design class in C#, one of the issues I have been having is that I cannot load my Save1.GAME text file with all the loading information, I receive a "System.FormatException: 'Input string was not in a correct format.'" error.
At the moment, this assignment includes a small panel where you, the player designs a Sokoban (https://en.wikipedia.org/wiki/Sokoban) map, I have already done this part and now I must load that save file into my program, then generate the "tiles" (the tiles just being little squares where items are) into the different panel where the game will actually be played.
So far I've tried to load the file and write it into a string array, line by line.
I've also tried to write the entire file into a string and use the .split(',') function, to no avail.
I've tried quite a few ideas that honestly I've forgotten every single one of them.
My load button on the form where the game will be played:
private void loadToolStripMenuItem_Click(object sender, EventArgs e)
{
OpenFileDialog openLevelDialog = new OpenFileDialog();
openLevelDialog.Title = "Select level to load";
if (openLevelDialog.ShowDialog() == DialogResult.OK)
{
string MyString = System.IO.File.ReadAllText(openLevelDialog.FileName);
int i = 0;
int j = 0;
//My array where I will just dump the whole file into.
int[,] result = new int[10, 10];
//foreach loop where I attempt to go line-by-line and split the individual numbers by ','
foreach (var row in MyString.Split('\n'))
{
j = 0;
foreach (var col in row.Trim().Split(','))
{
result[i, j] = int.Parse(col.Trim()); //Exception happens here.
j++;
}
i++;
}
//Just an attempt to display what the variable values in my form, ignore this part.
for (int a = 0; a < result.GetLength(0); a++)
{
for (int w = 0; w < result.GetLength(1); w++)
{
label1.Text += result[a,w].ToString();
}
}
}
}
And this is the Game1.GAME file
2,2 <--- This is the size of the map, 2X2 = 4 tiles total. ---
0,0,0 <--- This is tile [0,0] and according to my TileTypes enum inside my tile.cs class it should be empty hence, the third 0. ---
0,1,1 <--- This is tile [0,1] and according to my TileTypes enum inside my tile.cs class it should be "The Hero" hence, the 1. ---
1,0,2 <--- This is tile [1,0] and according to my TileTypes enum inside my tile.cs class it should be a wall hence, the 2. ---
1,1,3 <--- This is tile [1,1] and according to my TileTypes enum inside my tile.cs class it should be a box hence, the 3. ---
note: there is a 4th enum with the value of "Destination" but in this particular map I just didn't add any.
How it looks usually
2,2
0,0,0
0,1,1
1,0,2
1,1,3
I was hoping it would just load the string, chop it up into the int array but I cant seem to get past the exception no matter what I do.
Thanks for you're time in advance.
Here's my file from inside notepad++
My System.IO return
Based on the information you've provided, you're erroring out on the last line because newline at the end of your last record.
One means of handling this is to check whether row is Null, Empty, Whitespace in your iteration, and continue your loop if that condition is true.
foreach (var row in MyString.Split('\n'))
{
//skip iteration if row is null, empty, or whitespace
if (string.IsNullOrWhitespace(row))
continue;

Trying to delete an entry from a structure array in C#. Getting conflicting information?

I have been researching this topic and got conflicting answers. Any help is appreciated.
For an assignment, I am instructed to create a structure of arrays. I am trying to delete an entry in one case, and change in another. This is supposed to be by one of the fields and not by index number.
var countOfEmployees = 0;
var employees = new EmployeeData[100];
Console.Write("Please enter employee you want to delete:");
string deleteEmployee = Console.ReadLine();
bool deleted = false;
for (int x = 0; x < countOfemployees; x++)
{
if (items[x].ItemNumber == deleteItemNumber)
{
deleted = true;
}
if (true)
{
//code goes here
}
Any help is appreciated!
In an array, you might be able to delete the value from the place holder, but you will not be able to remove the actual item without some footwork.
Basically, what you can do is: Find the value you've searched for, and replace it with a null and treat it orrespondingly in every other function.
Option 2 would be to remove the item and then use a function that would "shift" all the values with a higher index upwards.
Option 3 is to use the advanced functions C#/.NET has to offer with collections, create a List, remove the item and cast back to an array.
var employees = new EmployeeData[100];
var list = employees.ToList();
int index=-1;
//search through in a loop (won't write it here)...
index = x; //get the index in your list then break the loop
break; //end the loop
list.RemoveAt(index); //delete the spot outside the loop
employees=list.ToArray();
Of course there's checks needed if the search didn't find anything, but i think you can manage to implement that without my help.
And this is of course me assuming that there's only ONE entry with that kind of value in the array.
If it's not, you're gonna have to loop through and erase them until the search doesn't find anything anymore.

Using DataGridView in Visual Studio C#

I have a string that contains: "# of rows, # of columns, Row'X'Col'X'=Serial#, ...
How do I create a DataGrid table with the number of rows and columns defined, and then place the serial #s into the grid.
Examples:
2,1,R1C1=111,R2C1=112,
2,2,R1C1=211,R1C2=212,R2C1=213,R2C2=214,
thanks
Below is code that does what you are asking; however I must point out some problems with this approach. First, getting the total rows and cols from the first two elements in order to create your table is risky. If that data is wrong, this code will most likely crash or possibly omit data. Example if the input is: 2,2,RXCX=.., RXCX=.., RXCX=.., RXCX=..,RXCX=, RXCX=… This line will only get the first 4 values.
Worse… this will crash… if the input is 2,2,RXCX=.., RXCX=.. Then it will crash when you try to access the 4th element in the splitArray because there isn’t a 4th element. Either way is not good.
My point is to be safe… it would be a better approach to see how much data is actually there before you create the grid. You could get how many items there are with StringArray.Length minus the first two elements. These elements will define the dimensions and allow you to check their validity. This will make sure your loops won’t go out of bounds because the supplied data was wrong. It seems redundant and error prone to supply the dimension values when you can get that info from the data itself.
I still am not 100% sure what you want to accomplish here. It looks like a search of some form. This is what I am picturing…
Looking at your (previous) screen shots it appears to me that after you type into the Serial # text box and click the “Search Txt Files” button it will search for data that came from the input string i.e. “PLX51…” and then have the grid display the “filtered” results that match (or are LIKE) what’s in the Serial # textbox. If this is true, I would ignore the RXCX vales and put the data in a single column. Then wire up an OnKeyPress event for the text box to filter the grid whenever the user types into the Serial # text box.
Otherwise I am lost as to why you would need to create the data in the fashion described. Just because the input has unnecessary data… doesn’t mean you have to use it. Just a thought.
string inputString = "2,2,R1C1=211,R1C2=212,R2C1=213,R2C2=214";
string[] splitArray = inputString.Split(',');
int totalRows = int.Parse(splitArray[0]);
int totalCols = int.Parse(splitArray[1]);
int itemIndex = 2;
// add the columns
for (int i = 0; i < totalCols; i++)
{
dataGridView1.Columns.Add("Col", "Col");
}
// add the rows
dataGridView1.Rows.Add(totalRows);
for (int i = 0; i < totalRows; i++)
{
for (int j = 0; j < totalCols; j++)
{
dataGridView1.Rows[i].Cells[j].Value = splitArray[itemIndex];
itemIndex++;
}
}

Swapping two button controls

Having a bit trouble trying to figure out a way to swap 2 buttons. Let just dive in and show you the code:
int mCatID;
int mTempPos;
mCatID = mCatButList[mValidCatNumber - 1].mCatID - 1;
if (mTempOldPos.ToString() != txtCatPos.Text) // Attempt to change position
{
foreach (DataRow row in mIMenu.mCategoryList.Rows) // Check if space is taken
{
if (row[2].ToString() == txtCatPos.Text) // Space is taken
{
mCatOldIDX = mTempOldID - 2;
mTempDesc = mIMenu.mCategoryList.Rows[mCatOldIDX][1].ToString();
mIMenu.mCategoryList.Rows[mCatOldIDX][1] = row[1].ToString(); // desc
mIMenu.mCategoryList.Rows[mCatOldIDX][2] = (int)row[2]; // pos
row[1] = mTempDesc;
row[2] = mTempOldPos; //RP change new location to old
mCatOldIDX = 0;
mIMenu.mCategoryList.AcceptChanges();
break;
}
}
// mIMenu.mCategoryList.DefaultView.Sort = "POS asc";
CreateCatButList();
DisplayMenuCategories();
[EDIT] I have modified the code and now it seems that it does swap the position of the button controls once. But if I swap two of the controls and then swap one of the swapped buttons with another button it seems to mess up all the position values on all of the other buttons!? This is really starting to bug me.. why does it work for the first time and then not for others? Ive tried accept changes and still no effect.. Its all to do with the value in the Datatable mIMenu.mCategoryList where column [1] is Description and [2] is the Position. What is frustrating is why would it work once changing the value and then as soon as the state changes to modified decides to revert back to older position values?

Putting alternate elements of an array into a combobox

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]);
}

Categories

Resources