I am programming in C# i need to put some things in a string 'xml'
I have the following code
TextBox[] myTextBoxes = new TextBox[] { this.textBox2, this.textBox3, this.textBox4, this.textBox5, this.textBox6, this.textBox7, this.textBox8, this.textBox9, this.textBox10, this.textBox11 };
TextBox[] ValueBoxes = new TextBox[] { this.textBox3, this.textBox5, this.textBox7, this.textBox9, this.textBox11 };
CheckBox[] myCheckBoxes = new CheckBox[] { this.checkBox2, this.checkBox4, this.checkBox6, this.checkBox8, this.checkBox10 };
CheckBox[] myMandBoxes = new CheckBox[] { this.checkBox3, this.checkBox5, this.checkBox7, this.checkBox9, this.checkBox11 };
and to verify certain condition i have
xml += "<fields>";
for (int i = 0; i < myTextBoxes.Length; i++)
{
if (string.IsNullOrWhiteSpace(myTextBoxes[i].Text))
{
if (myCheckBoxes[i].Checked == true)
xml += "<field display='yes'> ";
else
xml += "<field display='no'> ";
if (myMandBoxes[i].Checked == true)
xml += "<mandatory='yes'>";
else
xml += "<Mandatory='no'>";
xml += "<label>" + (string)myTextBoxes[i].Text + "</label>";
}
}
It gives me an Indexoutof boud exception at if (myCheckBoxes[i].Checked == true)
How can i resolve this
Your arrays have different amounts of elements in them so you cannot access them all by using the same index. They will have to be done independently.
You don't have same number of checkboxes as Textboxes so you can't access them against the same index.
Your index is starting from 0 to myTextBoxes.Length, if i is going to be greater than 4, then you will get this exception.
Not really sure what you are trying to do but you can add a check against the length before accessing the element from myCheckBoxes.
if (i < myCheckBoxes.Length && myCheckBoxes[i].Checked == true)
xml += "<field display='yes'> ";
Use Foreach instead
Here edit as myTextBoxes.Length - 1
for (int i = 0; i < myTextBoxes.Length - 1; i++)
EDIT:
Also your checkBox count and Textox count does not tally
Your for loop is running to myTextBoxes.length, but you are iterating through myCheckBoxes. It seems you have more textboxes than CheckBoxes
Change it to:
for (int i = 0; i < myCheckBoxes.Length; i++)
{
Instead of
for (int i = 0; i < myTextBoxes.Length; i++)
use
for (int i = 0; i < myCheckBoxes.Length; i++) // or myMandBoxes.Length (Both the CheckBoxes have same items)
Because you are looping with CheckBoxes so why having a length of TextBox.
Your text box has 11 elements, while checkbox has 5 elements.
Change following
if (string.IsNullOrWhiteSpace(myTextBoxes[i].Text))
to
if (string.IsNullOrWhiteSpace(myTextBoxes[i].Text) && i < myCheckBoxes.Length )
First of all, never use += on strings when constructing them with loops, they are immutable, and using it this way, it's just a waste of speed and memory. Use a StringBuilder instance instead.
As for your question, the length of the myTextBoxes array is 10, so you have items at indexes 0 through 9. The code in this line
if (myCheckBoxes[i].Checked == true)
tries to access the corresponding item in the myCheckBoxes array that has 5 elements (indexed 0 to 4). When i becomes 5, the code accesses the myCheckBoxes[5] that does not exist, hence the exception.
Other than that, textBox2 or checkBox7 are simply awful names for controls, and there are better options in the .net Framework for XML serialization and generation.
Related
I've been trying to display all the pair numbers in a loop that goes from 1 to 100 and increments 1 each time. I try to display the pair numbers like they would in this "if" code block.
for (var i = 0; i < 100; i++)
{
if (i % 2 == 0)
{
Console.WriteLine(i);
}
But I want to save these in a string called "losPares", which I attempt to do display in this way:
static void Main(string[] args)
{
var counter = 0;
var losPares = 0;
for (var i = 0; i < 100; i++)
{
if (i % 2 == 0)
{
counter++;
losPares = i;
}
}
Console.WriteLine("hay " + counter + " numeros pares.");
Console.WriteLine("estos son " + losPares);
}
Which is kinda weird. In the first code example the console will print out all the pair numbers. In the second one it will only print the last of them, 98. I don't really know what to do, tried creating an array instead of a variable but when I try to store "i" in it i get the following error:
Cannot implicitly convert type 'int' to 'int[]'
aAd if i try to cast "i" as a string when losPares is an array instead of a variable, like this:
int[] losPares = new int[100];
for (var i = 0; i < 100; i++)
{
if (i % 2 == 0)
{
counter++;
losPares = Convert.ToBase64CharArray(i);
}
I get the following error.
CS1501 No overload for method 'ToBase64CharArray' takes 1 arguments
I don't really know what to do. Thanks a bunch for reading!
Your console is printing last element because you are assigning value of i to losPares in your sencond code snippet. This assignment operator assinging value of i to losPares in each iteration where i % 2 condition is satisfied.
Instead of assigning value to integer, use List to store i and at the end of for loop print all elements from list.
public static void Main(string[] args)
{
var losPares = List<int>();
var counter = 0;
for (var i = 0; i < 100; i++)
{
if (i % 2 == 0)
{
counter++;
//Below line was executing everytime and in each execution this line was assigning value of i to losPares
//losPares = i;
losPares.Add(i);
}
}
Console.WriteLine("hay " + counter + " numeros pares.");
Console.WriteLine("estos son " + string.Join(Environment.NewLine, losPares));
}
An integer will only have 1 value and cannot have multiple values at the same time. If you want to keep track of all the values from the loop, you will have to save all the values in a collection / list or an array. Following example shows how to save them in a List.
var counter = 0;
var losPares = new List<int>();
for (var i = 0; i < 100; i++)
{
if (i % 2 == 0)
{
counter++;
losPares.Add(i);
}
}
Console.WriteLine("hay " + counter + " numeros pares.");
Console.WriteLine("estos son " + string.Join(" ", losPares));
You can create a list of ints (losPares) and then display that at the end. What you are doing is assigning a value to losPares and then overriding it again and again until the last iteration in you loop. That is why your losPares always have the last value.
As per my understanding below are my takes. First one is printing all values because the printing part is inside the loop but in second both print statements are outside the for loop block because of which it stores the last value of loop and display it.
You can create a string variable and append all the numbers to that string.
string temp = ''; and then in for loop you can do something like temp+=i + ' '; It is better to use string builder because of immutable property of string.
If you want to use array. Below is the way to assign values in a array.
int[] losPares = new int[100];
In a for loop you can use losPares[i] = i; This will fill your array.
I am fairly new to C#, so I'm sorry if this is a simple question
--
I have a list of stock objects and I am using a for loop to go backwards through the list. Each property of the stock object is set to a textbox to display the value and there is a button that allows the user to cycle through each object, changing the values of the textboxes.
I need to tell if I reach the beginning of the list so that I can deactivate the button that allows the user to go backwards through the list.
Note -
The Count is > 1 because I had to skip the first item in the list.
Here is my code:
if (stockList.Count > 1)
{
for (int i = stockList.Count - 1; i >= 0; i--)
{
txtName.Text = stockList[i].Name;
numLastPrice.Value = stockList[i].LastPrice;
numOpeningPrice.Value = stockList[i].OpeningPrice;
numLowPrice.Value = stockList[i].LowPrice;
numHighPrice.Value = stockList[i].HighPrice;
if (i == ???)
{
txtName.Text = stockList[i].Name;
numLastPrice.Value = stockList[i].LastPrice;
numOpeningPrice.Value = stockList[i].OpeningPrice;
numLowPrice.Value = stockList[i].LowPrice;
numHighPrice.Value = stockList[i].HighPrice;
btnBack.Enabled = false;
}
}
If you have 10 items in that list, then you're going backwards from 9 to 0 (indexes are zero based by default)
In your case, 0 indicates the first item in your list, so just check the index is 0
if (i == 0)
(edit after reading comments)
in your for loop you declare i as an int with the value of .Count - 1:
for (int i = stockList.Count - 1; i >= 0; i--)
so in your loop i is just a variable, but as a result of the way you declared it, it will also be the index value of your list as you iterate through the loop.
Hope that helps.
I hope that the following snippet helps you see the relationship between i and the list:
var myList = new List<string>() { "A", "B", "C", "D", "E" };
for (int i = myList.Count() - 1; i >= 0; i--)
{
Console.WriteLine($"i:{i}, myList[{i}]={myList[i]}");
if (i == 3)
{
//I can access the elements at an index different than `i`
Console.WriteLine($"i:{i}, Seaky peek at the 5th element (index 4): {myList[4]}");
}
}
// This would cause a compilation error because `i` is being used outside of `for`
//i = 100; // Error: The name 'i' does not exist in the current context
Console.WriteLine($"First item is myList[0] and is '{myList[0]}'");
Console.WriteLine($"Last item is myList[myLIst.Count()-1] ans is '{myList[myList.Count() - 1]}'");
// Let's go through the list again
for (int someNameForIndex = myList.Count() - 1; someNameForIndex >= 0; someNameForIndex--)
{
Console.WriteLine($"i:{someNameForIndex}, myList[{someNameForIndex}]={myList[someNameForIndex]}");
}
This generates the following output
i:4, myList[4]=E
i:3, myList[3]=D
i:3, Seaky peek at the 5th element (index 4): E
i:2, myList[2]=C
i:1, myList[1]=B
i:0, myList[0]=A
First item is myList[0] and is 'A'
Last item is myList[myLIst.Count()-1] ans is 'E'
i:4, myList[4]=E
i:3, myList[3]=D
i:2, myList[2]=C
i:1, myList[1]=B
i:0, myList[0]=A
In my code I have string array of 1000 indexes and it contain unique string data. Now, I want to make duplicate of some of them string element without overwriting next element. To summarize I would like to shift the array and inserting a duplicate value.
Here my code is,
for (int r = 0; r < sResultarray1.Length; r++)
{
if (sResultarray1[r] != null &&
sResultarray1[r].Contains("WP") &&
sResultarray1[r].Contains("CB") == true)
{
index = Array.IndexOf(sResultarray1, sResultarray1[r]);
for (int e = 1000; e >= index + c; e--)
{
sResultarray1[e] = sResultarray1[e - c];
}
break;
}
}
My current output is
++ST110+WP001.CB001
++ST120+WP001.CB001
++ST120+WP002.CB001
++ST130+WP001.CB001
++ST110+WP001.CB001
++ST120+WP001.CB001
++ST120+WP002.CB001
++ST130+WP001.CB001
My desired output is
++ST110+WP001.CB001
++ST110+WP001.CB001
++ST120+WP001.CB001
++ST120+WP001.CB001
++ST120+WP002.CB001
++ST120+WP002.CB001
++ST130+WP001.CB001
++ST130+WP001.CB001
Does anyone help me out to solve this problem?
I suggest using different collection type - List<string> instead of String[] (at least temporarily): Add, Insert ("shift and add") are not operations array has been designed for. Something like this:
using System.Linq;
...
// Temporal collection - list
List<string> list = sResultarray1.ToList();
// Downward - we don't want to check the inserted item
for (int r = list.Count - 1; r >= 0; --r) {
if (list[r] != null && list[r].Contains("WP") && list[r].Contains("CB")) {
// if you want to insert - "shift and add duplicate value" - just insert
list.Insert(r + 1, list[r]);
}
}
// back to the array
sResultarray1 = list.ToArray();
So I've been woking a Console game for a while now and I desided to use .txt files to hold the maps. This code opens and stores the txt file contents:
static void LoadMap(string fname)
{
string _org = File.ReadAllText("Maps/" + fname + ".txt");
_org.Split(',');
string[] _tmp = new string[_org.Length];
for (int i=0;i<_org.Length;i++)
{
_tmp[i] = _org[i].ToString();
}
//This line has the error
for (int i=0;_tmp[i]!="$";i+=2)
{
mapwidth += 1;
}
for (int i=0;i<_tmp.Length;i++)
{
leveldata.Add(_tmp[i]);
}
}
I get this error: Index was outside the bounds of the array. I can't figgure out why. Can anyone help? Thanks
Check that variable i does not take values beyond the Length - 1 of the array.
static void LoadMap(string fname)
{
string _org = File.ReadAllText("Maps/" + fname + ".txt");
_org.Split(',');
string[] _tmp = new string[_org.Length];
for (int i = 0;i < _org.Length; i++)
{
_tmp[i] = _org[i].ToString();
}
for (int i = 0;i < _tmp.Length && _tmp[i] != "$"; i += 2)
{
mapwidth += 1;
}
for (int i = 0;i < _tmp.Length; i++)
{
leveldata.Add(_tmp[i]);
}
}
I am not super sure what you are getting at here but I feel a foreach may be a step in the right direction.
First, here are a few things I noticed in the code you presented.
string _org = File.ReadAllText("Maps/" + fname + ".txt");
_org.Split(',');
Here you have ingested your text file and split _org with a comma delimiter. Though you never actually assigned the split array to a variable. _org is still a string, not a string[].
string[] _tmp = new string[_org.Length];
for (int i = 0; i < _org.Length; i++)
{
_tmp[i] = _org[i].ToString();
}
In this block we have set _tmp as a string array using the length of _org. The Length property in this case will retrieve the number of characters in the string _org. assuming _org is set to "foo" the size of the _tmparray is now 3. (0,1,2)
You then go on to load _tmp with the nth character of _org converted to a string.
At this point we have the following in our variables.
_org = "foo"
_tmp = {"f","o","o"}
This next part caught me a bit off guard as I cant tell for certain what you are trying to accomplish.
for (int i = 0; _tmp[i] != "$"; i += 2)
{
mapwidth += 1;
}
You are in a for loop until _tmp[i] equals "$", and you are adding 2 to i every time you move through the loop using i += 2. This logic will break the loop until it hits a "$", or if i grows outside of the bounds of the array it will throw an exception.
You then go on to add one to the mapwidth for every two increments of i
In this final block you are adding the contents of the _tmp array to leveldata
for (int i = 0; i < _tmp.Length; i++)
{
leveldata.Add(_tmp[i]);
}
Now for the good stuff, foreach.
I have made the assumption you wanted to set _org as an array, and that you wanted everything that was not a "$". That in mind, this should accomplish what you were going for, though I am not sure the purpose of incrementing by 2 in the second for loop so I have left that out for now.
static void LoadMap(string fname)
{
string[] _org = File.ReadAllText("Maps/" + fname + ".txt").Split(',');
foreach (var _tmp in _org)
{
if (_tmp != "$")
{
mapwidth += 1;
}
leveldata.Add(_tmp);
}
}
If you want to continue coding it is always a good idea to get a good grasp on the basics.
Though a bit dated here is a good tutorial by Microsoft for programming basics in C#:
C# Programmer's Reference
Try this link.
https://www.programiz.com/csharp-programming/foreach-loop
Have suggestion keyword to avoid Index was outside the bounds of the array error.
Sample code.
for(int i = 0; i < myArray.Length; i++)
{
// Coding to Array for loop.
}
I'm very new to programming so apologies if this is a very obvious question. Ive searched online but not found an answer that quite fits yet.
I am writing a programme that interprets bytes from an index within a filestream. Once they have been converted into human readable dates/strings/ints etc I wanted to use a Winform to display the results in columns. Currently I using a listbox and just dispalying each entry seperated by columns but this feels lile a very clunky way of doing it.
Can someone please suggest how I might go about placing the results into a display that uses columns?
It's better to use a ListView than a ListBox in your case. Here's an example showing all words in a string in separate columns in a ListView:
Make sure following property is set to your ListView (here the Name is ColumnsListView):
ColumnsListView.View = View.Details;
This method takes a string, splits it by space and adds a column for each of the values:
private void SetListView(string input)
{
var values = input.Split(' ');
ColumnsListView.Columns.Add("Column1");
var item = new ListViewItem(values[0]);
for (var i = 1; i < values.Length; i++)
{
ColumnsListView.Columns.Add("Column" + (i+1));
item.SubItems.Add(new ListViewItem.ListViewSubItem { Text = values[i] });
}
ColumnsListView.Items.Add(item);
}
This can be done differently when using LinQ's Skip() method to add the item with subitems:
private void SetListView(string input)
{
var values = input.Split(' ');
for (var i = 0; i < values.Length; i++)
ColumnsListView.Columns.Add("Column" + (i + 1));
var item = new ListViewItem(values[0]);
item.SubItems.AddRange(values.Skip(1).ToArray());
ColumnsListView.Items.Add(item);
}
Update:
Here's an example in case you want to use a DataGridView:
private void SetDataGridView(string input)
{
var values = input.Split(' ');
for (var i = 0; i < values.Length; i++)
ColumnsDataGridView.Columns.Add("Column" + (i + 1), "Column" + (i + 1));
ColumnsDataGridView.Rows.Add(values);
}