New window replicates - c#

I am working on an interface that uses a Wcf to obtain data from out database, I am having the following issue, I am using a dynamic window to display information as well as some buttons for date times, and close, etc...
However when I close the window and reopen it, it adds everything back to the form that was already there, which creates double and is causing some problems, any advice would be great, thanks in advance
Here is some code to better describe what I have....
This is the button I have on my primary form, which creates the new window
private void butMoreInf_Click(object sender, RoutedEventArgs e)
{
winMain.DataContext = null;
winMainContainer.DataContext = null;
winMainContainerLeft.DataContext = null;
winMainContainerRight.DataContext = null;
datGrid.DataContext = null;
//Generate the new window and panel to go within the window
winMain.Height = 750;
winMain.Width = 950;
winMainContainer.Width = 1000;
winMainContainer.HorizontalAlignment = HorizontalAlignment.Left;
winMainContainerLeft.Width = 120;
winMainContainerLeft.HorizontalAlignment = HorizontalAlignment.Left;
winMainContainerRight.Width = 880;
winMainContainerRight.HorizontalAlignment = HorizontalAlignment.Left;
//Generate the datagrid to contain the date to be changed etc.
datGrid.Margin = new Thickness(0, 12, 12, 12);
datGrid.HorizontalAlignment = HorizontalAlignment.Right;
//Generate a datepicker (start) and label
Label labS = new Label();
labS.Content = "Pick a start date";
labS.Width = 100;
labS.Margin = new Thickness(12, 1, 0, 1);
labS.HorizontalAlignment = HorizontalAlignment.Left;
DatePicker datPickStart = new DatePicker();
datPickStart.Width = 100;
datPickStart.Margin = new Thickness(12, 12, 1, 0);
datPickStart.HorizontalAlignment = HorizontalAlignment.Left;
datPickStart.SelectedDate = DateTime.Now.AddDays(-7);
datStartPick = datPickStart.SelectedDate == null ? DateTime.Now : Convert.ToDateTime(datPickStart.SelectedDate);
//Generate a datepicker (end) and label
Label labE = new Label();
labE.Content = "Pick an end date";
labE.Width = 100;
labE.Margin = new Thickness(12, 1, 0, 1);
labE.HorizontalAlignment = HorizontalAlignment.Left;
DatePicker datPickEnd = new DatePicker();
datPickEnd.Width = 100;
datPickEnd.Margin = new Thickness(12, 12, 1, 0);
datPickEnd.HorizontalAlignment = HorizontalAlignment.Left;
datPickEnd.SelectedDate = DateTime.Now;
datEndPick = datPickEnd.SelectedDate == null ? DateTime.Now : Convert.ToDateTime(datPickEnd.SelectedDate);
//Generate dropdown and label for that box
Label labY = new Label();
labY.Content = "";
labY.Width = 100;
labY.Margin = new Thickness(12, 1, 0, 1);
labY.HorizontalAlignment = HorizontalAlignment.Left;
ComboBox txtY = new ComboBox();
txtY.Width = 100;
txtY.Margin = new Thickness(12, 12, 1, 0);
txtY.HorizontalAlignment = HorizontalAlignment.Left;
txtY.SelectedIndex = 0;
txtY.SelectionChanged += CLLoadErrors;
txtY.SelectedIndex = 0;
//Generate error list button
Button butError = new Button();
butError.Width = 100;
butError.Margin = new Thickness(12, 12, 1, 0);
butError.HorizontalAlignment = HorizontalAlignment.Left;
butError.Content = "Get Errors";
butError.Click += CLLoadErrors;
//Generate clear button
Button butClear = new Button();
butClear.Width = 100;
butClear.Margin = new Thickness(12, 12, 1, 0);
butClear.HorizontalAlignment = HorizontalAlignment.Left;
butClear.Content = "Clear Grid";
butClear.Click += clearDataGrid;
//Generate close button
Button butClose = new Button();
butClose.Width = 100;
butClose.Margin = new Thickness(12, 12, 1, 0);
butClose.HorizontalAlignment = HorizontalAlignment.Left;
butClose.Content = "Close";
butClose.Click += CLHide;
//Add elements to the stackpanel / Also updates them before each instance
winMainContainerLeft.UpdateLayout();
winMainContainerLeft.Children.Add(labS);
winMainContainerLeft.Children.Add(datPickStart);
winMainContainerLeft.Children.Add(labE);
winMainContainerLeft.Children.Add(datPickEnd);
winMainContainerLeft.Children.Add(labY);
winMainContainerLeft.Children.Add(txtY);
winMainContainerLeft.Children.Add(butError);
winMainContainerLeft.Children.Add(butClear);
winMainContainerLeft.Children.Add(butClose);
winMainContainerRight.UpdateLayout();
winMainContainerRight.Children.Remove(datGrid);
winMainContainerRight.Children.Add(datGrid);
winMainContainer.UpdateLayout();
winMainContainer.Orientation = Orientation.Horizontal;
winMainContainer.Children.Remove(winMainContainerLeft);
winMainContainer.Children.Add(winMainContainerLeft);
winMainContainer.Children.Remove(winMainContainerRight);
winMainContainer.Children.Add(winMainContainerRight);
winMain.ResizeMode = ResizeMode.NoResize;
//Display the new form
winMain.UpdateLayout();
winMain.Content = winMainContainer;
winMain.Show();
datGrid.MouseDoubleClick += datGridDClick;
txtY.SelectionChanged += new SelectionChangedEventHandler(txtY_SelectionChanged);
}
Will provide more code if needed.

