Textbox to array declaration in C# windows form - c#

Hi I’m fairly new to c# programming so please bear with me. I’m currently working on a “simple” little program which allows the user to enter 25 values into the same text box and once this has been done I want to be able to display this 25 values in a list box as an array of 5 row by 5 column and I want to find out the largest number in the array.
private void button1_Click(object sender, EventArgs e)
{
int arrayrows = 5;
int arraycolomns = 5;
int[,] arraytimes;
arraytimes = new int[array rows, array columns];
// list_Matrix.Items.Add(tb_First.Text);
for (int i = 0; i != 5; i++)
{
for (int j = 0; j != 5; j++)
{
array times [i,j]= Convert. To Int32(Tb_First.Text);
list_Matrix.Items.Add(array times[i, j].To String());
}
}
}
This is what I've tried for displaying the array in a list box, but it isn't working. This also prevents me from moving to the next section of finding the largest number among them.

You can split your string using .Split(' ') (or any other character or string). This will give you a onedimensional array with 25 elements (if everything was entered). The trick to converting that into a twodimensional array or grid is to use integer division and modulo, the following code would to
String[] splitText = textBox.Text.Split(' '); //gets your 25-length 1D array
//make an empty grid with the right dimensions first
int[][] grid = new int[5][];
for (int i=0;i<5;i++) {
grid[i] = new int[5];
}
//save our highest value
int maxVal = 0;
//then fill this grid
for (int i=0;i<splitText.Length;i++){
int value = int.Parse(splitText[i]);
//i%5 gives us values from 0 to 4, which is our 'x-coordinate' in the grid
//i/5 uses integer division so its the same as Math.floor(i/5.0), giving us your 'y-coordinates'
grid[i%5][i/5] = value;
//check if this value is larger than the one that is currently the largest
if (value > maxVal)
{
maxVal = value;
}
}
This will fill the twodimensional grid array with the split textbox text, and if there are not enough values in the textbox it leaves a 0 in those cells.
At the end you will also have your maximum value.

Try the following (shows by printing the numbers as string). and assuming you enter the numbers in the following way,
'1,2,3,4...'
string[] nums=txtBox.Text.Split(',');
lstBox.Items.Clear();
int colCount=5;
int colIndex=0;
string line="";
foreach(string num in nums)
{
if(colIndex==colCount)
{
lstBox.Items.Add(line);
line="";
colIndex=0;
}
line+= line==""? num : " "+num;
colIndex+=1;
}
if(line!="")
lstBox.Items.Add(line);
Make sure to correct any syntax mistakes, and to change the parameter names to yours.

private void button1_Click(object sender, EventArgs e)
{
int[] ab=new int[10];
string s = textBox1.Text;
int j = 0;
string [] a = (s.Split(' '));
foreach (string word in a)
{
ab[j] = Convert.ToInt32(word);
j++;
}
for (int i = 0; i < 10; i++)
{
label2.Text +=ab[i].ToString()+" ";
}
}

Related

Get the biggest value of an array

