I cannot think of what i'm doing wrong here, the code is very simple, i'm trying to increment an intenger by +1 everytime a button is pressed, instead of doing for example: 5 + 1 which is 6, the label prints 51.
Code:
// update count here...
lblCount.Text = lblCount.Text + 1;
The label holds the initial value, i thought just adding what the label was currently then just doing +1 would be enough but it's not working as i thought.
any helpwould be appreciated.
Convert to int and then convert to String
var total = int.Parse(lblCount.Text) + 1;
lblCount.Text = total.ToString();
Yeah that is because output of label.Text is a String use it like this
int x = Int32.Parse(lblCount.Text);
Then add x + 1
This will increment when conversion is successful.
In C# 7 code:
if (int.TryParse(lblCount.Text, out int currentValue))
{
var result = currentValue + 1;
lblCount.Text = result.ToString();
};
if (int.TryParse(lblCount.Text, out int currentValue))
{
currentValue += currentValue 1;
lblCount.Text = currentValue.ToString();
};
lblCount.Text holds a text in it(better to say String) and now your are trying to make arithmatic calculation with integer.
It at first holds it's value and add the next value as a string(like concatination). To avoid this,
First you have to convert it to integer before adding the 1.
you do that like this lblCount.Text = int.Parse(lblCount.Text) + 1;
As you already notice your problem is that current value saved as a string. So you can not do mathematical operation on a string.
Instead of parsing string to integer every time you want add 1 - save current value in local variable of type integer and do all operations on this variable.
private int count;
// update count here...
count = count + 1;
lblCount.Text = count.ToString();
int counter;
public void Yourbutton_Click(object sender, EventArgs e)
{
counter + 1;
lblCount.Text =counter.ToString();
}
Related
Textbox2 has some 60 ids and i want to increase it to 250....
So i use following code increase the elements.
when i click the size button textbox2 should have 300 ids(now it has 60 only)..
lately i need to reduce it to 250 ids
. But it is getting exceptions
private void Size_Click(object sender, System.EventArgs e)
{
string[] vlist = textBox1.Text.Split('\n');
int size = (Convert.ToInt32(textBox2.Text)) / Convert.ToInt32(vlist) +1;
int p = Convert.ToInt32(textBox2.Text) * size;
textBox2.Text = p.ToString();
}
Please tell me what should i do in this?
private void Size_Click(object sender, System.EventArgs e)
{
List<string> vlist = new List<string>(textBox2.Text.Split('\n'));
int currentLineNumber = vlist.Count;
int targetLineNumber = Int32.Parse(textBox1.Text);
if (targetLineNumber == currentLineNumber)
return; //nothing to change
else if (targetLineNumber > currentLineNumber) //increase number of line
{
for (int i = currentLineNumber; i < targetLineNumber; ++i)
vlist.Add(vlist[(i - currentLineNumber) % currentLineNumber]);
}
else //reduce number of line
vlist = vlist.GetRange(0, targetLineNumber);
if (vlist.Count == 0)
textBox2.Text = String.Empty;
else
{
string result = vlist[0];
for (int i = 1; i < targetLineNumber; ++i)
result += String.Format("\n{0}", vlist[i]);
textBox2.Text = result;
}
}
The logic is quite simple. First, get number of line in textbox1 and target line number in textbox2. (This assume textbox1 is not empty though)
For increasing in size, we just keep adding id to the list until it reaches target size. For reducing size, it is even simpler, just take the first N lines from the list. After resizing, just reconnect all the lines together and set textBox1.Text to it.
You cannot change the array size.
If you want to have dynamic size you should use collections like List<T>
...
string[] vlist = textBox1.Text.Split('\n');
int size = (Convert.ToInt32(textBox2.Text)) / Convert.ToInt32(vlist.Length) +1;
string newString = "";
for(int i=0;i<size;i++){
newString = String.Join("\n",vlist);
textBox2.Text += newString + "\n";
}
...
This way, you append to the textbox the information you already got there (vlist), the number of times you need (size). I haven't tested it but probably this would repeat those IDs once more tan desired, in that case, remove the "+1" from the size variable definition
For the reduction to 250, you should specify which criteria are you following... if they are only the first 250, you could do that easily in a for loop with 250 as the break condition / top value
I have a ListForm in C#
The question is when a user clicks on a certain student in the list I want it to find the average, score count and sum.
Code Below:
private void listForm1_SelectedIndexChanged(object sender, EventArgs e)
{
txtTotal.Text = listForm1.SelectedItem.ToString();
}
private void Form1_Load(object sender, EventArgs e)
{
listForm1.Items.Add("Hamish overtonne" + "|" + 39 + "|" + 12 + "|" + 85);
listForm1.Items.Add("Claudia Dye" + "|" + 44 + "|" + 56 + "|" + 85);
listForm1.Items.Add("Mike Layne" + "|" + 12 + "|" + 47+ "|" + 28);
}
That's All I have for now
Here's the code you can use to do that. Just keep in mind to register a SelectedIndexChanged event to your list.
Also keep in mind that using integers, like I did, will create whole numbers, without decimal points.
I've added code comments to explain the process:
private void listForm1_SelectedIndexChanged(object sender, EventArgs e)
{
// Get the value from the selected item
string val = listForm1.GetItemText(listForm1.SelectedItem);
// Split the item's value to a string array according to the pipe char
string[] valArray = val.Split('|');
int sum = 0;
int scores = 0;
// Iterate through all possible values and sum it up,
// while keeping count to how many numbers there are:
for (int i = 1; i < valArray.Length; i++)
{
int num = Convert.ToInt32(valArray[i]);
sum += num;
scores++;
}
// Calculate the average.
// Keep in mind using an integer will create a whole number, without decimal points.
int average = sum / scores;
// Place the average and the sum in textboxes
txtAverage.Text = average.ToString();
txtTotal.Text = sum.ToString();
txtCount.Text = scores.ToString();
}
try below code :
private void listForm1_SelectedIndexChanged(object sender, EventArgs e)
{
// Get the value from the selected item
string val = listForm1.GetItemText(listForm1.SelectedItem);
// Split the item's value to a string array according to the pipe char
string[] valArray = val.Split('|');
int sum = 0;
int scores = 0;
int value=0;
// Iterate through all possible values and sum it up,
// while keeping count to how many numbers there are:
for (int i = 1; i < valArray.Length; i++)
{
int.TryParse(valArray[i], out value);
if(value>0){
int num = value;
sum += num;
scores++;
}
}
// Calculate the average.
// Keep in mind using an integer will create a whole number, without decimal points.
int average = sum / scores;
// Place the average and the sum in textboxes
txtAverage.Text = average.ToString();
txtTotal.Text = sum.ToString();
txtCount.Text = scores.ToString();
}
I'm making a simple program that computes the cube of the input number. I want to array the result from 1 up to the given number but I don't how to manipulate the label control.
Here's my coding:
int num = 0;
int cube;
string result;
private void input()
{
num = Convert.ToInt32(txtnum.Text);
}
Private void btncompute_Click(object sender, EventArgs e){
input();
int i = 0;
do
{
cube = num * num * num ;
i++;
result = i + " and cube of the " + i + " is :" + cube;
} while (i < num);
lbloutput.Text = result;
}
The only output here is the cube of the input number. I want to get the result from index 0 and display it on a label through array. For instance, for input 3, output should be something like this:
1 and the cube of the 1 is 1
...
3 and the cube of the 3 is 27
Your help will be greatly appreciated. Thank you.
A couple of things, the current logic won't give you what you want.
You want to multiply by i, not by num, for instance if num = 3, cube will always be 27. Based on your output you want all cubes up to and including your number.
You want to set i to 1 initially to start at 1, other you are starting at 0
You want to calculate the cube of num also, which means you have to change your loop to include num, thus i <= num
Change your code to the following:
int num = 0;
int cube;
string result = String.Empty;
private void input()
{
num = Convert.ToInt32(txtnum.Text);
}
private void btncompute_Click(object sender, EventArgs e)
{
input();
int i = 1;
do
{
cube = i* i* i;
result = result + String.Format("{0} and cube of the {0} is : {1}\r\n", i, cube);
i++;
}
while (i <= num);
lbloutput.Text = result.ToString();
}
The biggest part of your problem is that a label is not the appropriate control for displaying multiple lines of text. It doesn't size or scroll based on the size of the content. You would probably be better served with a multi-line text-box. You can make it read-only if you don't want it editable (like a label).
In that case, you would want to call
mytextBox.Clear()
before the loop to clear any existing text. And then after building your result string in the loop, call
mytextbox.AppendText(result);
to add the next iteration to the content.
Implementation left as an exercise for the reader ;)
I'm adding values from a file to an array and then adding those values to a list box in a form. I have methods performing calculations and everything is working great, but I'd like to be able to use a loop and insert the year prior to the values I am inserting into the list box. Is there a way to use the .Add method and include a variable which will be changing in this? Something like populationListbox.Items.Add(i, value); if i is my loop counter? Code is below so I'd like first line in the list box to have the year I specify with my counter, followed by the population. Like this, "1950 - 151868". As of now it only displays the value 151868. Thanks!
const int SIZE = 41;
int[] pops = new int[SIZE];
int index = 0;
int greatestChange;
int leastChange;
int greatestYear;
int leastYear;
double averageChange;
StreamReader inputFile;
inputFile = File.OpenText("USPopulation.txt");
while (!inputFile.EndOfStream && index < pops.Length)
{
pops[index] = int.Parse(inputFile.ReadLine());
index++;
}
inputFile.Close();
foreach (int value in pops)
{
**populationListbox.Items.Add(value);**
}
greatestChange = greatestIncrease(pops) * 1000;
leastChange = leastIncrease(pops) * 1000;
averageChange = averageIncrease(pops) * 1000;
greatestYear = greatestIncreaseyear(pops);
leastYear = leastIncreaseyear(pops);
greatestIncreaselabel.Text = greatestChange.ToString("N0");
leastIncreaselabel.Text = leastChange.ToString("N0");
averageChangelabel.Text = averageChange.ToString("N0");
greatestIncreaseyearlabel.Text = greatestYear.ToString();
leastIncreaseyearlabel.Text = leastYear.ToString();
Like this?
int i = 1950;
foreach (int value in pops)
{
populationListbox.Items.Add(i.ToString() + " - " + value);
i++;
}
Your life will be a lot easier if you stop trying to program C# as if it were 1980s C and use the power of it's Framework:
var pops = File.ReadLines("USPopulation.txt").Select(int.Parse);
populationListbox.Items.AddRange(pops.Select((p,i) => $"{i} - {p}"));
The code below belongs to a binary search algorithm. The user enters numbers in textbox1 and enters the number that he want to find with binarysearch in textbox2. When I enter for example 16 in textBox2 and put breakpoint on the line I commented, I see that the value of searchnum is 10.
I think it converts to hexadecimal. I don't know why. Can you help me?
private void button1_Click(object sender, EventArgs e)
{
string[] source = textBox1.Text.Split(',');
int[] nums = new int[source.Length];
for (int i = 0; i < source.Length; i++)
{
nums[i] = Convert.ToInt32(source[i]);
}
string str_searchnum = textBox2.Text;
int searchnum = Convert.ToInt32(str_searchnum); // str_searchnum shows the value 16 but searchnum shows 10
int first = 0;
int last = nums.Length - 1;
while (1 < nums.Length - 1)
{
int mid = (int)Math.Floor(first + last / 2.0);
////if (first < last)
////{
//// break;
////}
if (searchnum < nums[mid])
{
last = mid - 1;
}
if (searchnum > nums[mid])
{
first = mid + 1;
}
else
{
MessageBox.Show(nums[mid].ToString());
}
}
}
Check to see if the debugger is set to display values using hexadecimal notation? You can find this option by right clicking in the watch window.
If that's not it, step through the entire method. What is the value of str_searchnum?
Although I personally prefer int.TryParse(), Convert.ToInt32() should be well-tested and not be doing any base conversions.
Why not use Array.BinarySearch? Also, your loop condition is (probably) wrong.