You are reusing the same window again and again (why?), so you need to clear out the children collections before you add new elements, otherwise every click on your button will show the window + every control you add, resulting in double/triple/... controls.
Update: I assume you use StackPanels (from your comment / having Children enumerations). The Children enumeration is a UIElementCollection which allows to invoke the Clear method. Just call this prior to adding new controls. (on winMainContainer, winMainContainerRight and winMainContainerLeft)

Where do you initialize winMain? Is it a static variable or does it live within your current form?
I'm guessing that you keep adding controls to an existing object(which causes the duplication effect). To fix this you could either reinitialize the form object
winMain = new WinMainForm();
or you could remove all controls on the winMain variable right before adding the new children
foreach(var c in winMainContainer.children){
winMainContainer.children.remove(c)
}

It looks like you aren't creating a new window at all, rather just performing operations on 'winMain' which exists at some higher scope. So every time you call the function you are just adding more and more children to the stackpanel.
You can solve the problem by doing something like this in the beginning of your method.
winMainContainerLeft.Clear();
winMainContainerRight.Clear();
winMainContainer.Children.Clear();
I also noticed that you have included the following lines in your example:
winMainContainer.Children.Remove(winMainContainerLeft);
winMainContainer.Children.Add(winMainContainerLeft);
winMainContainer.Children.Remove(winMainContainerRight);
winMainContainer.Children.Add(winMainContainerRight);
But you don't need to remove them before adding them (this doesn't really make sense anyway.)

Related

How to use buttons and textbox created dynamically

