Declaring an Array of Textboxes - c#

I'm trying to declare the array Scores as an array of textboxes. It doesn't have a size. I also need to declare it as an instance variable, and instantiate it in the method, CreateTextBoxes. I keep getting an error, "Scores is a field but is used like a type."
namespace AverageCalculator
{
public partial class AverageCalculator : Form
{
private TextBox[] Scores;
public AverageCalculator()
{
InitializeComponent();
}
private void AverageCalculator_Load(object sender, EventArgs e)
{
btnCalculate.Visible = false;
}
private void btnOK_Click(object sender, EventArgs e)
{
int intNumTextBoxes;
intNumTextBoxes = Convert.ToInt32(txtNumScores.Text);
this.Height = 500;
btnCalculate.Visible = true;
btnOK.Enabled = false;
}
private void CreateTextBoxes(int number)
{
Scores[number] = new Scores[number];
int intTop = 150;
for (int i = 0; i < 150; i++)
{
}
}
}
}

your CreateTextBoxes should probably be something like this:
private void CreateTextBoxes(int number)
{
Scores = new TextBox[number];
for (int i = 0; i < number; i++)
{
Scores[i] = new TextBox();
}
}
As Adil suggested, a List<TextBox> is probably better in this case.

You need to instantiate TextBox but number should be constant You can read more about the array creation expression here. Its better to use List instead of array if you want variable size.
Scores = new TextBox[number];
Using List
List<TextBox> Scores= new List<TextBox>();

Your code should read:
Scores = new TextBox[number];
// do things with this array

The problem is in
private void CreateTextBoxes(int number)
{
Scores[number] = new Scores[number];
int intTop = 150;
for (int i = 0; i < 150; i++)
{
}
}
When you are trying to initialize the array, you are using the name of the field as they type and are including an index to the field name. Just change the new type to TextBox and remove the index accessor like this:
private void CreateTextBoxes(int number)
{
Scores = new TextBox[number];
int intTop = 150;
for (int i = 0; i < 150; i++)
{
}
}

replace line 1 with line 2
Scores[number] = new Scores[number];
Scores[number] = new TextBox();

You can't do this.
Scores[number] = new Scores[number];
Use a list of TextBox.

Related

Using a generic method in a C# class

Here is my current code:
namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
public Random random = new Random();
public int[] randomInt = new int[20];
public double[] randomDouble = new double[20];
public string searchKey;
public int intOrDouble; // 0 if int, 1 if double
public static int Search<T>(T[] inputArray, T key) where T : IComparable<T>
{
for (int i = 0; i < 20; i++)
{
if (inputArray[i].CompareTo(key) == 0)
{
return i;
}
}
return -1;
}
public Form1()
{
InitializeComponent();
}
private void randomIntGeneration_Click(object sender, EventArgs e)
{
randomNumbersTextBox.Clear(); // empty the textbox
intOrDouble = 0; // this is for knowing which parameter to send to search method
// generate 20 random integers and display them in the textbox
for (int i = 0; i < 20; ++i)
{
randomInt[i] = random.Next(0, 100);
randomNumbersTextBox.Text += randomInt[i].ToString() + " ";
}
}
private void randomDoubleGenerator_Click(object sender, EventArgs e)
{
randomNumbersTextBox.Clear(); // empty the textbox
intOrDouble = 1; // this is for knowing which parameter to send to search method
// generate 20 random doubles and display them in the textbox
for (int i = 0; i < 20; ++i)
{
randomDouble[i] = random.NextDouble() + random.Next(0, 100);
randomNumbersTextBox.Text += randomDouble[i].ToString() + " ";
}
}
private void searchArrayButton_Click(object sender, EventArgs e)
{
searchKey = searchKeyTextBox.Text;
if(intOrDouble == 0) // int array passed
{
resultsTextBox.Text = Search(randomInt, searchKey).ToString();
}
else
{
resultsTextBox.Text = Search(randomDouble, searchKey).ToString();
}
}
}
}
What i am trying to do is use this generic method. The GUI allows the user to generate a random array of either ints or doubles. I then want to use the Search method in the searchArrayButton_Click control to display whether or not the "searchKey" value entered is in the array. The error I am getting is "The type arguments for method 'Form1.Search(T[], T)' cannot be inferred from the usage. Try specifying the type arguments explicitly." They appear toward the bottom of the code when I try to call Search twice in the searchArrayButton_Click control.
You're trying to search an array of int or double values for a string. As a result, your call to Search has two arguments with two different types. That doesn't match the function signature.
You need to convert whatever is in that textbox into the value you are searching for, either an int or a double.
if(intOrDouble == 0) // int array passed
{
resultsTextBox.Text = Search(randomInt, int.Parse(searchKey)).ToString();
}
else
{
resultsTextBox.Text = Search(randomDouble, double.Parse(searchKey)).ToString();
}

