I have this code
for (short i = 100; i >= 1; i--)
{OutputFormattedXmlElement("test", i.ToString());}
i am using the "test" to populate a dropdownlist
<select id="list><xsl:apply-templates select="/sales/test">...
My problem is that in the dropdownlist it shows the 1 as the default (correct) but it is at the bottom of the list and i want it at the top.
Where do i have to make a change? Is there any other way except javascript?
Thanks in advance!
You're looping from 100 down to 1, meaning that 100 is the first item and 1 is the last. It would seem to me that reversing the loop might give you better results.
Can you just reverse your for loop?
for (short i = 1; i <= 100; i++)
{OutputFormattedXmlElement("test", i.ToString());}
For your situation, is it valid to simply flip the for loop?
for (short i = 1; i <= 100; i++)
...
Related
Why doesnt this for loop work while the while loop does
for (int i = 0; i > 10; i++)
{
Console.WriteLine(i);
}
int j = 1;
while(j != 11)
{
Console.WriteLine(j);
j++;
}
It's easy to mix up comparers. A good way to remember for me is the heart. <3 because I know that's read as "Less than three".
It's easy to get confused when starting out, you just mixed up the condition.
As of why your for does not work is because it starts with i = 0 then checks if if 0 is greater than 10 which is not that's why it will not excute the loop body and terminates the loop.
In your while loop, initially j = 1 then while checks if 1 is not equal to 11, which is true so loop body will execute until j is not equal to 11.
I have a list of roughly 50~60 items that I want to be able to divide into multiple columns dynamically. I'm using a nested for loop and the lists divide properly when there are an even number of items. However, when there are an odd number of items the remainder (modulus) items get left out. I've been playing around with it for a while and have not struck gold yet. I'm hoping someone smarter than me can & will assist.
Thanks.
for (int fillRow = 0; fillRow < numOfCols; fillRow++)
{
for (int fillCell = 0; fillCell < (siteTitles.Count / numOfCols); fillCell++)
{
linkAddress = new HyperLink();
linkAddress.Text = tempSites[fillCell].ToString();
linkAddress.NavigateUrl = tempUrls[fillCell].ToString();
mainTbl.Rows[fillCell].Cells[fillRow].Controls.Add(linkAddress);
}
}
Well yes, the problem is here:
fillCell < (siteTitles.Count / numOfCols)
That division will round down, so for example if there are 13 titles and numOfCols is 5, it will give 2 - which means that items 10-12 won't be used.
I suggest that actually you loop over all the items instead, and work out the row and column for each item:
for (int i = 0; i < siteTitles.Count; i++)
{
int row = i / numOfCols;
int col = i % numOfCols;
// Fill in things using row, col and i
}
(It's not exactly clear what you're doing as you're using siteTitles in the loop condition and tempSites in the loop body, and you're not using fillRow when extracting the data... basically I think you've still got some bugs...)
I am trying to get my loop to stop when i is equal to the loopEnd variable. Here is the code:
for (int i = loopStart; i < loopEnd; i++)
At the moment it stops when i is greater than loopEnd, but the program won't run if I replace < with =, and it won't work if I use ==.
No, currently it will stop when i is equal to loopEnd (because then i is not less than loopEnd). If you want it only stop when i is greater than loopEnd, use <= instead:
for (int i = loopStart; i <= loopEnd; i++)
Note that this approach has problems if loopEnd is int.MaxValue - you'll loop forever, because when i is incremented, it will become int.MinValue which is again less than loopEnd (unless you're in a checked context, in which case an exception will be thrown).
This may well not be an issue for you, but it's worth being aware of.
for (int i = loopStart; i <= loopEnd; i++)
//^ apply less or equal operator
for (int i = loopStart; i <= loopEnd; i++)
Is that what you want?
Use <= with loopEnd in your loop. Like;
for (int i = loopStart; i <= loopEnd; i++)
Use i != loopEnd. This condition indicates when to enter the loop, rather than when to stop entering.
As Chris mentions in his comment, it's mostly better to use <=, as you might increment i within the body and skip loopEnd.
My current code:
Remove()
{
for (int i = 0; i < ConGridView.RowCount; i++)
{
if (ConGridView.Rows[i].Cells[0].Value.ToString() == Address)
{
ConGridView.Rows.RemoveAt(i);
break;
}
}
}
So what I am trying to call the remove function every time a client disconnect. the function will remove the connection address from the datagridview. It works well when clients are disconnection one by one. However, if 100 connections gets dropped and it tries to remove 100 connections in less than a second, than it errors out saying "Row Index provided is out of range". How should I check for that ?
So far I've tried:
Try, catch.
if (ConGridView.Rows[i] != null), if (i < ConGridView.RowCount)
None of it seem to work so far. I've also got results using (i < ConGridView.RowCount) where i is 26 while RowCount is 24, but the remove at function still activates..
Any idea on this ?
You can't do this. Your code loops through all the rows in ConGridView, but it deletes them as you do. Therefore, at some point you will try to access an item you have deleted, which will cause the error you described.
Probably the best approach it to iterate through the rows in reverse order. This way, deleting a row at the end won't affect when you access rows at the start.
The problem is you initialise your for loop with the current count of rows and then start removing those same rows from the datagridview. At some point your for loop will try to remove a row at an index that is greater than the number of rows left.
Try this instead:
for (int i = ConGridView.RowCount - 1; i >= 0; i--)
{
if (ConGridView.Rows[i].Cells[0].Value.ToString() == Address)
{
ConGridView.Rows.RemoveAt(i);
break;
}
}
why dont you get the total count to a separate variable and then iterate
Remove()
{
int totalConnections = ConGridView.RowCount;
for (int i = 0; i < totalConnections ; i++)
{
if (ConGridView.Rows[i].Cells[0].Value.ToString() == Address)
{
ConGridView.Rows.RemoveAt(i);
break;
}
}
}
This issue is becuase you are modifying the collection your are iterating over. It will be better if you use a temporary array and two loops to remove your entries.
Remove()
// You can use an array/list or whatever you want below.
Collection<DataGridViewRow> rowsToDelete = new Collection<DataGridViewRow>();
for (int i = 0; i < ConGridView.RowCount; i++)
{
if (ConGridView.Rows[i].Cells[0].Value.ToString() == Address)
{
rowsToDelete.Add(ConGridView.Rows[i]);
break;
}
}
// now remove the marked entries.
foreach(DataGridViewRow deletedRow in rowsToDelete)
{
ConGridView.Rows.Remove(deletedRow);
}
When you remove an item from an array, it is reconstructed; shifting the remaining elements up by one to remove the gap of the index you have removed.
1. guybrush threepwood
2. murray
3. elaine
4. Jimmy Gibbs Jr.
If you remove 2. item in here; it becomes this:
1. guybrush threepwood
2. elaine
3. Jimmy Gibbs Jr.
When you are iterating, imagine:
for (int i = 0; i < myArray.Count; i++)
{
if (i == 2) myArray.RemoveAt(i);
}
While running this, when i = 3, the element at 3 has changed, you expect it to be 'elaine' but it is 'Jimmy Gibbs Jr.'. One way to fix this is decrease i by one if we delete it, making sure that i refers to correct value.
for (int i = 0; i < myArray.Count; i++)
{
if (i == 2)
{
myArray.RemoveAt(i);
i--;
}
}
I would go for LINQ in this case, though, everything is easier with that.
myArray.RemoveAll(x => x == "murray");
I've tried all the suggestions posted by everyone here, however, the error was still there.
I've solved the problem using a different way... I've switched to TreeNodeView since that's what I was going to use ultimately. Now I can remove as many connection as i want with:
For each(TreeNode TN in ConTreeView)
{
ConTreeView.Nodes.Remove(TN);
}
I'm writing code in C# and trying to add all of the numbers between the number 1 and N, N being the number that is inputted in a textbox. I'm doing this, at least trying to do this, by putting it into a while loop.
I have added all the numbers between 2 textboxes before but for some reason I'm driving myself crazy and can't figure this out. I'm a beginning programmer so please be gentle.
Any help would be greatly appreciated.
Edit:
One of the six thousand things I've tried. I think this has me in an infinite loop?
private void btnAddAll_Click(object sender, EventArgs e)
{
int n;
int count = 0;
int answer = 0;
n = int.Parse(txtNum.Text);
count = n;
while (count >= 1)
{
answer = answer + count;
count++;
}
lstShow.Items.Add("Sum = " + answer);
lstShow.Text = answer.ToString();
}
Why not use Gauss formula. (N*(N+1))/2
private void btnAddAll_Click(object sender, EventArgs e)
{
int n, answer;
n = int.Parse(txtNum.Text);
answer = (n*(n+1))/2;
lstShow.Items.Add("Sum = " + answer);
lstShow.Text = answer.ToString();
}
If you change the ++ to a -- it should work as you want it to.
int n;
int count = 0;
int answer = 0;
n = 3;
count = n;
while (count >= 1)
{
answer = answer + count;
count--; // here was the error
}
Console.WriteLine (answer);
Output: 6
Also, just for a point of additional interest you can use That uses Enumerable.Range and Enumerable.Sum instead of the while loop (probably goes beyond what is expected for a homework but it's useful to know what's out there).
answer = Enumerable.Range(1, n).Sum();
Your edit: you should decrement count..
Another edit, it appears I need to explain more:
By decrement I mean --. The post or pre decrement operator decreases the value by 1.
If count keeps increasing by 1, count >=1 will never be met. You need to reduce count to 1.. hence count--;
Also I suggest you use TryParse(string,out int) ; or at least wrap the Parse call in a try catch block.
Here is a pointer in pseudocode:
GetInput From User
TryParse Input
If Between 1 and N
Declare sum = 1;
for i to N-1
sum+=i;
/* if you don't want to use the for loop
while i < N
sum+=i;
inc i; */
Print sum
Debugging is an important skill for any programmer. There are some good tools in Visual Studio to help with debugging.
A good way to debug your code when you are stuck is to use 'breakpoints' and step through the code.
Select the line you want your code to stop at (e.g. n = int.Parse(txtNum.Text);) and press F9 - this will add a breakpoint at this line.
Now, when you run your programme, it will stop at the breakpoint. If you press F11, you can 'step' through the code one line at a time. You can hold your mouse over a variable to see its value while you are doing this.
You will quickly find the problem in your code if you do this.