i made a program that create many dynamic panel on button "ADD". The thing is that the name of the dynamic panel that have been created is by this way:
pArr[counter].Name = "panel" + (panel0.Controls.Count + 1);
And so on, so i guess the 5th panel would be named "panel5" if I'm right.
I added some buttons and a Textbox in these dynamically created panels. I don't understand how to use them. I have read a lot of posts in here about it but as its the first time I'm working with this kind of dynamic panels, its hard for me to understand. I found a lot of examples that seems to answer the question but I'm still confused about the names, how to controls buttons and/or textbox.
Per example, how will I set an Event from a button clicked from the 7th panel? It is complicated.
This is my code:
private void btnAdd_Click(object sender, EventArgs e)
{
Color color = ColorTranslator.FromHtml("#f0f0f0");
Color color2 = ColorTranslator.FromHtml("#4285f4");
System.Random R = new System.Random();
Panel p = new Panel();
Label lbl = new Label();
TextBox text = new TextBox();
Button btn = new Button();
Button btn2 = new Button();
Button btn3 = new Button();
int x = 100;
int y = 10;
int x2 = 300;
int y2 = 10;
int x3 = 380;
int y3 = 10;
int x4 = 20;
int y4 = 13;
int x5 = 500;
int y5 = 10;
int counter = 0;
Panel[] pArr = new Panel[25];
pArr[counter] = p;
pArr[counter].Name = "panel" + (panel0.Controls.Count + 1);
pArr[counter].BackColor = color;
pArr[counter].Size = new Size(panel0.ClientSize.Width, 40);
pArr[counter].BorderStyle = BorderStyle.Fixed3D;
pArr[counter].Dock = DockStyle.Top;
lbl.Text = "Name";
lbl.ForeColor = color2;
lbl.Font = new Font("Verdana", lbl.Font.Size);
lbl.Size = new Size(75, 20);
lbl.Location = new Point(x4, y4);
pArr[counter].Controls.Add(lbl);
text.Name = "txtBox" + (panel0.Controls.Count + 1);
text.Size = new Size(120, 20);
text.Location = new Point(x, y);
pArr[counter].Controls.Add(text);
btn.Name = "btnStart" + (panel0.Controls.Count + 1);
btn.Text = "Start";
btn.Font = new Font("Verdana", btn2.Font.Size);
btn.ForeColor = color2;
btn.Size = new Size(75, 20);
btn.Location = new Point(x2, y2);
pArr[counter].Controls.Add(btn);
btn2.Name = "btnStop" + (panel0.Controls.Count + 1);
btn2.Text = "Stop";
btn2.Font = new Font("Verdana", btn2.Font.Size);
btn2.ForeColor = color2;
btn2.Size = new Size(75, 20);
btn2.Location = new Point(x3, y3);
pArr[counter].Controls.Add(btn2);
btn3.Name = "btnClose" + (panel0.Controls.Count + 1);
btn3.Text = "Close";
btn3.Font = new Font("Verdana", btn3.Font.Size);
btn3.ForeColor = color2;
btn3.Size = new Size(75, 20);
btn3.Location = new Point(x5, y5);
pArr[counter].Controls.Add(btn3);
panel0.Controls.Add(pArr[counter]);
panel0.AutoScroll = false;
panel0.HorizontalScroll.Enabled = false;
panel0.HorizontalScroll.Visible = false;
panel0.HorizontalScroll.Maximum = 0;
panel0.AutoScroll = true;
counter++;
}
Can someone explain me how to control panels/buttons/textbox?
Give this a go:
public partial class UserControl2 : UserControl
{
public UserControl2()
{
InitializeComponent();
}
private void btnAdd_Click(object sender, EventArgs e)
{
var color = ColorTranslator.FromHtml("#f0f0f0");
var color2 = ColorTranslator.FromHtml("#4285f4");
var r = new System.Random();
var p = new Panel();
var lbl = new Label();
var pnlTxtBox = new TextBox();
var pnlBtnStart = new Button();
var pnlBtnStop = new Button();
var pnlBtnClose = new Button();
p.Name = "panel" + (panel0.Controls.Count + 1);
p.BackColor = color;
p.Size = new Size(panel0.ClientSize.Width, 40);
p.BorderStyle = BorderStyle.Fixed3D;
p.Dock = DockStyle.Top;
lbl.Text = "Name";
lbl.ForeColor = color2;
lbl.Font = new Font("Verdana", lbl.Font.Size);
lbl.Size = new Size(75, 20);
lbl.Location = new Point(20, 13);
p.Controls.Add(lbl);
pnlTxtBox.Name = "txtBox";
pnlTxtBox.Size = new Size(120, 20);
pnlTxtBox.Location = new Point(100, 10);
p.Controls.Add(pnlTxtBox);
pnlBtnStart.Name = "btnStart";
pnlBtnStart.Text = "Start";
pnlBtnStart.Font = new Font("Verdana", pnlBtnStart.Font.Size);
pnlBtnStart.ForeColor = color2;
pnlBtnStart.Size = new Size(75, 20);
pnlBtnStart.Location = new Point(300, 10);
pnlBtnStart.Click += (s,e) => StartWasClicked(pnlTxtBox);
p.Controls.Add(pnlBtnStart);
pnlBtnStop.Name = "btnStop";
pnlBtnStop.Text = "Stop";
pnlBtnStop.Font = new Font("Verdana", pnlBtnStop.Font.Size);
pnlBtnStop.ForeColor = color2;
pnlBtnStop.Size = new Size(75, 20);
pnlBtnStop.Location = new Point(380, 10);
p.Controls.Add(pnlBtnStop);
pnlBtnClose.Name = "btnClose";
pnlBtnClose.Text = "Close";
pnlBtnClose.Font = new Font("Verdana", pnlBtnClose.Font.Size);
pnlBtnClose.ForeColor = color2;
pnlBtnClose.Size = new Size(75, 20);
pnlBtnClose.Location = new Point(500, 10);
pnlBtnClose.Click += (s,e) => CloseWasClicked(p);
p.Controls.Add(pnlBtnClose);
panel0.Controls.Add(p);
panel0.AutoScroll = false;
panel0.HorizontalScroll.Enabled = false;
panel0.HorizontalScroll.Visible = false;
panel0.HorizontalScroll.Maximum = 0;
panel0.AutoScroll = true;
}
void StartWasClicked(TextBox tb){
MessageBox.Show(tb.Text);
}
void CloseWasClicked(Panel p){
p.Visible = false;
}
}
pArr needs to be a member of the class, not a local variable. Then you can simply access pArr with an index like any other array.
The panel doesn't even need a name. Names are only useful in the Visual Studio designer so that it can generate the .Designer.cs file with a variable name.
As for the events, just add an event handler with btn.Click += OnStartClick; as you would do for a button normally. In the function declaration, you will get object sender which identifies the button. You can then use Array.IndexOf() MSDN to get the index.
private void OnStartClick(object sender, EventArgs e)
{
var button = (Button) sender;
var panel = button.Parent;
var index = Array.IndexOf(pArr, panel);
...
}
Hokay, so on a comment elsewhere you said you want to
MessageBox.Show("Button name pressed: " + buttonName + " panel position number: " + panelPositionNb)
It means minimally you can have a code that looks like: (the second to last line is new)
btn.Name = "btnStart" + (panel0.Controls.Count + 1);
btn.Text = "Start";
btn.Font = new Font("Verdana", btn2.Font.Size);
btn.ForeColor = color2;
btn.Size = new Size(75, 20);
btn.Location = new Point(x2, y2);
btn.Click += (s, e) => MessageBox.Show($"Button name pressed: {btn.Name}");
pArr[counter].Controls.Add(btn);
Taking this apart:
btn.Click += (s, e) => MessageBox.Show($"Button name pressed: {btn.Name}");
.Click is the event of the button. An event is simply a "list of methods that have a particular signature", and when you say += you add a method to the "list of methods that shall be called when the event is raised". There's no defined order; you can add multiple different methods and they will be called, but not necessarily in any particular sequence. Click has a type of EventHandler which sets out the number and type of arguments any method must have in order to qualify as an handler for any event that is shaped like an EventHandler
+= we've covered; if there is an event on the left, then the thing on the right must be a method with a particular signature (dictated by the event signature) i.e. in the case of a button your method on the right must be shaped like an EventHandler which means it must have a first argument of type object and a second argument of type EventArgs. Your btnAdd_Click is an example of a method that conforms to those rules
(s, e) is a method signature header. Specifically it's a mini method that we call a lambda. The compiler looks at the event signature and knows that the first thing has to be object and the second has to be EventArgs; you only have to give names - the compiler will fill in the types. Actually because we don't even use the names of the arguments in the method code, we could just write (_, _) (in .net core+; framework might complain about duplicate names) here which means "no name; throw it away".. But if we did use the variable in the lambda method we'd have to give it a name. We could give them types too: (object s, EventArgs e) and it starts to look a lot like a normal method if we do; we don't add these because mostly we don't need to; the compiler can usually figure them out on its own
=> is the thing that separates a lambda method signature from the body
MessageBox.Show($"Button name pressed: {btn.Name}") is the body of the method; the thing that will happen when the button is clicked.
Doing a panel close one:
btn3.Name = "btnClose" + (panel0.Controls.Count + 1);
btn3.Text = "Close";
btn3.Font = new Font("Verdana", btn3.Font.Size);
btn3.ForeColor = color2;
btn3.Size = new Size(75, 20);
btn3.Location = new Point(x5, y5);
var pnl = pArr[counter];
btn3.Click += (s,e) => pnl.Visible = false;
pnl.Controls.Add(btn3);
Here we take the panel and capture it into a temporary variable. There are specific reasons for doing this, and it doesn't exactly apply to your code as written but I'm assuming at some point you'll upgrade this to use a loop; if we just did pArr[counter].Visible C# would take the resting value of counter as it was after all the looping is done, and hide that panel.. Any button would either cause an error, because counter would be off the end of the panels array, or some other wrong panel would hide.
We don't have to use these mini-methods (lambdas); we can pass this data around another way if you like..
Taking the example of the panel hide, because it's actually doing something interesting with the UI. Let's have a method that hides a panel that it finds in the Tag of the control in the sender:
private void HidePanelInTag(object sender, EventArgs e){
//get the sender as a button; we will only ever attach this code to buttons that have a Panel in their Tag
var b = sender as Button;
//get the Tag from the button and cast it to a panel
var p = b.Tag as Panel;
p.Visible = false;
}
Now we can tweak the loop that is creating the btn3 close buttons:
btn3.Name = "btnClose" + (panel0.Controls.Count + 1);
btn3.Text = "Close";
btn3.Font = new Font("Verdana", btn3.Font.Size);
btn3.ForeColor = color2;
btn3.Size = new Size(75, 20);
btn3.Location = new Point(x5, y5);
btn3.Tag = pArr[counter];
btn3.Click += HidePanelInTag;
pnl.Controls.Add(btn3);
We've stored the panel in the Tag - this varies for every button, a different Panel. The event handler attachment looks simpler too, because whereas a lambda has a full method (header, and body) defined on the line it is encountered, in more old fashioned terms the method definition is separated from its use:
btn3.Click += HidePanelInTag;
Remember before we said += separates an event on the left, from a method on the right; so long as the method on the right obeys the signature of the event, we're allowed to "add it to the list of methods that are called when the event is raised".
When the button is clicked, HidePanelInTag is called. Windows Forms automatically puts the control that is raising the event (the button) into the object sender argument. That's how we retrieve the Panel to hide; every button has a different Panel in its tag. If you click the 25th button, the sender is the 25th button, and the Tag is the 25th panel
End of the day there are loads of ways to skin this cat. For example you don't have to store a panel in a button's Tag.. You could even do some crazy like this:
btn3.Click += (s, e) => {
var b = s as Button;
var pname = b.Name.Replace("btnClose", "panel");
var p = panel0.Controls[pname];
p.Visible = false;
};
Get the button name, change it to be what the panels name is, find the panel by name, hide it... All in a multi-line lambda. That's kinda nasty, just treat it "for educational purposes" - ultimately all these buttons you make end up stored in tree of controls (your form has a penal that has panels that have buttons..) that can be searched, so "name" does have a use.. But we probably wouldn't use it for this approach.
The main take-away from this is that just like setting the name, the text, the position etc dynamically you also need to wire up the click events dynamically. That's done using event_name_here += event_handler_method_name_without_parentheses_here; in this regard methods aren't really any different from data variables in the way they're passed around by name
Passing Methods Around Like We Pass Data
Edit, following on from a comment below
You're comfortable with Properties:
btn3.Name = "btnClose" + (panel0.Controls.Count + 1);
Events are nearly exactly the same:
btn3.Click += (s,e) => pnl.Visible = false;
Let's have a table:
Property, btn3.Name
Event, btn3.Click
receives a string
receives a method
set with =
set with +=
can receive any string you want, for example "btnClose" + (panel0.Controls.Count + 1)
can receive any method you want, so long as the method has two arguments: an object and an EventArgs, for example (s,e) => pnl.Visible = false
Once you're happy that the following two things are essentially both methods, one called GetTime, and one without a name (because it doesn't need one):
(n) => "Hello " + n + ", the time is " + DateTime.Now;
public string GetTime(string n){
return "Hello " + n + ", the time is " + DateTime.Now;
}
the only mental block you might have, that we need to unblock, is this idea of "passing methods around like we pass data around".
Methods typically produce data when you call them, so you're used to using a method to produce data and assign data:
btn3.Text = GetGermanTranslationFor("Close");
That will call the method GetGermanTranslationFor passing in "Close", and the method returns "Schließen", then "Schließen" will be set as the text - that was all "passing data around"
But suppose a button had a MethodToCallToGetTheText property where instead of setting the data, we set the method to call to get the data and then button will call that method itself:
btn3.MethodToCallToGetTheText = GetGermanTranslationFor
There is no ( after the method name here; we don't want to call the method ourselves.. We want to give the method to the button so the button can call it.
This is what events are intended to do; a way of saying "here, when the click happens, call this method I'm giving you".
Microsoft can write a Button but they can't know what text I will put on it, so they provide a Text property and I set it myself
Microsoft can write a Button but they can't know what what code I'll run when the user clicks it so they just provide a facility where they say "put a method here, with these certain parameters, and we'll call it when the user clicks"
As it happens, Microsoft decided that the "put a method here" should actually be "put one or more methods here", which is why we use += to wire them up (because events are like a list of methods that you add to) but other than that, the theory is the same as setting a property; passing methods round like data is very useful

How to store certain variable values in a dynamically added control

I have a button which I added programmatically and I want to store certain unique information with every button. I have saved the Name and Text but is there a way to store another string to access later. Below is the code for my button and it's click event.
for (int i = bankaccountsDatagridview.Rows.Count - 1; i >= 0; i--)
{
string buttonName = "individualDepartmentBtn-" + i;
FontAwesome.Sharp.IconButton individualDepartmentBtn = new FontAwesome.Sharp.IconButton();
individualDepartmentBtn.BackColor = System.Drawing.Color.White;
individualDepartmentBtn.Cursor = System.Windows.Forms.Cursors.Hand;
individualDepartmentBtn.Dock = System.Windows.Forms.DockStyle.Top;
individualDepartmentBtn.FlatAppearance.BorderSize = 0;
individualDepartmentBtn.FlatAppearance.MouseDownBackColor = System.Drawing.Color.Silver;
individualDepartmentBtn.FlatAppearance.MouseOverBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(224)))), ((int)(((byte)(224)))), ((int)(((byte)(224)))));
individualDepartmentBtn.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
individualDepartmentBtn.Flip = FontAwesome.Sharp.FlipOrientation.Normal;
individualDepartmentBtn.Font = new System.Drawing.Font("Roboto", 11.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
individualDepartmentBtn.ForeColor = System.Drawing.Color.DimGray;
individualDepartmentBtn.IconChar = FontAwesome.Sharp.IconChar.None;
individualDepartmentBtn.IconColor = System.Drawing.Color.DimGray;
individualDepartmentBtn.IconSize = 25;
individualDepartmentBtn.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
individualDepartmentBtn.Margin = new System.Windows.Forms.Padding(10);
individualDepartmentBtn.Padding = new System.Windows.Forms.Padding(30, 0, 0, 0);
individualDepartmentBtn.Name = bankaccountsDatagridview.Rows[i].Cells[1].Value.ToString();
individualDepartmentBtn.Rotation = 0D;
individualDepartmentBtn.Size = new System.Drawing.Size(192, 30);
individualDepartmentBtn.TabIndex = 1;
individualDepartmentBtn.Text = bankaccountsDatagridview.Rows[i].Cells[1].Value.ToString();
individualDepartmentBtn.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
individualDepartmentBtn.UseVisualStyleBackColor = false;
navigationPanel.Controls.Add(individualDepartmentBtn);
individualDepartmentBtn.MouseDown += new System.Windows.Forms.MouseEventHandler(individualBankBtnDown);
}
Click Event:
private void individualBankBtnDown(object sender, MouseEventArgs e)
{
bankTitle = ((FontAwesome.Sharp.IconButton)sender).Name.ToString();
}
You can use the Tag property. For example:
individualDepartmentBtn.Tag = "My String";
You can store any object within Tag and not only strings.
Note that you could also use the var keyword and an object initializer to make your code a little bit more readable:
var individualDepartmentBtn = new FontAwesome.Sharp.IconButton
{
BackColor = System.Drawing.Color.White,
Cursor = System.Windows.Forms.Cursors.Hand,
Dock = System.Windows.Forms.DockStyle.Top,
...
};

