C# Label not visible in GroupBox - c#

I have a loop that is supposed to go through DataTable and for each row create a new GroupBox, set it's text to value from one column, in that GroupBox I want to put a Label with Text similar to another column in the table.
This is just part of the code!
for (int i = 0; i < tab.Rows.Count; i++)
{
lblbox[i] = new GroupBox();
lblbox[i].Text = tab.Rows[i]["text"].ToString();
lblbox[i].Name = "box no " + i.ToString();
lblbox[i].Visible = true;
this.Controls.Add(lblbox[i]);
lblbox[i].Location = new Point(5, 55 * i);
lblbox[i].Height = 50;
lblbox[i].SendToBack();
importancelbl[i] = new Label();
importancelbl[i].Text = "Importance: " + tab.Rows[i]["importance"].ToString();
importancelbl[i].Name = "implbl" + i.ToString();
importancelbl[i].Visible = true;
lblbox[i].Controls.Add(importancelbl[i]);
importancelbl[i].BringToFront();
Point locP = new Point();
locP.X = lblbox[i].Location.X + 5;
locP.Y = lblbox[i].Location.Y + 15;
importancelbl[i].Location = locP;
}
When i run the code it creates three (I have three rows in my table) GroupBoxes correctly and creates all the labels, but only first label is visible in its Groupbox. When I add those labels to the Form and not to the GroupBox, all of them are visible, but I want them to be in boxes...
I've tried pretty much everything and I'm still very confused (espacially by the behavior of the first label). I know the mistake is probably obvious and stupid, but I just can't find it!

Control.Location is relative to its parent, so set Location for the label to (5, 15).
locP.X = 5;
locP.Y = 15;

My guess is that they are somehow overlapping and making each other disappear somehow.
Could you try posting pictures of the form when it works and when it doesn't? Also add all your code?

Try to preform adding
lblbox[i].Controls.Add(importancelbl[i]);
this.Controls.Add(lblbox[i]);
after setting all your properties

Related

Dynamic button-C#

i have buttons this buttons for categories i want when click in this buttons i want to get rows from database products table and get two data product name and price and set it those values into dynamic buttons in windows application notes i have set location properities for button such like flowLayoutPanel
i have this code
private void btnhotdrink_Click_1(object sender, EventArgs e)
{
//int StartPositition = 100;
//int EndPosition = 10;
DataTable dt = new DataTable();
dt =clsprdcat.GET_HOTDRINK_CATEGORY();
for(int i=0; i < dt.Rows.Count; i++)
{
for (int s=0; s < dt.Columns[4]; s++)
{
Button l = addbuttons(i,s);
flowLayoutPanel1.Controls.Add(l);
//EndPosition +=70;
}
}
}
Button addbuttons(int i)
{
Button l = new Button();
l.Name = "Name" + l.ToString();
l.Text = "label" + l.ToString();
l.ForeColor = Color.White;
l.BackColor = Color.Green;
l.Font = new Font("Serif", 24, FontStyle.Bold);
l.Width = 170;
l.Height = 80;
//l.Location = new Point(start, end);
l.TextAlign = ContentAlignment.MiddleCenter;
l.Margin = new Padding(5);
return l;
}
How Can i Do this
All Buttons are inherently dynamically created at runtime. The Windows Forms Designer works via partial classes: You work on one part. The designer on the other (designer.cs). And at compile time the Designers code is executed by calling "InitializeComponents()" in the Constructor. It can only do exactly the same things you can do.
If you need help with creating buttons yourself, you can always look into the Designer part. Just do take care not to change anything in that part. This System only works because the designer is exclusively writing in the file and compilation/loading of a Project is prone to seizing up if you did manual changes.
As you wrote it right now, this code will create dt.Rows.Count buttons at the same locaiton. Usually the Button creation code it needs access to the loop variable, to adapt the positions of each consequtive element.. Personally I prefer to leave positioning of Elements as much to automatics as possible. These designs simply adapt better to changes in resolution and window size.

Dinamically generate a button to open file dialog and select a file using WPF controls and C#

