Adding controls to GroupBox during runtime - c#

I'm trying to create a GroupBox, add a Grid (or StackPanel) to it then put some TextBlocks on it, all during runtime. This is what i've tried
GroupBox groupBox1 = new GroupBox();
Grid grid1 = new Grid();
groupBox1.Width = 85;
groupBox1.Height = 60;
grid1.Height = 85;
grid1.Width = 60;
groupBox1.Content = grid1.Children.Add(textBlock1);
groupBox1.Margin = new Thickness(50, 50, 0, 0);
mainWindow.canvas.Children.Add(groupBox1);
But all I get is a groupbox with a thick white border with nothing in it.

As far as I can see a Grid.Children.Add returns an int and that's not what you want to set the content of the groupBox1 to.
An untested idea from me as a non WPF expert is to set the grid as the Content of your groupbox.
grid1.Children.Add(textBlock1);
groupBox1.Content = grid1;

For simple checkboxes i used this code :
var container = new FlowLayoutPanel
{
FlowDirection = FlowDirection.TopDown,
Dock = DockStyle.Fill
};
myGroupBox.Controls.Add(container);
foreach (var myText in textList)
{
var checkBox = new CheckBox
{
Text = myText
};
container.Controls.Add(checkBox);
}
Of course the foreach statement is just for the example :)

Related

Create GroupBox and labels inside it programmatically

I want to create a groupbox programmatically and inside it put labels. Now I created this but with design and I have like this:
I'm trying but I don't know how can I assign labels in correct position and how can I assign it to a specific group box
GroupBox groupBox1 = new GroupBox();
Panel grid1 = new Panel();
Label lbl1 = new Label { Text = "Completed" };
Label lbl2 = new Label { Text = "label" };
Label lbl3 = new Label { Text = "In progress" };
Label lbl4 = new Label { Text = "label" };
//etcetera
groupBox1.Width = 185;
groupBox1.Height = 160;
grid1.Height = 185;
grid1.Width = 160;
How can I achieve that? Regards
Update
As the comments below I try
GroupBox groupBox1 = new GroupBox();
this.Controls.Add(groupBox1);
Panel grid1 = new Panel();
groupBox1.Controls.Add(grid1);
groupBox1.Location = new Point(20, 250);
grid1.Location = new Point(20, 250);
Label lbl1 = new Label { Text = "test" };
Label lbl2 = new Label { Text = "Test2" };
groupBox1.Name = "TESTTT";
groupBox1.Width = 222;
groupBox1.Height = 149;
grid1.Height = 218;
grid1.Width = 145;
grid1.Controls.Add(lbl1);
grid1.Controls.Add(lbl2);
Result:
But my group box it just clear without name and without labels, why it happen?
Controls in WinForms are arranged so that they reside inside one another. So your Form has a Controls collection which is essentially a Collection of type Control. So if you add a GroupBox to the form, then you must add it to the Controls collection of the form. Then if you add a control to your GroupBox then you need to add it to the GroupBox collection of controls.
With that in mind, you can do something like this:
private void AddGroupBoxAndLables()
{
GroupBox groupBox1 = new GroupBox();
groupBox1.SetBounds(50, 50, 300, 200);
this.Controls.Add(groupBox1);
Label lblCompleted = new Label { Name = "lblCompleted", Text = "Completed" };
lblCompleted.Location = new Point(20, 20);
groupBox1.Controls.Add(lblCompleted);
Label valCompleted = new Label { Name = "valCompleted" };
valCompleted.Location = new Point(80, 20);
groupBox1.Controls.Add(valCompleted);
Label lblInProgress = new Label { Name = "lblInProgress", Text = "In Progress" };
lblInProgress.Location = new Point(20, 60);
groupBox1.Controls.Add(lblInProgress);
Label valInProgress = new Label { Name = "valInProgress" };
valInProgress.Location = new Point(80, 60);
groupBox1.Controls.Add(valInProgress);
}
simplest way for solution is that your code is already created when you did design. Code is created automatically in respective form's designer.cs or designer.vb file. To see this file, in solution explorer click on button 'Show all files'. Still for your understanding let me explain code
You have created groupbox using
GroupBox groupBox1 = new GroupBox();
To see this group box on form you need to add this groupbox to form
this.Controls.Add(groupBox1);
Similar in case of panel. If you want to add panel inside of groupbox then
groupbox1.Controls.Add(grid1);
Then add all labels inside of panel.
You will find similar kind of code in form's designer.cs.

How do I set event methods for programmatically created combo boxes?