Carrying user inputs from a textbox from one form to another

I am making a program where the user can enter values in textboxes on one form and then the data will be carried over to the other form. I think the best way of doing this is to store the user data in several arrays and then carry those arrays over but at the moment I am having real trouble doing it. The textboxes are also created once the user has entered how many they require so the textboxes don't exist on the page initially
string q = combobox1.SelectedItem.ToString();
int g = Convert.ToInt32(q);
MessageBox.Show("I have added " +(g-1) +" Films to the list");
TextBox[] FilmTitle1 = new TextBox[int.Parse(q)];
TextBox[] FilmBudget1 = new TextBox[int.Parse(q)];
TextBox[] FilmBoxOffice1 = new TextBox[int.Parse(q)];
TextBox[] FilmDirector1 = new TextBox[int.Parse(q)];
TextBox[] FilmRtScore1 = new TextBox[int.Parse(q)];
TextBox[] FilmGenre1 = new TextBox[int.Parse(q)];
int y = 500;
for (int i = 0; i < g; i++)
{
FilmTitle1[i] = new TextBox();
FilmTitle1[i].Text = "Film Title";
FilmTitle1[i].Size = new Size(162, 20);
FilmTitle1[i].Location = new Point(106, y);
FilmTitle1[i].Tag = 0;
this.Controls.Add(FilmTitle1[i]);
y= y + 40;
private void Createbar_Click(object sender, EventArgs e)
{
BarGraphCreation frm = new BarGraphCreation(FilmTitle.Text, FilmBudget.Text, FilmBoxOffice.Text, FilmDirector.Text, FilmGenre.Text, ft1, FilmBudget1.Text, FilmBoxOffice1.Text, FilmDirector1.Text, FilmGenre1.Text);
frm.Show();
}
But when I do it this way it says that there is no construct for textboxes despite the fact that it allows it everywhere else in the program.
Any type of help is extremely appreciated
public class Form
{
// your code ...
string q = combobox1.SelectedItem.ToString();
int g = Convert.ToInt32(q);
MessageBox.Show("I have added " +(g-1) +" Films to the list");
public TextBox[] FilmTitle1 = new TextBox[int.Parse(q)];
public TextBox[] FilmBudget1 = new TextBox[int.Parse(q)];
public TextBox[] FilmBoxOffice1 = new TextBox[int.Parse(q)];
public TextBox[] FilmDirector1 = new TextBox[int.Parse(q)];
public TextBox[] FilmRtScore1 = new TextBox[int.Parse(q)];
public TextBox[] FilmGenre1 = new TextBox[int.Parse(q)];
int y = 500;
for (int i = 0; i < g; i++)
{
FilmTitle1[i] = new TextBox();
FilmTitle1[i].Text = "Film Title";
FilmTitle1[i].Size = new Size(162, 20);
FilmTitle1[i].Location = new Point(106, y);
FilmTitle1[i].Tag = 0;
this.Controls.Add(FilmTitle1[i]);
y= y + 40;
private void Createbar_Click(object sender, EventArgs e)
{
BarGraphCreation frm = new BarGraphCreation(this);
frm.Show();
}
}
public class BarGraphCreation
{
// your code...
Form form;
public BarGraphCreation(Form form)
{
// ...
this.form = form;
}
private void function()
{
// here you can work with your data like
// form.FilmTitle1 and so on
}
}
You should avoid passing whole objects like TextBox over to some other controls. General idea is You wan't to pass only data (information), always.
As the Form layout is created dynamically, the information about it's Controls should be held somewhere, where can be accessed again easily.
Example (including both array and list as an example):
public class Form1 : Form
{
private TextBox[] FilmTitles;
private List<TextBox> FilmBudget = new List<Textbox>();
//code removed for brevity
private void Button1_Click( /***/ )
{
FilmBudget.Clear();
int count = Convert.ToInt32(q);
FilmTitles = new TextBox[count];
for (int i = 0; i < count; i++)
{
FilmTitles[i] = new TextBox()
{
Text = "Programmer in one day",
Size = new Size(162, 20)
// all other definitions
};
FilmBudget.Add(new TextBox()
{
Text = "1225",
Size = new Size(162, 20)
// all other definitions
};
this.Controls.Add(FilmTitles[i]);
this.Controls.Add(FilmBudget[i]);
//Now you are holding all the TB & text in global variables (arrays/lists)
}
}
private void Createbar_Click(object sender, EventArgs e)
{
BarGraphCreation frm = new BarGraphCreation(
FilmTitles.Select( a => a.Text).ToArray(),
FilmBudget.Select( a => a.Text).ToArray());
frm.Show();
}
}
Where:
public class BarGraphCreation : Form
{
public BarGraphCreation(string[] Titles, string[] Budgets)
{ }
}
Note that this part is using LINQ to select exact properties (values) into 2 arrays:
BarGraphCreation frm = new BarGraphCreation(
FilmTitles.Select( a => a.Text).ToArray(),
FilmBudget.Select( a => a.Text).ToArray());

creat eventHandler for label array element

I was wondering how am I supposed to assign an eventHandler for each array element in my label array. I understand that it's not possible to create a method for each of eventHandlers, so what could be the solution? Thank you!
for(int i = 0, i < 10; i++)
{
lbs[i] = new Label();
lbs[i].Location = new System.Drawing.Point(76 + f, 164);
lbs[i].Size = new System.Drawing.Size(49, 17);
//able to perform this, but wont able to create a method for this
lbs[i].Click += new System.EventHandler(lbs[i]_Click);
}
//can't do this, what is alternative?
public void lbs[i]_Click(object sender, EventArgs e)
{
}
Your function name is invalid (you can't have [] in a function name) try changing lbs[i]_Click to lbs_Click.
for(int i = 0; i < 10; i++)
{
lbs[i] = new Label();
lbs[i].Location = new System.Drawing.Point(76 + f, 164);
lbs[i].Size = new System.Drawing.Size(49, 17);
lbs[i].Name = "label" + i;
//able to perform this, but wont able to create a method for this
lbs[i].Click += new System.EventHandler(lbsi_Click);
}
public void lbsi_Click(object sender, EventArgs e)
{
var label = sender as Label;
if(label != null && label.Name == "label1"){
//event was raised from label1
}
}

C# Creating an array of Fields

Hey!
I want to create an array of fields. however my code return an error of the following: Field 'WindowsFormsApplication1.Form1.fieldArray' is never assigned to, and will always have its default value null.
any suggestion to how I can solve this error?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
private Field[] fieldArray;
private Field f;
public Form1()
{
InitializeComponent();
}
private void populateTree(string path, TreeNode tv1)
{
string[] dir = Directory.GetDirectories(path);
foreach (string d in dir)
{
string entry = Path.GetFileName(d);
TreeNode t = tv1.Nodes.Add("Folder", entry, 0);
populateTree(d, t);
}
string[] files = Directory.GetFiles(path);
foreach (string f in files)
{
string entry = Path.GetFileName(f);
tv1.Nodes.Add(f, entry, 1);
}
}
private void Form1_Load(object sender, EventArgs e)
{
//populate the tree
TreeNode t = treeView1.Nodes.Add("Units");
populateTree(#"..\units\", t);
f = new Field();
for (int i = 0; i < 10; i++)
{
fieldArray[i] = new Field();
}
fieldArray[1].label.AutoSize = true;
fieldArray[1].label.Location = new System.Drawing.Point(323, 9);
fieldArray[1].label.Name = "Programtittle";
fieldArray[1].label.Text = "UAI UnitDef Editor";
this.Controls.Add(fieldArray[1].label);
int clabel = 36;
//fieldArray[1].varName = new string[] { "unitName", "name", "description" }; //define labels
//popluate label
for (int i = 1; i < fieldArray[i].varName.Length; i++)
{
fieldArray[i].label = new Label();
fieldArray[i].label.AutoSize = true;
fieldArray[i].label.Location = new System.Drawing.Point(323, clabel);
fieldArray[i].label.Name = "label";
this.Controls.Add(fieldArray[i].label);
fieldArray[i].label.Text = fieldArray[i].varName[i];
clabel = clabel + 26;
}
//populate textbox
int cbox = 33;
for (int i = 0; i < fieldArray[i].varName.Length; i++)
{
fieldArray[i].txtBox = new TextBox();
fieldArray[i].txtBox.Location = new System.Drawing.Point(380, cbox);
fieldArray[i].txtBox.Name = "txtBox";
fieldArray[i].txtBox.Size = new System.Drawing.Size(100, 50);
this.Controls.Add(fieldArray[i].txtBox);
cbox = cbox + 26;
}
}
private void populateLabelTxtBox(string path)
{
//f.txtBox.Multiline = true; //added for testing purpose;
//read,split file
string text = System.IO.File.ReadAllText(path);
char[] delimiters = new char[] { '{', '=', ';', '}' };
string[] parts = text.Split(delimiters, StringSplitOptions.RemoveEmptyEntries);
for (int i = 0; i < parts.Length; i++)
{
fieldArray[i].txtBox.Text = parts[i];
}
}
private void treeView1_NodeMouseDoubleClick(object sender, TreeNodeMouseClickEventArgs e)
{
if (treeView1.SelectedNode.Name != "Folder")
{
string text = System.IO.File.ReadAllText(treeView1.SelectedNode.Name);
//f.txtBox.Text = text;
populateLabelTxtBox(treeView1.SelectedNode.Name);
}
}
}
}
A list might be easier than an array, but: you are assigning items to a null array; once you know the number you need, create the array first:
fieldArray = new Field[10];      
for (int i = 0; i < 10; i++)
{...}
However, personally I'd use a list:
private readonly List<Field> fields = new List<Field>();
...
fields.Add(someField);
You never initialize fieldArray
//Change
private Field[] fieldArray;
to
private Field[] fieldArray = new Field[10];
You never initialized fieldArray. Something like fieldArray = new Field[10]; in the constructor of your Form should do it.
Before you try to access elements in the fieldArray you have to initialize the array like so:
fieldArray = new Field[/*size of the array*/];
However, be careful to create an array large enough to store all your fields. Suppose you create a Field[5] array of 5 elements, and you try to assign a value to fieldArray[5] you will get an OutOfBounds exception.
Before doing your loop where you initialize each element of the array, you need to initialize the array itself:
fieldArray = new Field[10]; // Create this with the appropriate size
for (int i = 0; i < 10; i++)
{
fieldArray[i] = new Field();
}
On a different note, you're never actually setting fieldArray[0] - I suspect your code that is explicitly setting fieldArray[1].XXX should be working on element 0.
Initialize your array when you declare it:
private Field[] fieldArray = new Field[100]; // size == 100
I don't see any line that assigns the array: like
int number_of_elements = 100;
fieldArray = new Field[number_of_elements];
if the number of fields is dynamic I would use an ArrayList, like
List fieldArray = new List();
and then add elements to it:
fieldArray.Add(...)
You must initialize your array
fieldArray = new Field[10];
fieldArray[i] = new Field();
The above code makes you think that the array is already initialized, but actually it has not. You need to have something like the following to allocate some memory for the array.
fieldArray = new Field[/*length or size*/];

C# reassigning array values(down one step ex 5-4) that are within an object during a event

Just learning C# (along with object and event programing) and the teacher didn't really show us how to get things done.
class Postion
{
private int[] x_coordinate = new int[100];
private int[] y_coordinate = new int[100];
private double[] speed = new double[100];
private int[] direction = new int[100];
const int MAX_SPEED = 50;
int counter = 0;
public Postion()
{
x_coordinate[counter] = 0;
y_coordinate[counter] = 0;
speed[counter] = 0;
direction[counter] = 0;
}
//get set methods
public int X
{
get
{
return x_coordinate[counter];
}
set
{
x_coordinate[counter] = value;
}
}
There is one more Class between them
The values are frist assigned by a button click.
Airplane newplane = new Airplane();
private void BtnCreate_Click(object sender, EventArgs e)
{
bool box = txtName.Text != "";
if (box == true)
newplane.Name = txtName.Text;
else { }
box = txtx.Text != "";
if (box == true)
newplane.PlanePostion.X = int.Parse(txtx.Text);
else { }
Etc.
I can call on the array values for display for the list box.
private void lsbplanes_SelectedIndexChanged(object sender, EventArgs e)
{
placeholder = newplane.PlanePostion.Counter;
newplane.PlanePostion.Counter = lsbplanes.SelectedIndex;
if (newplane.PlanePostion.Counter < 0)
newplane.PlanePostion.Counter = 0;
else { }
lblxshow.Text = Convert.ToString(newplane.Getx());
but when using a destroy button to remove an item in the list box I need to have it so the box updates with the new values when the user selects the item in the listbox.
This is what I have to try and do it so far, it sets all the ones above to 0s but does remove the the deleted one fine
private void BtnKill_Click(object sender, EventArgs e)
{
if (lsbplanes.SelectedIndex == -1)
{
MessageBox.Show("Please select an item first.", "No item selected", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
else
{
placeholder = lsbplanes.SelectedIndex;
newplane.PlanePostion.Counter = lsbplanes.Items.Count;
while (newplane.PlanePostion.Counter > placeholder)
{
placex = newplane.PlanePostion.X;
placey = newplane.PlanePostion.Y;
placespeed = newplane.Getspeed();
placedic = newplane.Getdirection();
newplane.PlanePostion.Counter--;
newplane.PlanePostion.X = placex;
newplane.PlanePostion.Y = placey;
newplane.PlanePostion.Speed = placespeed;
newplane.PlanePostion.Direction = placedic;
}
lsbplanes.Items.RemoveAt(lsbplanes.SelectedIndex);
newplane.PlanePostion.Counter = lsbplanes.Items.Count;
}
anyone can help me on this?
I was torn in this question, answer exactly what your problem is, or suggest that you redesign it.
#Marc is right you should be using some sort of List<Position> on your Plane object (or a ReadOnlyObservableCollection<Position>).
#Marc is also right, that the problem you are having is that you are trying to push the values down from the end of the list and overwriting them. In these cases it is better to start from the deletion point and pull them down.
So if you have {1,2,3,4,5,6,7,8,9,10} and you delete from item 5, you would have {1,2,3,4,10,10,10,10,10,10}. The code below will let you end up with {1,2,3,4,6,7,8,9,0}
placeholder = lsbplanes.SelectedIndex;
int idx = placeholder;
while (idx < lsbplanes.Items.Count)
{
newplane.PlanePosition.Counter = idx+1;
placex = newplane.PlanePostion.X;
placey = newplane.PlanePostion.Y;
placespeed = newplane.Getspeed();
placedic = newplane.Getdirection();
newplane.PlanePostion.Counter = idx;
newplane.PlanePostion.X = placex;
newplane.PlanePostion.Y = placey;
newplane.PlanePostion.Speed = placespeed;
newplane.PlanePostion.Direction = placedic;
idx++;
}
// Need to zero out elements at the end
newplant.PlanePosition.Counter = lsbplanes.Items.Count;
/* Zeroing code goes here */
newplane.PlanePosition.Counter = placeholder;
lsbplanes.Items.RemoveAt(lsbplanes.SelectedIndex);

Categories

Resources