Dynamically created c# label not visible

I'm attempting to display some dynamically generated labels next to dynamically generated text boxes. The text boxes appear but the labels do not.
I've looked at several solutions and have tried to make sure I defined all the label properties. I looked at some threading related solution that seem unnecessary because i'm not changing visibility state, I would just like to pop up the labels next to the text boxes.
TextBox[] channelNames = new TextBox[numOfChannels];
GroupBox channelBox = new GroupBox();
Label[] labelNames = new Label[numOfChannels];
for (int currentChannelIndex = 0; currentChannelIndex < numOfChannels; currentChannelIndex++)
{
var txt = new TextBox();
channelNames[currentChannelIndex] = txt;
txt.Name = channelCollection[currentChannelIndex].PhysicalName;
txt.Text = "ben";
txt.Location = new Point(200, 32 + (currentChannelIndex * 28));
txt.Visible = true;
this.channelBox.Controls.Add(channelNames[currentChannelIndex]);
var lbl = new Label();
labelNames[currentChannelIndex] = lbl;
lbl.AutoSize = true;
lbl.Name = channelCollection[currentChannelIndex].PhysicalName;
lbl.Size = new Size(55, 13);
lbl.TabIndex = 69;
lbl.Text = channelCollection[currentChannelIndex].PhysicalName;
lbl.Location = new Point(175, 32 + (currentChannelIndex * 28));
lbl.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.channelBox.Controls.Add(labelNames[currentChannelIndex]);
}
Here are a few things to check:
1) You are setting "AutoSize" and "Size". Trying removing "Size"
2) The default font is likely too large for the (55,13) size.
Try explicitly setting the font to something small to see if it shows up.
Does channelCollection[currentChannelIndex].PhysicalName actually contain a non-Empty string? e.g.:
class Something
{
public string PhysicalName { get; set; }
}
private void AddLabels()
{
Something[] channelCollection = new Something[]
{
//Applying this to Label.Text makes it "invisible"
new Something() { PhysicalName = "" }
};
var currentChannelIndex = 0;
var txt = new TextBox();
txt.Name = channelCollection[currentChannelIndex].PhysicalName;
txt.Text = "ben";
txt.Location = new Point(200, 32);
txt.Visible = true;
this.Controls.Add(txt);
var lbl = new Label();
lbl.AutoSize = true;
lbl.Name = channelCollection[currentChannelIndex].PhysicalName;
lbl.Size = new Size(55, 13);
lbl.TabIndex = 69;
lbl.Text = channelCollection[currentChannelIndex].PhysicalName;
lbl.Location = new Point(175, 32);
lbl.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.Controls.Add(lbl);
}
I actually had an exception that downstream of this code block that was causing the issue. I assumed that i would see the labels since the exception was thrown after the call to the label. Thanks for your suggestions.