I am creating small program that has dynamically created combo boxes. Each time the user opens the program, based on some context, there could be 3-30 items that need 4 drop down lists for selection. I am creating these based off of the following code, which is just a snippet.
for (int i = 0; i < 4; i++)
{
s.Children.Add(new ComboBox()
{
VerticalAlignment = VerticalAlignment.Top,
HorizontalAlignment = HorizontalAlignment.Left,
Margin = new Thickness(m, -25, 0, 0),
Width = 75,
Height = 25,
FontSize = 12,
Name = "obj1_" + i.ToString(),
ItemsSource = objs,
});
m = m + 50;
s.Children.Add(new Label()
{
VerticalAlignment = VerticalAlignment.Top,
HorizontalAlignment = HorizontalAlignment.Left,
Margin = new Thickness(m, -25, 0, 0),
Width = 25,
Height = 25,
FontSize = 12,
Name = "lbl1_" + i.ToString(),
});
}
s is a stack panel that I am adding each of the combo boxes too. The ItemSource is from a small method elsewhere to figure out which list should go into the drop down.
My question is, how do I call the events for these created combo boxes? Trying
private void obj1_1_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
ComboBox this_box = (ComboBox)sender;
lbl1_1.Content = "!!!";
}
works well enough but the label doesn't exist in the current context.
Also, am I creating the boxes and labels the best way for this type of scenario?
Thanks in advance.
Inside you for loop
1)Create an new Panel
2)Add the label and combo to that panel
3)Add the newly created panel to s
Inside your obj1_1_SelectionChanged event:
1)Find the Parent control of the ComboBox
2)Search for the label inside its Children and update its text
Solution 2
When you create your controls create a Guid (or an int) and set the Tag property of your controls to that object.
Now when you are on a combo you can search your Window for the label with the same Tag
for (int i = 0; i < 4; i++)
{
Guid g = Guid.NewGuid();
s.Children.Add(new ComboBox()
{
Tag = g
});
s.Children.Add(new Label()
{
Tag = g
});
}

WPF grid cells in C# no text

I need to show some data in a structured way with colored letters and rows with background colors.
I made a grid in a WPF Window. It shows the textboxes and some of the labels, but none of the text. Also the column header, last column, gridseperators, grid bot and left edges are invisible.
My grid is called propertiesView.
Code for adding header elements (labels)
private void AddHeaderElement(string text, int row, int col)
{
Label headerElement = new Label();
headerElement.Height = cellHeight;
headerElement.Width = cellWidth;
headerElement.DataContext = text;
headerElement.Background = headerBackground;
headerElement.BorderBrush = new SolidColorBrush(Color.FromRgb(120, 120, 120));
headerElement.BorderThickness = new Thickness(3);
propertiesView.Children.Add(headerElement);
Grid.SetRow(headerElement, row);
Grid.SetColumn(headerElement, col);
}
Code for adding cells
RichTextBox cell = new RichTextBox();
cell.Height = cellHeight;
cell.Width = cellWidth;
cell.ToolTip = toolTip;
cell.DataContext = text;
cell.Background = rowDifferent;
propertiesView.Children.Add(cell);
//box.SetValue(Grid.RowProperty, rowCount);
//box.SetValue(Grid.ColumnProperty, columnCount);
Grid.SetRow(cell, rowCount);
Grid.SetColumn(cell, columnCount);
Code for adding grid seperators
GridSplitter colSeperator = new GridSplitter();
colSeperator.Margin = new Thickness(-2.5, 0, 0, 0);
colSeperator.Width = 5;
colSeperator.ResizeDirection = GridResizeDirection.Columns;
colSeperator.ResizeBehavior = GridResizeBehavior.CurrentAndNext;
colSeperator.VerticalAlignment = VerticalAlignment.Stretch;
colSeperator.HorizontalAlignment = HorizontalAlignment.Left;
propertiesView.Children.Add(colSeperator);
Grid.SetColumn(colSeperator, 0);
Grid.SetRowSpan(colSeperator, totalRows + 1);
The tooltips do show the right text.
I tried using TextBox instead of RichTextBox and setting all this stuff in the class constructor instead of a seperate method.
Well it seems like you just never set the Content dependency property on your labels, or the Document of your RichTextBoxes.
For your labels, as you set the text parameter as the DataContext, you can just add something like
headerElement.SetBinding(Label.ContentProperty, new Binding());
Turns out I needed labels with textblocks, spans and runs.
Style can be added on the span (through properties like Foreground, TextDecoration or FontWeight). Add the text to the span inside a Run, then add all spans to a textblock, which is shown through a label.
Span span = new Span();
span.Foreground = Brushes.Black;
span.Inlines.Add(new Run("Text"));
textBlock.Inlines.Add(span);
Label cell = new Label();
cell.MinHeight = cellHeight;
cell.MaxWidth = cellWidth * 3;
cell.MinWidth = cellWidth;
cell.ToolTip = "toolTip";
cell.BorderThickness = new Thickness(2);
TextBlock cellText = new TextBlock();
cellText.HorizontalAlignment = HorizontalAlignment.Stretch;
cellText.TextWrapping = TextWrapping.WrapWithOverflow;
cell.Content = cellText;
The text works now, I should be able to get the gridseperators working.

