Array values from textboxes - c#

I have a 16 element int array and 16 textboxes (textBox1, textBox2 ....) that look like 4x4 matrix. Is there any way to put textboxes values to every array element not using code like this:
array[1] = (int)textBox1.Text;
array[2] = (int)textBox2.Text;

One possibility would be to store the references to the TextBox instances in an array.
TextBox[] Boxes;
And then use a 'for' loop to populate the values.
for (int i = 0; i < 16; i++)
{
array[i] = (int)Boxes[i].Text;
}

You could use a function to get the text box's text as an integer using it's "index" from the form's control collection:
int GetBoxText(int index)
{
return Convert.ToInt32(this.Controls["textBox" + i.ToString()].Text);
}
Note that this has no error checking of any kind. You could add some if you wanted to. All this does is get the text of the control named textBox + whatever i is from the form's control collection and convert it to an integer.

IMHO the best way to design is by the way it's meant to be. In particular, rectangular/multidimensional arrays may be useful in this scenario:
public partial class Form1 : Form {
TextBox[,] textBoxes;
int[,] values;
public Form1() {
InitializeComponent();
textBoxes = new TextBox[4, 4];
values = new int[textBoxes.GetLength(0), textBoxes.GetLength(1)];
for(int r = 0; r < textBoxes.GetLength(0); r++) {
for(int c = 0; c < textBoxes.GetLength(1); c++) {
values[r, c] = int.Parse(textBoxes[r, c].Text);
}
}
}
}

Related

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()));

How to read values from textboxes I created in one form and send them to another form?

So, I created this textboxes in a form2;
System.Windows.Forms.TextBox[] someTb = new System.Windows.Forms.TextBox[10];
for (int i = 0; i < 10; ++i)
{
sombeTb[i] = new TextBox();
textos[i].Location = new System.Drawing.Point(60, 84 + i * 35);
this.Controls.Add(textos[i]);
}
I need to acces to this TextBoxes (someTb) and send them to another Form
Since you already have them in an array, you can just pass that array to another form. Declare a public TextBox[] TextBoxes { get; set; } on the new form, when the form is instanced, assign the array (or a copy of the array) to the public property. Otherwise, you could do similar with a Dictionary<int, string> that uses the array index as the int key portion, and the TextBox Value in the string value portion. Then pass that collection along to the new form.
Probably the most simple answer would be to have a static class in your project that has static members of TextBoxs and read/write to the static variable from either form.
Finally I used the Name property to calle the TextBox whenever i want.
System.Windows.Forms.TextBox[] someTb = new System.Windows.Forms.TextBox[10];
for (int i = 0; i < 10; ++i)
{
sombeTb[i] = new TextBox();
someTb[i].Location = new System.Drawing.Point(60, 84 + i * 35);
this.Controls.Add(someTb[i]);
someTb[i].Name = "someName" + i.ToString();
}
And then I can acces to its methods like this
this.Controls["someName" + i].Method
It´s not the best way, but since I was in a hurry it was the one I used.

How to show array of integer numbers in a listview

I have C# application that make some random number and push it into the array.
How can I show items which are kept in an array on my listview in a single column
when I want use for loop for getting number it makes error
listBox1.Items.Clear();
d = Convert.ToInt32(textBox1.Text);
int[] TimeRand = new int[d];
Random rand = new Random();
for (int i = 0; i < d; i++)
{
TimeRand[i] = rand.Next(1, 100);
}
//i use this code to show but got error
for (int i = 0; i < d; i++)
{
listview1.Items.Add(TimeRand[i]);
}
Since you didn't write what error you got it can be one of two problems with your code:
listview1 is not the correct name of the listview, since the default is listView1 (notice the capital V)
The method Items.Add accepts only strings and you are sending it an int
This should solve your problem:
listView1.Items.Add(TimeRand[i].ToString());

How to square items on Listbox

Is there a way to square the items on a listbox then the output would go to the other listbox
for example I added an item on the listbox using loop
int items;
items=2;
do
{
listbox1.items.add(items);
items=items+2;
} while(items<20);
If you want to add 4, 16, 36, ... 324 items, you can achieve it with the code:
for (int i = 2; i < 20; i += 2)
listbox1.Items.Add(i * i);
Based on the image you posted in a comment to Abdelhamid's answer it looks like you are trying to populate the items in the second list box as the squared version of their counterparts in the first list
foreach(var item in listBox1.Items)
{
//Since you don't specify their type I presume they need parsing..
int num;
int.TryParse(item.ToString(), out num);
listBox2.Items.Add(num * num);
}
If you were trying to do it at the same time as populating the first..
int items = 2;
do
{
listbox1.Items.Add(items);
listbox2.Items.Add(items * items);
items += 2;
} while(items<20);
How about
int items =2;
int items_sq;
do
{
listBox1.Items.Add(items);
items_sq=Math.Pow(items,2); //squares the items variable
listBox2.Items.Add(items_sq);
items += 2;
} while(items<20);
Use the ListBox for display and for user interaction only and do the logic operations independently from the listbox.
// Initialize
List<int> input = new List<int>();
for (int i = 2; i < 20; i += 2) {
input.Add(i);
}
// Calculate
List<int> result = new List<int>();
for (int i = 0; i < input.Count; i++) {
int value = input[i];
result.Add(value * value);
}
// Display
listbox1.Items.AddRange(input);
listbox2.Items.AddRange(result);
The GUI (Graphical User Interface) logic should always be kept separate from the so called Business Logic (in this case the calculation of squares). The List<int>s represent the data in the business logic (they are called the Model). They are typed and need no casting or transformation and do not depend on some controls. If you want to convert your example into a web page, the business logic part will remain exactly the same, where as the display part will be completely different.
int items;
items=2;
do
{
listbox1.items.add(items);
items = Math.Pow(items, 2)
} while(items<20);
Try this...
int items;
items=2;
do
{
listbox1.items.add(items);
listbox2.items.add(items*items);
items=items+2;
} while(items<20);

Textbox to array declaration in C# windows form

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()+" ";
}
}

Categories

Resources