What's happening to my label?

Ok so I have this code to create controls on my form:
public CableID_DuplicateView(CableID_CreateView CView)
{
InitializeComponent();
Label lbl = new Label();
Button btn = new Button();
ComboBox cmb = new ComboBox();
TextBox txt = new TextBox();
if (CView.input == 1)
{
lbl.Text = "Please select a cable number to duplicate:";
lbl.Location = new Point(12, 9);
cmb.Location = new Point((lbl.Width + 17), 6);
cmb.Size = new System.Drawing.Size(125, 20);
btn.Location = new Point((lbl.Width + cmb.Width + 17), 5);
btn.Size = new System.Drawing.Size(90, 23);
btn.Text = "Add to Table";
this.Height = cmb.Height + 48;
this.Width = lbl.Width + cmb.Width + btn.Width + 34;
this.Controls.Add(lbl);
this.Controls.Add(cmb);
this.Controls.Add(btn);
}
}
Which produces this:
What is causing my label to get cut off like that? And why is the comboBox sitting in a strange location?
What is happening here is that label.width is 100 which is not covering the whole text do this instead:
lbl.Text = "Please select a cable number to duplicate:";
lbl.Location = new Point(12, 9);
lbl.Width = 200;
You can also do this:
lbl.AutoSize = true;
Try this to set AutoSize width Property:
lbl.Text = "Please select a cable number to duplicate:";
lbl.Location = new Point(12, 9);
lbl.AutoSize = true;
this.Controls.Add(lbl);
Width property will not be set until the control has been added to the parent container.
Problem : You didn't set Width for your Label Control.so it takes some default width for your Label
Solution: You need to set Width for your Label
Try This:
lbl.Size = new System.Drawing.Size(200, 20); //width = 200, height = 20
As others said the width for the label is too short.
Solution 1: Set the width to a larger fixed width:
lbl.Width = 200;
Solution 2: Set AutoSize to true:
lbl.AutoSize = true;
Solution 3: Combine a fixed width with the AutoEllipsis property:
lbl.Width = 100;
lbl.AutoEllipsis = true;
When using AutoEllipsis the label remains the set width,
but the shown text is followed by three dots to indicate that not all text is shown.