Add Controls to GroupBox which was created dynamically

I add GroupBoxes to an ItemsControl dynamically using:
string name_ = "TestName", header_ = "TestHeader"
GroupBox MyGroupBox = new GroupBox { Name = name_, Header= header_, Width = 240, Height = 150, Foreground=new SolidColorBrush(Color.FromArgb(255, 0, 0, 0)) };
MyItemsControl.Items.Add(MyGroupBox);
Now I need to add content to this GroupBox, like a few TextBlocks created like:
TextBlock MyTextBlock = new TextBlock {Text = "test"};
But I can't figure out how to do that. Normally to a Grid or something like that I would just use .Children.Add(MyTextBlock), but that doesn't work here.
Also I have to be able to remove specific Items from the ItemsControl again (best would be by the name of the Item, name_ in this example).
Try something like that
GroupBox groupBox1 = new GroupBox();
Grid grid1 = new Grid();
TextBlock MyTextBlock = new TextBlock {Text = "test"};
groupBox1.Width = 185;
groupBox1.Height = 160;
grid1.Height = 185;
grid1.Width = 160;
grid1.Children.Add(MyTextBlock);
groupBox1.Content = grid1;
mainWindow.canvas.Children.Add(groupBox1);
The GroupBox has only a Content Property which is designed to hold a ContentPresentor. You can add a Grid/Canvas etc.. to the GroupBox and then add your content to that.

setting DockStyle.Fill for dynamic controls does not resize when i move the splitter

I have a split container on panel 1 I have added a groupbox, in that groupbox is a flowcontrol which has dynamic number of textboxes, i have set both the groupbox and flowcontrol to dockstyle to fill.
In code i have also set the textboxes to dock style to fill, but they wont resize when i move the splitter, while the parent flowcontrol does resize.
Label labelInput = new Label();
TextBox listBoxNewInput = new TextBox();
listBoxNewInput.Name = ce.ToString();
labelInput.AutoSize = true;
labelInput.Font = new Font(labelInput.Font, FontStyle.Bold);
listBoxNewInput.Multiline = true;
// Add vertical scroll bars to the TextBox control.
listBoxNewInput.ScrollBars = ScrollBars.Vertical;
// Allow the RETURN key in the TextBox control.
listBoxNewInput.AcceptsReturn = true;
// Allow the TAB key to be entered in the TextBox control.
listBoxNewInput.AcceptsTab = true;
// Set WordWrap to true to allow text to wrap to the next line.
listBoxNewInput.WordWrap = true;
listBoxNewInput.Text = ts.ToString();
//listBoxNewInput.Width = 150;
listBoxNewInput.MinimumSize = new Size(200,150);
listBoxNewInput.MaximumSize = new Size(1000, 150);
listBoxNewInput.Dock = DockStyle.Fill;
listBoxNewInput.TextChanged += new EventHandler(listBoxNewInput_TextChanged);
//Add the newly created text box to the list of input text boxes
inputTextBoxesList.Add(listBoxNewInput);
//Add the labels and text box to the form
flowLayoutPanel1.Controls.Add(labelInput);
flowLayoutPanel1.Controls.Add(listBoxNewInput);
if i try to put controls directly in to spliter panel 1 only the first two controls appear, which do resize when i move the splitter
splitContainer1.Panel1.Controls.Add(labelInput); splitContainer1.Panel1.Controls.Add(listBoxNewInput);
->if the controls when i put them in flow control resize, when i move the splitter that would be good
OR
->All controls appear when i put them directly into the splitter panel 1
Based on your comments and what I think you are trying to accomplish, I think you need to replace the FlowLayoutPanel with a TableLayoutPanel because it sounds like you are just stacking one TextBox below another.
Create a TableLayoutPanel with 1 column and 1 row.
Here is a working example:
tableLayoutPanel1.AutoScroll = true;
tableLayoutPanel1.GrowStyle = TableLayoutPanelGrowStyle.AddRows;
tableLayoutPanel1.RowStyles.Clear();
tableLayoutPanel1.RowStyles.Add(new RowStyle(SizeType.Absolute, 150));
for (int i = 0; i < 4; i++) {
AddTextBox("TextBox #" + i.ToString());
}
private void AddTextBox(string info) {
TextBox tx = new TextBox();
tx.Multiline = true;
tx.Text = info;
tx.ScrollBars = ScrollBars.Vertical;
tx.WordWrap = true;
tx.Height = 150;
tx.Anchor = AnchorStyles.Left | AnchorStyles.Top | AnchorStyles.Right;
tableLayoutPanel1.Controls.Add(tx);
}
Instead of docking, I set the height of the TextBox and then I set the Anchors so that when the SplitPanel resizes, the TextBoxes resize appropriately.

Categories

Resources