I have a textbox to write the position of an array and a textbox to write the value of that position. Every time I want to add a value and a position I click the button btnStoreValue
I created a function (CompareTwoNumbers) for another exercise that compares two numbers and returns the biggest
Using that function and avoiding the use of comparison characters like > and < I'm supposed to get the biggest value of the array
public partial class Form1 : ExerciseArray
{
int[] numbers = new int[10];
private int CompareTwoNumbers(int i, int j)
{
if (i < j)
{
return j;
}
return i;
}
private void btnBiggestValue_Click(object sender, EventArgs e)
{
//int n=1;
int counter = 0;
int highestPosition = CompareTwoNumbers(0, 1);
for(int i=0; i<10; i++){
//int j = CompareTwoNumbers(numbers[i], numbers[i+1])
//n = CompareTwoNumbers(numbers[n], numbers[i+1]
counter = CompareTwoNumbers(highestPosition, i);
}
txtBiggestValuePosition.Text= n.ToString();
txtBiggestValue.Text=numbers[n].ToString();
}
I've tried multiple things, using multiple variables, I tried to write it on paper to try to understand things better and I'm stuck. I don't know how is it possible to find that value using the function I created on the previous exercise (assuming the function I created is correct)
So, the core part of your question is that you want to know how to find the biggest number in an array using your helper function CompareTwoNumbers and then figure out what the value and position of the biggest number is.
Based on my understanding above, you have the framework almost set up correctly.
First off, CompareTwoNumbers should be updated to return a bool. Doing this will let you conditionally update your variables holding the biggest number value and position.
private int CompareTwoNumbers(int i, int j)
{
if (i < j)
{
return true;
}
return false;
}
To know what the largest value in an (unsorted) array is, you will need to iterate through every value. While doing so, you need to keep track of the value and position of the biggest value, only updating it when a bigger value is found.
private void btnBiggestValue_Click(object sender, EventArgs e)
{
// Store the bigget number's index and value
// We start with the first index and corresponding
// value to give us a starting point.
int biggestNumberIndex = 0;
int biggestNumber = numbers[0];
// Iterate through the array of numbers to find
// the biggest number and its index
for(int i=0; i<10; i++)
{
// If the current number is larger than the
// currently stored biggest number...
if(CompareTwoNumbers(biggestNumber, numbers[i])
{
// ...then update the value and index with
// the new biggest number.
biggestNumber = number[i];
biggestNumberIndex = i;
}
}
// Finally, update the text fields with
// the correct biggest value and biggest
// value position.
txtBiggestValuePosition.Text= biggestNumberIndex.ToString();
txtBiggestValue.Text=numbers[biggestNumberIndex].ToString();
}
This uses a Tuple to give you both the max index and max value from the same method:
public (int, int) FindMaxValue(int[] items)
{
int maxValue = items[0];
int maxIndex = 0;
for(int i=1;i<items.Length;i++)
{
if (items[i] > maxValue)
{
maxValue = items[i];
maxIndex = i;
}
}
return (maxIndex, maxValue);
}

Reading a file and storing in 2d array on Form Load

I'm designing a simple Epos system as a project and I need to read my stock values in from a file at the beginning of the application in the form of a collection so I am trying to use a 2d int array but not having much luck.
The format of my txt file looks like this:
15,10,12,19,8
16,9,11,17,10
7,6,17,14,11
8,8,12,13,5
6,7,13,14,4
1,4,15,10,10
6,9,10,14,13
8,7,9,10,11
8,12,10,15,6
9,7,6,13,9
18,8,7,11,5
7,12,10,8,9
12,6,7,9,10
My code is as follows :
private void ReadToFileOpeningStock(int [,] Stock)
{
//create an array to hold data from file
string[] OneRowOfDataArray;
const int StockColumns = 13;
const int StockRows = 5;
int[,] STOCK_ITEMS = new int[StockColumns, StockRows];
try
{
// Declare a StreamReader variable.
StreamReader inputFile;
// Open the file and get a StreamReader object.
inputFile = File.OpenText("Opening StartingStock.txt");
while (!inputFile.EndOfStream)
{
OneRowOfDataArray = inputFile.ReadLine().Split(',');
for (int i = 0; i < StockColumns; i++)
{
//Here are the inner columns
for (int j = 0; j < StockRows; j++)
{
}
}
}
inputFile.Close();
}
catch
{
MessageBox.Show("Error");
}
I also have an empty array named Stock declared with the rest of thevariables that I have declared in the method name above.
int[,] Stock ;
How do I assign my text values to an array so that I can use it later in the application?
Sorry if I'm not being clear, I'm new to programming. Any help would be greatly appreciated. Thanks.
I changed it to use file.readallines as it is what I normally use. I've added an extra array to record all the lines, to then be separated with a split into OneRowOfDataArray.
I added outputs and the line to set the value to the STOCK_ITEMS. The only other thing I changed is I removed the spaces in between the rows on the txt file
static int[,] STOCK_ITEMS = new int[4, 3];
static void Main(string[] args)
{
//create an array to hold data from file
string[] RowsOfData;//contains rows of data
string[] OneRowOfDataArray;//will contain values seperated by the rows
const int StockColumns = 13;
const int StockRows = 5;
int[,] STOCK_ITEMS = new int[StockColumns, StockRows];
try
{
// Open the file and get a StreamReader object.
RowsOfData = File.ReadAllLines("Opening StartingStock.txt");//sets all lines and seperates them into ROWSOFDATA array
for (int i = 0; i < StockColumns; i++)
{
OneRowOfDataArray = RowsOfData[i].Split(',');//splits the values in each row seperate
Console.WriteLine();//new line when outputting the data
//Here are the inner columns
for (int j = 0; j < StockRows; j++)
{
STOCK_ITEMS[i, j] = Int32.Parse(OneRowOfDataArray[j]);//save to correct index in stock items
Console.Write("[" + STOCK_ITEMS[i, j] + "]");//output value from the row
}
}
}
catch
{
MessageBox.Show("Error");
}
}
txt file
15,10,12,19,8
16,9,11,17,10
7,6,17,14,11
8,8,12,13,5
6,7,13,14,4
1,4,15,10,10
6,9,10,14,13
8,7,9,10,11
8,12,10,15,6
9,7,6,13,9
18,8,7,11,5
7,12,10,8,9
12,6,7,9,10

C# Checking if there is same random value in the array or not

I want to check if there is same value in the array or not as I mentioned in the title. And if there is, I want to pass that value and check another random value to add to listbox.
In my form, there is 2 textBox, 1 listbox and 1 button. When button is clicked, listbox has to show random numbers up to sum of textbox1 and textbox2. For instance;
5 entered from textbox1 and 10 entered from textbox2. Sum is of course 15 and listbox has to show 15 random numbers but those numbers have to be different from each other.
I wrote something like that and used Contains method to check if there is same value or not. But the program froze and didn't give any error.
int a, b;
Random rnd = new Random();
int[] array;
private void button1_Click(object sender, EventArgs e)
{
a = Convert.ToInt32(textBox1.Text);
b = Convert.ToInt32(textBox2.Text);
int c = a + b;
array = new int[c];
for (int i = 0; i < array.Length; i++)
{
int number = rnd.Next(c);
foreach(int numbers in array)
{
if (array.Contains(numbers))
{
i--;
}
else
{
array[i] = number;
listBox1.Items.Add(array[i]);
}
}
}
I also did it without foreach(Only Contains part I mean). Also didn't work. I wrote in "else";
array[i] += number;
it also didn't work.
I would be very appreciated if you help me. Thanks in advance.
instead of a for loop, use a while loop:
int = 0;
while(i<c)
{
int random rnd.Next(c);
if(!array.Contains(random))
array[i++] = random;
}
you may also create a list of numbers from 1-15 and then shuffle them (as your random function will create only random numbers from 1-15 just random):
array = Enumberable.Range(0,c).OrderBy(x => rnd.Next()).ToArray();
The above code is much faster, because imagine that we have generated 14 random numbers and only one number (5 for instance) left, it has to go through loop several times so that finally random number that is generated equals to 5, but in the above code there is no need to check that, we just have all numbers and then we shuffle it.
You can try to use do...while instead of for loop
Random.Next get the value from 0 to c - 1, so rnd.Next(c + 1); need to add 1 otherwise, the loop will not be stopped.
var array = new int[c];
int number;
for (int i = 0; i < array.Length; i++)
{
do
{
number = rnd.Next(c + 1);
} while (array.Contains(number));
array[i] = number;
listBox1.Items.Add(array[i]);
}
You basically need to shuffle your data. Create a collection with all values:
var temp = Enumerable.Range(0, c);
Now order it by random
temp = temp.OrderBy(_ => rnd.Next());
Now you can add temp to your listBox
Or, as single line:
listBox1.Items.AddRange(Enumerable.Range(0, c).OrderBy(_ => rnd.Next()));

passing arrays in c#

Hi i am working on Grade Calculation. My problem here is if the length of string array is longer that int array it works skipping the last 2 grades.
ex:
int[] unit = new int[] {1,-3,3,4};
string[] letter_grade = new string[] {"A", "B","B","W","D","F"};
but if length of int array longer than that of string array its not working its throwing error Index was outside the bounds of the array.
int[] unit = new int[] {1,-3,3,4,5,6,7};
string[] letter_grade = new string[] {"A", "B","B"};
so my question how do i make it work for both??
int length = unit.Length;
int no_units = length;
double totalGrade_Points = 0.0;
int totalno_units = 0;
totalGPA = 0;
for (int i = 0; i < unit.Length; i++)
{
entrygot = findGpaListentry(letter_grade[i]); //Index was outside the bounds of the array.
if (entrygot != null)
{
//some code calculation
}
}
For array indexing you must have starting and stopping condition defined very well. For accessing two arrays either they must be equal or they are compared under certain valid conditions. Have a look at this:
for(int i=0;i<unit.length;i++){
entrygot = findGpaListentry(letter_grade[i]);// only if letter_grade is valid under all values of i i.e unit.length
}
// either you have to check as if;
if(lenght_of_letter_grade < i-1)
//then access
entrygot = findGpaListentry(letter_grade[i]);
You can't just check if the array item is null, because you would be out of the bounds of the array and you will get an exception before the null check occurs.
I would check the length of the array on each iteration...
for (int i = 0; i < unit.Length; i++)
{
if (currentArray.Length < i - 1) { break; }
// other code...
}
I think in your case, the number of elements will never be large hence performance wont be an issue. So I think you should be using a List instead of an array. With an array you will have to be insert checks each time some logic changes or you add other functionalities.
foreach loop is best for your scenerio.
foreach (string s in letter_grade)
{
entrygot = findGpaListentry(s);
if (entrygot != null)
{
//some code calculation
}
}

How to implement C# code for Order id separated by commas and range separated by hyphens, and display all info of order

Ex: 1,4-90, 292,123
It needs to display the whole order information of
1
4,5,6....90
292
123.
Whats the gud approach to solve this.
It is similar to tracking in UPS or fedex if multiple orders are given in search box.
I meant if in a search box I giv 1,4-90, 292,123 this string the result that needs to come back is a grid representation of all the data which is corresponding to each of the order id respectively. I want to know how to parse the string into collection and send them to the database and show the information in the grid for...
1
4,5,6....90
292
123.
as a different row...from where I can generate reports too (alternative)
Please try.
static ArrayList list;
static void Main(string[] args)
{
string str = "1,4-90,292,123";
string[] arr = str.Split(',');
list = new ArrayList();
for (int i = 0; i < arr.Length; i++)
{
string tmp = arr[i];
if (tmp.IndexOf('-') != -1)
{
Range(tmp);
}
else list.Add(int.Parse(tmp));
}
list.Sort();
object[] intResult = list.ToArray();
//print the final result
for (int i = 0; i < intResult.Length; i++)
{
Console.WriteLine(intResult[i].ToString());
}
Console.Read();
}
static void Range(string range)
{
string[] tmpArr = range.Split('-');
int stInt = int.Parse(tmpArr[0]);
int edInt = int.Parse(tmpArr[1]);
int[] intArr = new int[(edInt - stInt) + 1];
for (int i = 0; stInt <= edInt; i++)
{
list.Add(stInt++);
}
}

Categories

Resources