Basically I'm making a program that allows you to add to a stackpanel another stackpanel with several horizontally aligned textboxes with the press of a button. So far, everything is working as intented. Here's my code so far ,Stacker is the name of the parent stackpanel and it starts off empty:
private void Add_Click(object sender, RoutedEventArgs e)
{
Stacker.Children.Add(NewXD(Stacker.Children.Count + 1));
}
public System.Windows.Controls.StackPanel NewXD(int XD)
{
System.Windows.Controls.StackPanel NewP = new StackPanel();
NewP.Orientation = Orientation.Horizontal;
System.Windows.Controls.TextBox HAHA = new TextBox();
HAHA.Name = "question" + XD.ToString();
//HAHA.Text = HAHA.Height.ToString()+" "+HAHA.Width.ToString();
HAHA.Height = Double.NaN;
HAHA.Width = 120;
HAHA.FontSize=20;
NewP.Children.Add(HAHA);
for (int i = 1; i < 6; i++)
{
System.Windows.Controls.TextBox newBox = new TextBox();
newBox.Name = "answer"+XD.ToString()+"_"+i.ToString();
newBox.Height = Double.NaN;
newBox.Width = 120;
NewP.Children.Add(newBox);
}
System.Windows.Controls.ComboBox correct = new ComboBox();
correct.Name = "correct" + XD.ToString();
for (int i = 1; i < 6; i++)
{
System.Windows.Controls.ComboBoxItem newItem = new ComboBoxItem();
newItem.Name = "ans" + XD.ToString() + "_" + i.ToString();
newItem.Content = i.ToString();
correct.Items.Add(newItem);
}
NewP.Children.Add(correct);
return NewP;
}
I apologize for the lack of seriousness in some of my code.
Now, what I need to do is for the child stackpanels to also contain independent file pickers that work like the one sampled in this thread: Open file dialog and select a file using WPF controls and C#
What I don't know how to perform is that each of these generated buttons have the same basic funcion but are linked with each of their corresponding textbox.
Thanks in advance :)
Edit: As I was writing this it occured to me that perhaps I could use the help of the child stackpanel's array-like properties to choose the corresponding textbox, because the file selector's textbox and button will always be the last two items in the stackpanel, but I'm not very sure how to perform this.
For functionality you can create an EventHandler that will be assigned to each button. Your event handler will then open File Dialog...
Buttons have Tag property which you could use to identify your TextBoxes, or you could derive from Button class and add AssociatedTextBox property for example.

Dynamically added labels disappear in runtime

I add labels to my form programmatically, but they disappear, except last one. I'm sure that given location to them is appropriate. But when the second label appears, first disappears, or when third label appears, second disappears.
Here is my code:
Label[] lenlab = new Label[255];
Label lab = new Label();
lab.Font = new Font("Microsoft Sans Serif", 10, FontStyle.Bold);
lab.ForeColor = Color.White;
lab.BackColor = Color.Transparent;
lab.AutoSize = true;
lenlab[1] = lab;
lenlab[1].Location = new Point(50, panel1.Location.Y + panel1.Height + 20);
lenlab[1].Text = c[1];
this.Controls.Add(lenlab[1]);
for (int i = 2; i < c.Count; i++)
{
lenlab[i] = lab;
lenlab[i].Location = new Point(lenlab[i - 1].Location.X + lenlab[i -1].Width + 40, lenlab[i - 1].Location.Y);
lenlab[i].Text = " + " + c[i];
this.Controls.Add(lenlab[i]);
}
This line is causing every position in your array to have a reference to the same Label you created originally, outside the loop, which means all you're doing is changing the position and text of the same Label inside your loop.
lenlab[i] = lab;
The behavior you're seeing is due to the fact that you can only add a particular control to this.Controls once, so the effect is that you see the same label changing position.
Here's the portion of the Add() method that checks whether the control you're adding already has a parent, and if it does, then it removes it from it's current parent before adding it to the new one. So every time you call this.Controls.Add() with the same Label, it removes it from the Form and then adds it again.
// Remove the new control from its old parent (if any)
if (value.parent != null) {
value.parent.Controls.Remove(value);
}
Instead, create a new Label inside your for loop:
lenlab[i] = new Label();
There are controls that can help you layout controls without the need to calculate a new position each time. In particular, read up on the FlowLayoutPanel and TableLayoutPanel classes.
What you are doing there is basically create one Label, change it several times, and attach it several times to the page. What you end up having on the page is the last version of the Label being added once, which is the expected behavior.
If you want to add several labels, you need to new each of them.

dynamically created radio buttons not displaying

