I have a bunch of dynamically added controls which add row by row when the user clicks the add user button. I want there to be a label when the page loads and i want the same label to move down every time the add user button is clicked (under each row of textboxes). Right now it is there on load and it moves down when the user clicks the button the first time but after that it just stays. Here is my code:
Global variables:
Label Savelbl = new Label();
int LabelX = 15;
int LabelY = 110;
int spacelbl = 15;
Page load:
Savelbl.Location = new Point(LabelX, LabelY);
Savelbl.Name = "Savelbl";
Savelbl.Text = "Please click 'save' to save your changes";
CaeUsersPanel.Controls.Add(Savelbl);
Add user button:
private void CAEAddUserbtn_Click(object sender, EventArgs e)
{
var i = UsernameTextBoxes.Count + 1; // this is a list of the added textboxes
ADDUserInfo(i); //method which adds the dynamically created textboxes
Savelbl.Location = new Point(LabelX, LabelY + spacelbl);
}
Remove user button (the label should move back up when this is clicked):
private void Remove_Click(object sender, EventArgs e)
{
DialogResult result = MessageBox.Show("Are you sure you want delete this user? \n Deleting users may break workflows", "Delete", MessageBoxButtons.YesNo);
if (result == DialogResult.Yes)
{
int idx = RemoveButtons.IndexOf((Button)sender);
// Remove button
RemoveButtons[idx].Dispose();
RemoveButtons.RemoveAt(idx);
// Remove textbox
UsernameTextBoxes[idx + 1].Dispose();
UsernameTextBoxes.RemoveAt(idx + 1);
//Shift controls up
for (int i = idx; i < RemoveButtons.Count; i++)
{
UsernameTextBoxes[i + 1].Top -= SpaceDelta;
}
space -= SpaceDelta;
Savelbl.Location = new Point(LabelX, LabelY - spacelbl);
}
}
You never update LabelX and LabelY.
LabelX = Savelbl.Location.X
LabelY = Savelbl.Location.Y
Savelbl.Location = new Point(LabelX, LabelY - spacelbl);
You could also get rid of these variables probably...
Related
I am currently experimenting in WPF and just created a UniformGrid with 800 buttons which are created in a for loop. All buttons have their own names and share the same click event.
What I want to do now is the following: I want to click the first button (rect0) to change the color of this button and the next one (rect1).
I am totally stuck right now because everything I write into the click event refers to the button I clicked.
public MainWindow()
{
InitializeComponent();
for (int i = 0; i < 800; i++)
{
Button BTN_rect = new Button()
{
Name = "rect" + i,
Background = Brushes.White,
};
BTN_rect.Click += BTN_rect_Click;
Uniform.Children.Add(BTN_rect);
}
}
private void BTN_rect_Click(object sender, RoutedEventArgs e)
{
Button BTN_rect = sender as Button;
BTN_rect.Background = Brushes.Red;
MessageBox.Show(BTN_rect.Name);
}
There are a load of ways to do this.
I took a shortcut and put just 9 buttons in a stackpanel, otherwise the same.
public MainWindow()
{
InitializeComponent();
for (int i = 0; i < 8; i++)
{
Button BTN_rect = new Button()
{
Name = "rect" + i,
Content =Name,
Tag = i,
Background = Brushes.White,
};
BTN_rect.Click += BTN_rect_Click;
sp.Children.Add(BTN_rect);
}
}
private void BTN_rect_Click(object sender, RoutedEventArgs e)
{
Button current = sender as Button;
current.Background = Brushes.Red;
string targetName = $"rect{((int)current.Tag) + 1}";
Button nextButton = sp.Children.OfType<Button>().Where(x => x.Name == targetName).SingleOrDefault();
nextButton.Background = Brushes.Red;
}
Usually, you'd template data into repeated controls rather than add them in code, btw.
How to create buttons dynamically after user input in C# (Visual Studio).
There is a text-box to enter how many buttons user wants?
Then my target is to create buttons below the input field as the user wants
then how can I get id's of that buttons?
private void button1_Click(object sender, EventArgs e)
{
List<Button> buttons = new List<Button>();
for (int i = 0; i < n; i++)
{
this.Controls.Add(buttons[i]);
}
}
Here I first added an event handler to the textbox, which is called whenever the text value is changed. The value is converted to the int value and then is used in a for loop statement. You can set your button's potion to the desired value using location property. Using tag or name property you can assign a unique value to your buttons. I hope the code helps.
Look at the code below :
private void Form1_Load(object sender, EventArgs e)
{
textBox1.TextChanged += textBox1_TextChanged;
}
void textBox1_TextChanged(object sender, EventArgs e)
{
var txtBox = sender as TextBox;
if (txtBox == null) return;
var count = Convert.ToInt16(txtBox.Text);
//
var xPosition = 0;
for (var i = 1; i <= count; i++)
{
var button = new Button
{
Tag = string.Format("Btn{0}", i),
Text = string.Format("Button{0}",i),
Location = new Point(xPosition, 0)
};
xPosition = xPosition + 100;
Controls.Add(button);
}
When you are creating Control(in your case Buttons) you can give them Name property. It will be very good if that name will be unique.
var btn = new Button();
btn.Name = "MyBtn";
btn.Text = "Our Button";
this.Controls.Add(btn);
For creation of N buttons you just need to put this in a Loop with N iterations and set btn.Name to something like "Name"+SomeNumber.
To set the Position of the Buttons to below the input you should set btn.Left and btn.Top to the corresponding coordinates.
Then when you need to work with generated Control/Button you can do search by that Name in the following way:
var btn = (Button)this.Controls.Find("MyBtn", true).First();
and do whatever you want with that Control/Button.
But in this case there is some danger as I am not checking if there was found any control with that name. If you write incorrect Name this will throw exception on .First().
I'm looking for some advice on how to add click event handlers to labels that have been created created dynamically within a loop.
I've searched for click event handlers on dynamically created controls but this always comes back with single controls that aren't within an array.
example of code:
//create an array of 16 labels
Label[] label = new Label[16];
//loop through the array of labels
for (int i = 0; i < label.Length; i++)
{
label[i] = new Label(); //create new label
label[i].Name = "lbl" + i.ToString(); //give the label a name
label[i].Text = "label " + i.ToString(); //give the label text
}
Any help and advice on this would be great, thanks!
Add a handler:
label[i].Click += HandleLabelClick;
void HandleLabelClick(object sender, EventArgs e)
{
// ...
}
Note that you can determine which label was clicked by using the sender argument:
void HandleLabelClick(object sender, EventArgs e)
{
var label = (Label) sender;
if (label.Text == "this or that") { /* ... */ }
}
When clicking on a button, 5 textboxes will be displayed. I have to add a button for reply to the last textbox - can anyone show me how?
This is my code:
protected void GenTextBox(object sender, EventArgs e)
{
for (i = 1; i <= TotalReplys; i++)
{
HtmlGenericControl lineBreak = new HtmlGenericControl("br");
Page.Controls.Add(lineBreak);
TextBox MyTextBox = new TextBox();
MyTextBox.ID = i.ToString();
MyTextBox.Width = 540;
MyTextBox.Height = 60;
MyTextBox.Text = "Get the value from the database";
MyTextBox.TextMode = TextBoxMode.MultiLine;
Panel1.Controls.Add(MyTextBox);
Panel1.Controls.Add(lineBreak);
}
}
In general, you are on the right track. Use the same code that you have for generating a textbox, but repurpose it to generate a button.
Here are some hints to get you on the right track
if ( i == TotalReplys ){
Button MySearchButton = new Button();
//Set Button Properties
Panel1.Controls.Add(MySearchButton);
}
I imagine you are either hung up on the if-statement logic or perhaps not aware of the Button object. Either way, this should set you on the right track.
I was wondering how to go about doing something such as this:
I need to create a Form with a specific number of buttons based on an integer value representing the number of buttons needed, then give them their own specific names so that each can have their own unique event handlers.
A real example I can think of doing this would be the Windows log-in screen, where the number of controls created is based on the number of users and whether there is a Guest account or not. How do you think that they programmed that?
Thank you.
for (int i = 0; i < 5; i++)
{
Button newButton = new Button();
newButton.Name = "button" + i.ToString();
newButton.Text = "Button #" + i.ToString();
newButton.Location = new Point(32, i * 32);
newButton.Click += new EventHandler(button1_Click);
this.Controls.Add(newButton);
}
private void button1_Click(object sender, EventArgs e)
{
if (((Button)sender).Name == "button0")
MessageBox.Show("Button 0");
else if (((Button)sender).Name == "button1")
MessageBox.Show("Button 1");
}
Somehow you have to define the names of all the buttons. I would suggest you to create a new string array and write the button names inside, and then use them in buttons creation loop:
//do the same length as the for loop below:
string[] buttonNames = { "button1", "button2", "button3", "button4", "button5" };
for (int i = 0; i < buttonNames.Lenght; i++)
{
Button newButton = new Button();
newButton.Name = "button" + i.ToString();
newButton.Text = buttonNames[i]; //each button will now get its own name from array
newButton.Location = new Point(32, i * 32);
newbutton.Size = new Size(25,100); //maybe you can set different sizes too (especially for X axes)
newButton.Click += new EventHandler(buttons_Click);
this.Controls.Add(newButton);
}
private void buttons_Click(object sender, EventArgs e)
{
Button btn = sender as Button
MessageBox.Show("You clicked button: " + btn.Text + ".");
}