Cannot access dynamic controls

I have some trouble when i'm trying to click my dynamic controls in StackPanel.
I'm adding controls to Grid in this way...
void Opt()
{
TextBlock Title_1 = new TextBlock();
TextBlock Title_2 = new TextBlock();
CheckBox Kwota_exists = new CheckBox();
TextBox Title = new TextBox();
StackPanel Frame = new StackPanel();
Button OK = new Button();
Title_1.Text = "Dodaj kategorię";
Title_2.Text = "Aktywne kategorię";
Kwota_exists.Content = "Stała kwota?";
Title.Text = "Nazwa kategorii";
OK.Content = "Dodaj";
OK.IsEnabled = true;
OK.IsHitTestVisible = true;
OK.IsTabStop = true;
OK.ClickMode = ClickMode.Release;
Frame.IsHitTestVisible = true;
Kwota_exists.Checked +=Kwota_exists_Checked;
Title_1.FontSize = 50;
Title_2.FontSize = 50;
Title.FontSize = 20;
Frame.Height = 100;
Frame.Width = 400;
Title_1.Margin = new Thickness(0, 0, 0, 0);
Title_2.Margin = new Thickness(0, 220, 0, 0);
Frame.Margin = new Thickness(0, 70, 0, 0);
Frame.HorizontalAlignment = Windows.UI.Xaml.HorizontalAlignment.Left;
Frame.VerticalAlignment = Windows.UI.Xaml.VerticalAlignment.Top;
Frame.Orientation = Orientation.Horizontal;
Frame.Background = new SolidColorBrush(Windows.UI.Color.FromArgb(145, 56, 234, 21));
Frame.Children.Add(Kwota_exists);
Frame.Children.Add(Title);
Frame.Children.Add(OK);
GrdContent.Children.Add(Frame);
GrdContent.Children.Add(Title_1);
GrdContent.Children.Add(Title_2);
}
But when i'm trying to click button or check checkbox controls doesn't seem to response (unclickable).
Looks like i can't access them or i'm doing something wrong. I would be gradefull if someone explain me where i'm doing mistake.

Categories

Resources