I have an application in which there are several tabs. One of those creates several group boxes and in each of these group boxes I need 10 radio buttons ranging from 1-10. My problem is that I cannot get the radio button to show up and work properly. When I create them if I add them to the current tabs controls all the radio buttons will display but the winform treats them all as one set of radio.
I need the radio buttons in each groupbox to be a set. If I add the buttons to the groupbox the radio buttons will not display. I have played around with the order in which I add the radio button to the groupbox, call the radio buttons show() method, add the groupbox to the tabs control, and call the groupbox's show() method but no matter what configuration I try these in I can't seem to get the radio buttons to display. I also tried to change the childIndex of the radio button but that didn't work either.
Some of you may suggest to just use a drop down or upDownNumaric but I actually have the UpDownNumaric working but the customer wants it changed to a set of radio buttons. The code I currently have:
groupBoxLocation.Y += 45;
GroupBox newGroupBox = new GroupBox();
newGroupBox.Location = groupBoxLocation;
newGroupBox.Text = reader["Description"].ToString().Trim();
newGroupBox.Size = new Size(425, 40);
newGroupBox.Name = ("PS_L_" + newGroupBox.Text).Replace(" ", "").Trim();
RadioButton rateValue;
radioButtonsLocation = new Point(newGroupBox.Location.X - 30, newGroupBox.Location.Y + 15);
tabControl1.TabPages[3].Controls.Add(newGroupBox);
newGroupBox.Show();
for (int i = 0; i < 10; ++i)
{
rateValue = new RadioButton();
radioButtonsLocation = new Point(radioButtonsLocation.X + 41, radioButtonsLocation.Y);
rateValue.Location = radioButtonsLocation;
rateValue.Text = (i + 1).ToString().Trim();
rateValue.Width = 40;
rateValue.Name = "PI_V_" + newGroupBox.Text.Replace(" ", "") + "_" + i;
newGroupBox.Controls.Add(rateValue);
newGroupBox.Controls[rateValue.Name].Show();
}
The problem is your initialization of the radioButtonsLocation. The locations are relative to their parent, not relative to the root container, so try changing
radioButtonsLocation = new Point(newGroupBox.Location.X - 30, newGroupBox.Location.Y + 15);
to
radioButtonsLocation = new Point(0,10);
or some similar point based on how you would like your UI to look.

LayoutGrid SetRow and SetColumn not working as intended

I have code that creates a button for each object in a list. When each object is created it is given a name that corresponds to the row and column (i.e. name = row1col2). Each button is generated dynamically, added to the grid and then the row/column are set. At a later time I need to gather the "selected" button data so I can perform actions on the data they represent. When I attempt to get the control data from the buttons everything is fine, except for the grid row/column data. It remains the same for all of the selected rows and columns in a grid.
Creating buttons:
for (int i = 1; i < row.StackCount+1; i++)
{
//create button for the column
stackButton = new Button();
stackButton.Height = ((newRow.Height - 2));
stackButton.Width = ((newRow.Width / row.StackCount) - 2);
stackButton.Background = new SolidColorBrush(Colors.White);
//add the button border
stackButton.BorderBrush = new SolidColorBrush(Colors.Black);
stackButton.BorderThickness = new Thickness(1);
stackButton.Style = Application.Current.Resources["flatButton"] as Style;
//add the button name
stackButton.Name = "Row" + row.LineNumber + "Col" + (i - 1).ToString();
//add the event handler to the button
stackButton.Click += new RoutedEventHandler(stackButton_Click);
//add a new column
newRow.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(newRow.Width, GridUnitType.Star) });
//put the button into the grid
newRow.Children.Add(stackButton);
Grid.SetRow(stackButton, 0);
Grid.SetColumn(stackButton, i-1);
}
Getting the Button data back
g = (Grid)b.Child;
foreach (Button currentButton in g.Children)
{
if (((SolidColorBrush)currentButton.Background).Color == Colors.Gray)
{
//create a stack object
buttonData.StartDate = DateTime.Now;
buttonData.LotNumber = LotDisplay.Text;
buttonData.RoomID = SilverGlobals.CurrentRoom.RoomID;
buttonData.RoomCol = Grid.GetColumn(currentButton);
buttonData.RoomRow = Grid.GetRow(currentButton);
buttonData.TrayCount = int.Parse(currentButton.Content.ToString());
buttonData.Status = 0;
//add stack object to list of stack objects
stacks.Add(buttonData);
}
}
I know this must be something small I am missing. Anyone got any ideas?
Although the comment in your second section of code says:
//create a stack object
you don't actually create a new stack object so it is simply overwriting the single instance of buttonData on each iteration. The values for row and column that you see at the end are the last iteration's values.
The net effect is that stacks is a collection of all the same instance of an object instead of a collection of separate instances.
This is just a shot in the dark, but based on this question and this question, it might be that you need to set the Row and Column properties before you add the button to its parent - something like this:
//put the button into the grid
Grid.SetRow(stackButton, 0);
Grid.SetColumn(stackButton, i-1);
newRow.Children.Add(stackButton);

Categories