I´m adding controls dynamically onto my form, but I can't see those new controls.
My code is:
frmFormulario myform = new frmFormulario();
for (int i = 0; i < elements.Count; i++)
{
String nm = elements[i].name;
String chk = "chk"+nm;
CheckBox checkboxWS = new CheckBox();
checkboxWS.Name = chk;
checkboxWS.Checked = true;
checkboxWS.Visible = true;
checkboxWS.Width.Equals(40);
myform.Controls.Add(checkboxWS);
myform.Controls.SetChildIndex(checkboxWS, 0);
}
Can anybody spot the problem?
Thanks
My environment is C# Visual Studio 2010
Try adding
myform.Show(); //or myform.ShowDialog;
after the for loop. If you want to completely work on this new window (myform) and discard the former or parent then try creating it in a new thread.
Hope it helps.
You are creating a new form inside of the loop as well as the controls. Once the loop is done it falls out of scope. I'm sure you didn't want to do that, rather add them to an existing form.
Where do you show myform, the instance of frmFormulario?
Currently you are creating a new form and you don't display it.
Related
I'm working on a Agenda using windows forms C#, I'm trying to create a colored picture box for each appointment object in the project. Using this code that is used in a loop for each object in my appointment list im creating each picturebox on the right location on the form1 screen.
PictureBox Point = new PictureBox();
this.Controls.Add(Point);
Point.Location = new Point(obj.Location.X, 45 + obj.Location.Y);
Point.BackColor = color;
Point.Size = new Size(96, 25);
Point.Enabled = false;
Point.Tag = "Point";
Point.TabIndex = 100;
Point.Visible = true;
When I'm calling this method from input on the same form, for example a button click. It will work just fine and create all the picture boxxes as needed. But when I'm calling it from the form2.closed event it wont work. Form 2 is my appointment planner form, when clicking on save on this form it will add a new object to the list, so a new picturebox should be created. I have checked the debug using breakpoints, and strange enough it will go through the create code, but no matter what I do it wont render the pictureboxxes.
I personally think it has to do with the form1 not Initializing when called from form2.closed event. But even when using InitializeComponent(); end Refresh(); inside my code it still doesnt work.
Am I using the wrong event or is there a specific call I need to make to generate the pictureboxxes?
Sorry if my post is lacking code or info, I'm not used to posting on stackoverflow, feel free to ask for more information if needed.
if you run your code from Form2 and you want to add control to Form1 you cannot use "this". Form1 has to be accessible from Form2.
PictureBox Point = new PictureBox();
Point.Location = new Point(obj.Location.X, 45 + obj.Location.Y);
Point.BackColor = color;
Point.Size = new Size(96, 25);
Point.Enabled = false;
Point.Tag = "Point";
Point.TabIndex = 100;
Point.Visible = true;
Form1.Controls.Add(Point);
I'm working on an inventory program and have finished the main functionality as a command line console app. I am now working on a version for winforms. I want to enable it to dynamically generate a Groupbox that holds some textboxes. I'd rather not design 50+ lines of multiple textboxes. Keep in mind I'm rather new to programming, having started with C# a year ago. I know next to nothing on Winforms.
I've tried to use dynamic item = new Groupbox();as a similar method allowed generation of objects at runtime. In the command line app, the way it works is that based on information given, a certain amount of objects are passed into the list _AllItems. I was thinking of generating the Groupboxes by using:
private void InitializeGroupBox()
{
foreach (Product product in Product._AllItems)
{
dynamic Item = new GroupBox();
}
}
But I have the feeling I'm nowhere near the correct method. Thanks to anybody who helps.
You will need to learn a bit more, but here is what I usually do to achieve what you asked.
internal class DynamicForm : Form
{
private FlowLayoutPanel mFlowLayoutPanel;
public DynamicForm()
{
mFlowLayoutPanel = new FlowLayoutPanel();
mFlowLayoutPanel.Dock = DockStyle.Fill;
// Add to this Form
this.Controls.Add(mFlowLayoutPanel);
InitializeGroupBox();
}
private void InitializeGroupBox()
{
mFlowLayoutPanel.SuspendLayout(); // Performance
for (int i = 1; i <= 20; i++) {
var groupBox = new GroupBox();
groupBox.Text = "GroupBox #" + i;
groupBox.Size = new Size(200, 50);
var textBox = new TextBox();
textBox.Dock = DockStyle.Fill;
// Add the TextBox to GroupBox
groupBox.Controls.Add(textBox);
// Add to this Form
mFlowLayoutPanel.Controls.Add(groupBox);
}
mFlowLayoutPanel.ResumeLayout(); // after suspend, resume!
}
}
I have my main form and a dialogbox which is called from main. In my main form I have a label and a button that which properties I can't change. I'm using Visual Studio 2015, not sure if there is a bug regarding this. I also made sure my label and button are set to public to modify.
Code: (this is from the dialog box, this has a list box the function is triggered at selectindexchange)
else if ((short)lbDiscountTypes.SelectedValue == 2) //Senior
{
frm_Main main = new frm_Main();
main.VAT = false;
main.labelStatus.Text = "NON-VAT (SENIOR)";
main.labelStatus.BackColor = System.Drawing.Color.IndianRed;
main.labelStatus.ForeColor = System.Drawing.Color.WhiteSmoke;
main.btnNonVat.Enabled = false;
main.btnNonVat.BackColor = System.Drawing.Color.SlateGray;
main.btnNonVat.ForeColor = System.Drawing.Color.Navy;
main.labelVatAmount.Text = 0.00m.ToString();
main.Dispose();
//INQUIRE DISCOUNT TYPES
var Discount = GC.CSHR_DiscountTypes.Where(Filter => Filter.DiscountCode == (short)lbDiscountTypes.SelectedValue);
decimal DP = 0.00m;
foreach (var item in Discount)
{
DP = item.DiscountPercentage;
}
foreach (var item in GC.CSHR_SORepo
.Where(Filter => Filter.Machine == MACHINE
&& Filter.SalesOrderNum == SALESORDERNUM
&& Filter.First_SRP == Filter.IMFSRP))
{
item.DiscountAmount = (item.SoldSRP * DP) / 100;
item.TotalAmount = (item.Quantity * item.SoldSRP) - item.DiscountAmount;
item.VATableSalesOnTotalAmount = (item.Quantity * item.SoldSRP) - item.DiscountAmount;
item.VATRate = 0.00m;
GC.SaveChanges();
}
Close();
}
The code below //INQUIRE DISCOUNT TYPES works well but not the one on top.
I've used debug mode to check if the lines are not being skipped over and they aren't.
You should pay attention to:
You are creating a new instance of your main form that you don't need (while it is open behind the dialog), so you need to get it not create a new instance
You are disposing the main form you created. main.Dispose();
In fact you are creating a new instance of main form and assigning values to those controls and then dispose it. While and instance of yor main form that you expect to see changes on it, is open and untouched behind your dialog.
To set value of those controls you can do one of these ways:
Option 1
Make your labelStatus and btnNonVat public. Open your main form in designer and select labelStatus and btnNonVat and in property grid, set Modifier to public. Then write this code:
//var main = Application.OpenForms.OfType<frm_Main>().FirstOrDefault();
var main = (frm_Main)Application.OpenForms["frm_Main"];
main.labelStatus.Text = "NON-VAT (SENIOR)";
main.labelStatus.BackColor = System.Drawing.Color.IndianRed;
main.labelStatus.ForeColor = System.Drawing.Color.WhiteSmoke;
main.btnNonVat.Enabled = false;
main.btnNonVat.BackColor = System.Drawing.Color.SlateGray;
main.btnNonVat.ForeColor = System.Drawing.Color.Navy;
main.labelVatAmount.Text = 0.00m.ToString();
Option 2
Pass an instance of your frm_Main to your dialog and work with it.
Option 3
After closing the dialog, use values from dialog and set values of your main form
Looks like you are trying to create new form using frm_Main main = new frm_Main(); syntax. All you need to do is get the instance of your current form.
var _currentMainForm= Application.OpenForms[0];
or if you have given name to your form
var _currentMainForm = Application.OpenForms["MainFormName"];
Once you get the reference you can perform all your label updates.
The code on top creates a new form, changes the labels and then disposes the form.
I think you should change the labels of the existing form.
Like in the other answer said you are setting properties of controls into a new Form object and not in the form where you come from.
You should pass the form object into the parameters of the dialog, something like:
void myDialog(frm_Main callingForm)
{
callingForm.Textbox1.Text = "abc";
}
And call it from you main form like this
...
myDialog(this);
I have created a textBox control on run-time for my winform application. The control appears just find once the form loads up, and works great too. However, I have just run into a problem as I realize I do not know how to write the code to write to a dynamically created control.
Let's assume I have created a button (named "Button1") on design time. In Button1's click event, (Button1_Click), I would like to write the word "Hello" to a textBox control that won't be created until the application is executed. Some code below:
C# Code:
// Create the textBox control
TextBox new_textBox = null;
int x = 10;
int y = 10;
int xWidth = 300;
int yHeight = 200;
new_textBox = new TextBox();
new_textBox.Text = controlText;
new_textBox.Name = "textBox" + controlName;
new_textBox.Size = new System.Drawing.Size(xWidth - 10, yHeight - 10);
new_textBox.Location = new Point(x, y);
new_textBox.BringToFront();
new_textBox.Multiline = true;
new_textBox.BorderStyle = BorderStyle.None;
// Add the textBox control to the form
this.Controls.Add(new_textBox);
The Problem:
From Button1_Click event, I cannot get in contact with a control that has not even been created yet. Thus, Visual Studio will throw an obvious error that the control does not exist (because it doesn't).
So, is there some way to dynamically call a control, and more
specifically, a textBox control?
Thank you for any help on the matter,
Evan
Declare the new_textBox at class scope. Then the compiler can access it. For example:
class MyForm
{
TextBox new_textBox;
void InitializeTextBox()
{
new_textBox = new TextBox();
// initialization code here
// Add it to the form
this.Controls.Add(new_textBox);
}
void Button1_Click(...)
{
new_textBox.Text = "clicked";
}
You can make the new_textBox a class member (member of the form). You can again assign it a value and add to the forms controls later dynamically.
It would be a good practice to check if is null in the buttonClick event, though.
For example, I would like an array of checkboxes:
CheckBox[] faults = new CheckBox[20];
Now how do I place these in my Form and link them to their array name?
Thanks.
How about that:
YourForm.Controls.AddRange(faults);
You have iterate through each checkboxes in faults, but keep in mind they do not overlap so, you can do like this.
Example:
int top = 0; //used for proper positioning of controls
foreach (CheckBox cb in faults)
{
cb.Location =new Point(0 , top); // fixing cb for distinct position
top +=10;
this.Controls.Add(cb);
}
foreach (CheckBox cb in faults) YourForm.Controls.Add(cb);
Assuming you are using MS Visual Studio: create a small test project, add a checkbox to a form named MyForm using the Visual Studio designer and have a look into the generated method InitializeComponent in the file MyForm.designer.cs. This will help you to find out which properties of your checkboxes you will have to initialize. And, of course, you will see where Visual Studio places the call this.Controls.Add(cb).
Try this:
var faults = new CheckBox[20];
Point startPoint = new Point(20, 10);
for (int i = 0; i < faults.Length; i++)
{
Controls.Add(new CheckBox()
{
Location = new Point(startPoint.X, 20 * i + startPoint.Y),
Text = (i + 1).ToString()
});
}
Good luck!