I was wondering how could I select objects which were created during programs runtime.
Each object has its unique name. How could I select that object by its name?
Example names:
"mapPart_0_0"
"mapPart_0_1"
"mapPart_0_2"
etc.
It's a windows form project. In c#.
Creation of those objects:
private void addBoxes()
{
for (int a = 0; a < 25; a++)
{
for (int b = 0; b < 10; b++)
{
MyCustomPictureBox box = new MyCustomPictureBox();
box.Location = new Point(b * 23 + 5, a * 23 + 5);
box.Image = new System.Drawing.Bitmap("tiles/0.png");
box.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
box.Size = new Size(24, 24);
box.Name = "mapPart_" + a + "_" + b;
box.Click += new EventHandler(boxClickAdd);
box.oFile = "0";
panel1.Controls.Add(box);
}
}
}
I would suggest to simply put the objects in a System.Collections.Generic.Dictionary<string, your object type> list. It provides the exact functionality you are seeking if I understand the question correctly.
Related
I am wanting to use to names assigned using .Name to input from text boxes then calculate and output to the labels.
Not sure how I can refer to these inputs as they currently have names but no assigned variables.
Sorry if I don't make much sense I am not a very proficient coder.
public partial class Form1 : Form
{
List<TextBox> Txt1 = new List<TextBox>();
public Form1()
{
InitializeComponent();
for (int i = 0; i < 4; i++)
{
for(int j = 0; j < 7; j++)
{
if (j == 0)
{
var txtbox = new TextBox();
txtbox.Location = new Point(163 + (i * 220), (36));
txtbox.Name = i + "Names";
txtbox.Text = txtbox.Name;
txtbox.Width = 40;
this.Controls.Add(txtbox);
}
else if (j>0 && j<6)
{
var extratxt = new TextBox();
extratxt.Location = new Point(163 + (i * 220), (36+ 36 * j));
extratxt.Name = i + "Input" + j;
extratxt.Text = extratxt.Name;
extratxt.Width = 70;
this.Controls.Add(extratxt);
var percentbox = new Label();
percentbox.Location = new Point(163 + (90+ i * 220), (36 + 36 * j));
percentbox.Name = i + "Percent" + j;
percentbox.Text = percentbox.Name;
percentbox.Width = 50;
this.Controls.Add(percentbox);
var gradebox = new Label();
gradebox.Location = new Point(163 + (150 + i * 220), (36 + 36 * j));
gradebox.Name = i + "Grade" + j;
gradebox.Text = gradebox.Name;
gradebox.Width = 50;
this.Controls.Add(gradebox);
}
else
{
var totals = new Label();
totals.Location = new Point(163 + (i * 220), (36 + 36 * j));
totals.Name = i + "Total";
totals.Text = totals.Name;
totals.Width = 40;
this.Controls.Add(totals);
...
}
...
}
}
}
}
Hope I understand you correctly.
Basically, your difficulty is how to access the instance stored in list of the dynamically create controls by their name, right?
Well, you can use .FirstOrDefault() to select instance with a specific property. For example,
private void Form1_Load(object sender, EventArgs e)
{
List<TextBox> tbList = new List<TextBox>();
for (int i = 0; i < 3; i++)
{
TextBox tb = new TextBox();
tb.Text = "Test" + i.ToString();
tb.Name = "TextBox" + (i + 1).ToString();
tb.Location = new Point(0, 25 * i);
tb.Tag = i;
tbList.Add(tb);
this.Controls.Add(tb);
}
var tb2 = tbList.FirstOrDefault(tb => tb.Name == "TextBox2");
if (tb2 != null)
tb2.Text = "Modified text";
var sum = tbList.Sum(tb => (int)tb.Tag);
}
This sounds wierd but i have no idea how to do this, despite the fact i've read lots of articles and answers about it.
this one seems to be the most clear, but unfortunately it doesn't help me.
Like this
so i have an array of labels that should be updated during the for cycles:
public const int NUM_OF_PAGES = 128;
...
int[] PEcnt = new int[NUM_OF_PAGES];
Label[] PElabels = new Label[NUM_OF_PAGES];
for (int i = 0; i < NUM_OF_PAGES; i++) // initialization
{
PEcnt[i] = 0;
PElabels[i] = new Label();
PElabels[i].Content = 0;
PElabels[i].Margin = new Thickness(50 + 80 * (i % 16), 50 + 20 * (i / 16), 0, 0);
Grid1.Children.Add(PElabels[i]);
}
...
for (int i = 0; i < NUM_OF_PAGES; i++)
{
PEcnt[i] += 2;
PElabels[i].Content = PEcnt[i];
BindingOperations.GetBindingExpressionBase(PElabels[i], Label.ContentProperty).UpdateTarget(); //trying to update
}
but this throws me "System.NullReferenceException"
hope u will help me, learning is difficult, but im trying hard
don't .UpdateTarget(); and it should be okay I believe
you don't need to get binding expressions for this, if you are using it else where do not update target here.
so first of all:
The Label.Content Property stores an object! So you can store an Integer in it without casting!
You are trying to update an BindingExpression on an NOTbinded Property!
So the way you should solve your problem, is by just NOT updating it.
Because your Label isn't using any bindings your called function returns null.
So just Store your Integer in the content property and YOLO. Here is the working code:
public const int NUM_OF_PAGES = 128;
Label[] PElabels = new Label[NUM_OF_PAGES];
...
for (int i = 0; i < NUM_OF_PAGES; i++) // initialization
{
PElabels[i] = new Label();
PElabels[i].Content = 0; //Storing your Data as int in object
PElabels[i].Margin = new Thickness(50 + 80 * (i % 16), 50 + 20 * (i / 16), 0, 0);
Grid1.Children.Add(PElabels[i]);
}
...
for (int i = 0; i < NUM_OF_PAGES; i++)
{
PElabels[i].Content = (int)PElabels[i].Content + 2; //Storing your new Data
}
SO!!!!
If you realy need to use this update binding, you have to set your content property to an Binding. To do so, you have to store your data in some property for example in the Label.DataContext. Now you need to set the Binding (pointing at the DataContext) to you Label.ContentProperty. After doing that you can update your BindingExpression and the Label will change.
Working Code here:
public const int NUM_OF_PAGES = 128;
Label[] PElabels = new Label[NUM_OF_PAGES];
...
for (int i = 0; i < NUM_OF_PAGES; i++) // initialization
{
PEcnt[i] = 0;
PElabels[i] = new Label();
PElabels[i].DataContext = 0; //Storing your Data
Binding PEcntBind = new Binding("DataContext");
PEcntBind.Source = PElabels[i];
PElabels[i].SetBinding(Label.ContentProperty, PEcntBind); //Binding to your stored Data
PElabels[i].Margin = new Thickness(50 + 80 * (i % 16), 50 + 20 * (i / 16), 0, 0);
Grid1.Children.Add(PElabels[i]);
}
...
for (int i = 0; i < NUM_OF_PAGES; i++)
{
PEcnt[i] += 2;
PElabels[i].DataContext = PEcnt[i]; //Storing your new Data
BindingExpression LabBindEx = (PElabels[i] as FrameworkElement).GetBindingExpression(Label.ContentProperty);
LabBindEx.UpdateTarget(); //Updating the Bindings
}
(Oh and by the way you have to use GetBindingExpression not GetBindingExpressionBase)
I have got the below code to generate labels using for loop, however there is a problem with the for loop, if the productList has 4 items, it generates 1 label instead of 4. I can't figure out what the problem is.
List<models.Car> carList = carController.getCars();
for (int i = 0; i < carList.Count; i++)
{
List<models.Product> productList = productController.getProducts(carList[i].Model);
for (int j = 0; j < productList.Count; j++)
{
productLabels.Add(new Label());
var productLabelsPoint = new System.Drawing.Point(200, 40 + i * 50);
(productLabels[j] as Label).Location = productLabelsPoint;
(productLabels[j] as Label).Size = new System.Drawing.Size(150, 15);
(productLabels[j] as Label).Text = productList[j].Title;
this.Tab.TabPages["tab1"].Controls.Add((productLabels[j] as Label));
}
}
This only relies on i, not on j:
System.Drawing.Point productLabelsPoint = new System.Drawing.Point(200, 40 + i * 50);
So you might be drawing the labels one on top of the other.
In which case, you'd need to add j into the mix, for example like this:
System.Drawing.Point productLabelsPoint = new System.Drawing.Point(200, 40 + i * 50 + j * 50);
I would also change the way you are referencing the label. (I can't tell from the context if what you are doing is okay or not, as it depends how that productLabels variables has been instantiated.)
Here is the code I'm using
It's supposed to create labels for each module name entered by a user and all the assessment names for that module under it. Should work with any number of modules and assessments. The problem is that it only shows assessments for the last module displayed.
dat.Modules and dat.Assessments are arraylists, each of them holds 4 elements with info about a module or an assessments, that is why i divide the count by 4.
private void testingButton_Click(object sender, EventArgs e)
{
int pos1 = 50;
int pos2 = 150;
int modLength = dat.Modules.Count;
modLength = modLength / 4;
int assessLength = 0;
int arrayData = 0;
int displayCount = 0;
for (int i = 0; i < modLength; i++)
{
this.moduleLabels.Add(new Label());
System.Drawing.Point pLabel1 = new System.Drawing.Point(50, pos1);
(moduleLabels[i] as Label).Location = pLabel1;
(moduleLabels[i] as Label).Size = new System.Drawing.Size(100, 13);
(moduleLabels[i] as Label).Text = dat.Modules[arrayData].ToString();
tabPage5.Controls.Add((moduleLabels[i] as Label));
String asd = dat.Modules[arrayData + 2].ToString();
Console.WriteLine(asd);
assessLength = int.Parse(asd);
pos2 = pos1 + 25;
for (int y = 0; y < assessLength; y++)
{
this.assessLabels.Add(new Label());
System.Drawing.Point pLabel2 = new System.Drawing.Point(70, pos2);
(assessLabels[y] as Label).Location = pLabel2;
(assessLabels[y] as Label).Size = new System.Drawing.Size(250, 13);
(assessLabels[y] as Label).Text = dat.Assessments[displayCount + 1].ToString() + " weights " + dat.Assessments[displayCount+2].ToString() +"%, Enter your mark:";
textboxComputer.Add(new TextBox());
System.Drawing.Point pText1 = new System.Drawing.Point(400, pos2);
(textboxComputer[y] as TextBox).Location = pText1;
(textboxComputer[y] as TextBox).Size = new System.Drawing.Size(20, 20);
tabPage5.Controls.Add(assessLabels[y] as Label);
tabPage5.Controls.Add(textboxComputer[y] as TextBox);
pos2 = pos2 + 25;
displayCount = displayCount + 4;
}
pos1 = pos2+25;
arrayData = arrayData + 4;
}
}
this is an example of what it displays
http://dc540.4shared.com/download/YI8IENYI/tsid20120501-211723-cbc785f9/asd.jpg
The first two modules should have their assessments listed. The first one doesn't display any. For Java it only displays the last one, out of 3 total for that module. And for the last Module "Another Module" it displays all assessments.
For each increment of i, y starts at 0. You then add new labels to assessLabels, but attempt to access the one you added by using assessLabels[y] which would usually yield the labels created for the previous value of i. This causes labels created for the first module to be reused by the next, and so forth.
A quick solution is not to use assessLabels[y] but assessLabels[assessLabels.Count - 1].
A better solution is to create a local variable for the labels, set their properties, and then add them to the list:
for (int y = 0; y < assessLength; y++)
{
Label assessLabel = new Label();
assessLabel.Location = ...;
// etc.
tabPage5.Controls.Add(assessLabel);
assessLabels.Add(assessLabel);
}
This would also remove the need to continuously cast the ArrayList members and unneeded access to the list.
PS. If assessLabels only contains objects of type Labels, consider using a List<Label> instead.
I have generated 8*16 ovalshape's in a form. The code is:
for (int i = 0; i < 16; i++)
{
for (int j = 0; j < 8; j++)
{
OvalShape ovl = new OvalShape();
ovl.Width = 20;
ovl.Height = 20;
ovl.FillStyle = FillStyle.Solid;
ovl.FillColor = Color.Transparent;
ovl.Name = "oval" + j + "" + i;
ovl.Location = new Point((ovl.Width * i) * 2, (ovl.Height * j) * 2);
ovalShape.Add(ovl);
}
}
foreach (OvalShape os in ovalShape)
{
Microsoft.VisualBasic.PowerPacks.ShapeContainer shapeContainer =
new Microsoft.VisualBasic.PowerPacks.ShapeContainer();
os.Parent = shapeContainer;
this.Controls.Add(shapeContainer);
}
Now I want access to each ovalshape differently. How could I do this?
Since ovalShape is a List<OvalShape>, you can use the indexer to access any one item:
var anOval = ovalShape[0];
You are already accessing each ovalshape in ovalShape differently in your foreach loop
foreach (OvalShape os in ovalShape)
{
//...
}
Otherwise you can also access each ovalshape by it's index, as
var newOvalShape = ovalShape[0];
You have already named your controle like ovl.Name = "oval" + j + "" + i;
So , I think you can create dictrionary like Dictionary<string , OvalShape> dic
Then you can set it like
//...
ovl.Name = "oval" + j + "" + i;
dic.add(ovl.Name , ovl);
//...
Then , you can access this dictionary in other methods , and access it by its name.