C# - Dynamically creating and moving picturebox - c#

Okay so I'm trying to attempt to move a button around on a form. I use the following codes to call the button:
i++;
Button button = new Button();
button.Location = new Point(160, 30 * i + 10);
button.Click += new EventHandler(b_Click);
button.Tag = i;
panel1.Controls.Add(button);
I'm able to click each button and get a Messagebox showing their tag but I want to use their tag as a way to move the buttons around with a timer.

Assuming this is WinForms, you can use a Linq query on the Form Controls collection to find a button by its tag.
var found = (from Control c
in this.Controls
where c.Tag == "ButtonTag"
select c).FirstOrDefault() as Button;
if (found != null)
{
// manipulate the button
}
I should note that this will only find top level controls on the form. It would not find buttons that are inside of a container control (like a panel). If your buttons are in a container, just replace "this" with the name of your container.
var found = (from Control c
in panel1.Controls
where c.Tag == "ButtonTag"
select c).FirstOrDefault() as Button;
I should also note that this could be slow on a form with a large number of controls.

Related

Getting list of checked radiobuttons in .net

TLDR; Looking for a method to retrieve all radiobuttons by means of something like this... (psudo)
List<RadioButton> btn = new List<RadioButton>;
btn = stackPanel.getAllRadioButtons()
I am currently building a little quiz application in C#. I have functions that add the required GUI elements to a groupbox. I would like to know if there is any way that I can loop through the created elements (for instance radio buttons) to see which are checked.
Here is one of the functions along with how they are added to the window.
private void tfQ(string questionBody)
{
StackPanel questionPanel = new StackPanel{Orientation = Orientation.Vertical};
questionPanel.Children.Add(new Label { Content = questionBody });
GroupBox group = new GroupBox();
RadioButton trueRadio = new RadioButton();
trueRadio.Content = "True";
RadioButton falseRadio = new RadioButton();
falseRadio.Content = "False";
questionPanel.Children.Add(trueRadio);
questionPanel.Children.Add(falseRadio);
group.Content = questionPanel;
mainStack.Children.Add(group);
}
Constructor:
public quiz()
{
tfQ("This is a true/false question");
Window w = new Window();
w.Content = mainStack;
w.Show();
}
I have found many ways to do it in the C# scripting format
(using the Control function ...)
var checkedButton = container.Controls.OfType<RadioButton>()
.FirstOrDefault(r => r.Checked);
but I have not yet found a "programmatic" way of doing it. I have considered changing the type of void tfQ to a StackPanel, but that only helps me to easier loop through the stack panels, althought that only partly solves me problem - allows me to easier loop through the StackPanels but I still don't know how to get the RadioButtons on a panel.
P.S I am very new to C# - with experience in Java/C/C++/Python
I made use of the following code to cast the content into a new groupbox and stackpanel, respectively.
if (child is GroupBox)
{
if ((child as GroupBox).Content is StackPanel)
{
StackPanel d = (StackPanel)((GroupBox)child).Content;
}
}
This allowed me to cast the content into a local copy of a control. It may not be the best way - I'm sure it is very inefficient to be honest. Solved the problem.

C# add buttons to flow control without stealing focus

In my application I dynamically create buttons and add them to a flow control that is later cleared. I have this on a timer to refresh every X seconds to clear then add buttons. This is all being done on the main form.
The problem is when I have a child form launched the main form will steal focus every time the controls are added to the flow control.
Here is the code I have that dynamically clears and adds the controls on the main form.
I call this before adding the controls
flw_users.Controls.Clear();
This is what I call to dynamically create/add the buttons to the flow control.
private void DisplayNewMobileUser(string MobileUserName)
{
// Set Button properties
Button button = new Button();
button.Text = MobileUserName;
button.Size = new System.Drawing.Size(171, 28);
button.Name = MobileUserName;
button.BackColor = System.Drawing.Color.White;
button.FlatAppearance.BorderColor = System.Drawing.Color.White;
button.Font = new System.Drawing.Font("Segoe UI", 12F, System.Drawing.FontStyle.Bold);
button.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
button.ForeColor = System.Drawing.Color.Black;
button.Margin = new System.Windows.Forms.Padding(0, 1, 0, 1);
button.TextAlign = System.Drawing.ContentAlignment.TopLeft;
button.Click += new EventHandler(MobileUserName_OnClick);
flw_users.Controls.Add(button);
}
Is there a way to add buttons to a flow control with out it always stealing focus ?
Thanks to LarsTech I researched how to properly dispose each control added to flw_users. The main issues was fixed by changing the OnClick event to change focus to a label, which in turn didn't cause the main form to gain topmost every time the controls were cleared and re added. So everytime I clicked a button that button still had focus while the new form appeared.
Thanks everyone !
Here is the code I used to properly clear the controls
private void ClearUsers()
{
List<Control> ctrls = new List<Control>();
foreach (Control c in flw_users.Controls)
{
ctrls.Add(c);
}
flw_users.Controls.Clear();
foreach (Control c in ctrls)
{
c.Dispose();
}
}

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.

Changing properties of controls that were added at runtime

I have a form in which several buttons are added at runtime via a 'for' method
public Form()
{
for (int i = 0 ... )
Button b = new Button()
b.text = (string) i ;
etc..
etc..
}
. now i wish to change the text property of the buttons on a certain event. How can this be accomplished? I have tried a few things but none worked.. since the buttons variables are inside the method , they are not available outside.
Thanks
The variables aren't important (although you could store them in a single List<T> field if it made things easier). The normal way to do this is to look through the Controls collection (recursively, if necessary).
foreach(Control control in someParent.Controls) {
Button btn = control as Button;
if(btn != null) {
btn.Text = "hello world";
// etc
}
}
The above assumes all the buttons were added to the same parent control; if that isn't the case, then walk recursively:
void DoSomething(Control parent) {
foreach(Control control in parent.Controls) {
Button btn = control as Button;
if(btn != null) {
btn.Text = "hello world";
// etc
}
DoSometing(control); // recurse
}
}
You can keep the reference of the button you have created ie you can either have a List with all the dynamic controls in it or if it is only one button, make the button object a class level object so that you can access it anywhere.

Dynamic control in c#

I want to create a kind of 4 x 3 matrix with textboxes and checkboxes. Whether the element is checkbox or textbox depends upon the values in database.I want it to be dynamic. What is the best way to start?
// something like this but I need to fill in each elements of the matrix...
private void CreateSpecificControl(string requestedType)
{
if (requestedType == "CheckBox")
{
CheckBox control1 = new CheckBox();
control1.Click += new EventHandler(chk_CheckedChanged);
//TableLayout panel
layout.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 25));
layout.Controls.Add(control1);
}
else
{
Label control1 = new Label();
control1.Text = "Not a checkbox";
layout.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 25));
layout.Controls.Add(control1);
}
}
Use a usercontrol. See this tutorial.
At run time you can change the contents of the User control. There's a Controls collection in each user control that you can add or remove elements from. For example if you want to add check boxes just do somethign like this:
myUserControl.Controls.Add(new CheckBox());
Similarly elements can be removed from this collection, thus achieving a dynamic behaviour.

Categories