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
Related
I am trying to make savegame for a quite simple game, and this is the code I am using right now to write money to a .txt file (NameBox is the textbox you use to write the name of the .txt file):
private void SaveBtn_Click(object sender, EventArgs e)
{
String filename = NameBox.Text;
if (filename == "")
{
filename = "New Save";
}
filename += ".txt";
String[] Money = new String[MainForm.Money];
Money[MainForm.Money] = MainForm.Money.ToString();
System.IO.File.WriteAllLines(filename, Money);
Application.Exit();
}
However I get an index out of bounds error on whatever line is after
Money[MainForm.Money] = MainForm.Money.ToString();
I've also tried doing this:
for (int i = 0; i < MainForm.Money; i++){
Money[MainForm.Money] = MainForm.Money.ToString();
}
But it gives me an error on the closing body (squiggly bracket as I call it)
I have done a savegame before with an array of walls and soldiers saving their sizes and locations using this code (wallList[i].ToString() refers to a method in the wall class that returns all the values):
private void SaveBtn_Click(object sender, EventArgs e)
{
String filename = filenametxt.Text;
if (filename == "")
{
filename = "Level";
}
filename += ".txt";
String[] lines = new String[MainForm.wallList.Count +
MainForm.soldierList.Count+1];
for (int i = 0; i < MainForm.wallList.Count; i++)
{
lines[i] = MainForm.wallList[i].ToString();
}
lines[MainForm.wallList.Count] = "#";
for (int i = 0; i < MainForm.soldierList.Count; i++)
{
lines[i + MainForm.wallList.Count +1] =
MainForm.soldierList[i].ToString();
}
System.IO.File.WriteAllLines(filename, lines);
Application.Exit();
}
I would very much appreciate if someone could help me! (Please explain to me what each part of the code means, for example explaining that .ToString() converts an int into a string)
String[] Money = new String[MainForm.Money];
Here you create the array of size MainForm.Money. Say the value of MainForm.Money is 10.
The array is size 10, meaning there are 10 slots. These are numbered 0-9.
Money[MainForm.Money] = MainForm.Money.ToString();
Here you do the equivalent of Money[10] when it only has slots up to 9. Thus you go "Out of Bounds" of the array.
In short:
Arrays are 0-based so this array access is the problem:
Money[MainForm.Money] = ... // MainForm.Money-1 would be okay
In more detail:
So we have these two lines causing your problem:
String[] Money = new String[MainForm.Money];
Money[MainForm.Money] = MainForm.Money.ToString();
Assuming that MoneyForm.Money is an int - let's pretend it is 5000:
In this case you are creating a string array Money with 5000 empty slots to store strings in.
In the second line you basically say that you want to write that 5000 as string (so "5000") in the array's 5000th element.
Money[5000] = "5000";
But when you declare an array with 5000 "slots" you have them from 0-4999 because arrays are 0-based. That's why 5000 is "out of bounds".
It appears that you are initializing an array with the length of Mainform.Money that starts at 0 up to Mainform.Money - 1, but when you try to set the value of Money[Mainform.Money], you are setting that value outside the defined array.
Since you are populating the string array Money with length equal to the value of MainForm.Money the maximum possible index for the array is equal to MainForm.Money -1 not MainForm.Money:
Money[MainForm.Money] = MainForm.Money.ToString();
// you should change the index here to be within the range (0 - MainForm.Money -1) based on your requirements
In the line below, you initialized the Money to have be an array of x amount of
strings (x = MainForm.Money).
Then you tried to access item x + 1 from the line below, which caused the exception. If you want to access the last element of the array, you should call Money[MainForm.Money - 1].
Money[MainForm.Money] = MainForm.Money.ToString();
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've only been working with Arrays for a short while, and Im finding them much harder than working with Lists. For an assignment I have written a form with takes an input from a textbox and outputs a count,average, and total. The code is as follows:
int [] intScoreTotalArray = new int[20];
decimal decScoreAverage = 0m;
decimal decScoreTotal = 0m;
decimal decScoreCount = 0m;
private void btnAdd_Click(object sender, EventArgs e)
{
intScoreTotalArray[0] = Convert.ToInt32(txtScore.Text);
for(int i = 0; i < intScoreTotalArray.Length; i++)
{
decScoreTotal += intScoreTotalArray[i];
}
decScoreCount++;
decScoreAverage = decScoreTotal / decScoreCount;
But I also need to display it in a message box in a stong, and it only gives me the last value. My theory is that the problem lies in both boxes of code, or in the intial for loop.
private void btnDisplayScores_Click(object sender, EventArgs e)
{
decimal decScore = Convert.ToDecimal(txtScore.Text);
string strScoreTotal = " ";
for (int i = 0; i < intScoreTotalArray[i]; i++)
{
strScoreTotal += decScore.ToString() + "\n";
}
Array.Sort(intScoreTotalArray);
MessageBox.Show(strScoreTotal + "\n","Score Array");
Advice?
Why are you using an array to determine the count, average and total of a list of numbers? They aren't the best structure for a dynamic list of items as you have to declare an array's size when you initialize it. You SHOULD be using a list for this task.
As to why your code isn't behaving:
intScoreTotalArray[0] = Convert.ToInt32(txtScore.Text);
You are only assigning the first item in the array here.
It looks like you are using decScoreCount to keep track of the number of items in your array. I think you want to do this:
intScoreTotalArray[(int) decScoreCount] = Convert.ToInt32(txtScore.Text);
I have this form application project. I upload a snap of the sales field. Two datagridview are there. Bottom datagirdview contain TAX details. Contain of bottom datagrid came from database except “Amount” column. Amount column value provided by user or auto calculated. I write a code. When I try to execute it shows a error. Index was out of range. Must be non-negative and less than the size of the collection.Parameter name: index. How Can I solve it??
Snap::
Here is the code:
private void dgvSalesFooterAdd_CellStateChanged(object sender, DataGridViewCellStateChangedEventArgs e)
{
decimal Total = 0;
decimal a=Convert.ToDecimal(lblTotalAdd.Text);
for (int i = 0; i <dgvSalesFooterAdd.Rows.Count ; i++)
{
dgvSalesFooterAdd.Rows[i].Cells[4].Value = a + (a * (Convert.ToDecimal(dgvSalesFooterAdd.Rows[i].Cells[3].Value)/100));
Total += Convert.ToDecimal(dgvSalesFooterAdd.Rows[i].Cells[4].Value);
}
lblFinalTotalAdd.Text = Total.ToString();
}
[NOTE: Error on
dgvSalesFooterAdd.Rows[i].Cells[4].Value = a + (a * (Convert.ToDecimal(dgvSalesFooterAdd.Rows[i].Cells[3].Value)/100));
Total += Convert.ToDecimal(dgvSalesFooterAdd.Rows[i].Cells[4].Value);
this two lins.]
dgvSalesFooterAdd.Rows[i].Cells[4].Value = a + (a *(Convert.ToDecimal(dgvSalesFooterAdd.Rows[i].Cells[3].Value)/100));
Total += Convert.ToDecimal(dgvSalesFooterAdd.Rows[i].Cells[4].Value);
it will throw an exception because you are reading the value of 4th column which is null, because cell_value changed worked once you leave the cell...
got throught this link it will give you a better picture..
http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.cellvaluechanged.aspx
and try you code like this..
void dgvSalesFooterAdd_CurrentCellDirtyStateChanged(object sender,
EventArgs e)
{
if (dgvSalesFooterAdd.IsCurrentCellDirty)
{
dgvSalesFooterAdd.CommitEdit(DataGridViewDataErrorContexts.Commit);
}
}
private void dgvSalesFooterAdd_CellStateChanged(object sender, DataGridViewCellStateChangedEventArgs e)
{
decimal Total = 0;
decimal a=Convert.ToDecimal(lblTotalAdd.Text);
for (int i = 0; i <dgvSalesFooterAdd.Rows.Count ; i++)
{
dgvSalesFooterAdd.Rows[i].Cells[4].Value = a + (a * (Convert.ToDecimal(dgvSalesFooterAdd.Rows[i].Cells[3].Value)/100));
Total += Convert.ToDecimal(dgvSalesFooterAdd.Rows[i].Cells[4].Value);
}
lblFinalTotalAdd.Text = Total.ToString();
}
The exception is thrown when it does not find the Row index in i. You will have to reduce the number of rows by 1. This will tell the loop to count only the rows filled by values. Change the line
int i = 0; i <dgvSalesFooterAdd.Rows.Count
to
int i = 0; i <dgvSalesFooterAdd.Rows.Count - 1
Complete block will look like this;
for (int i = 0; i <dgvSalesFooterAdd.Rows.Count - 1; i++)
{
dgvSalesFooterAdd.Rows[i].Cells[4].Value = a + (a * (Convert.ToDecimal(dgvSalesFooterAdd.Rows[i].Cells[3].Value)/100));
Total += Convert.ToDecimal(dgvSalesFooterAdd.Rows[i].Cells[4].Value);
}