C# Adding Button with Value at Runtime

C# Adding button with value at runtime

In you save button put :

 private void btnSave_Click(object sender, EventArgs e)
{
x = 4;
y = panel1 .Controls.Count * 70;
Button newButton = new Button ();
newButton.Height = 150;
newButton.Width = 60;
newButton.Location = new Point(x, y);
newButton.Text= "your text";
newButton.Click += new
System.EventHandler(Button_Click);
tabControl1.TabPages [0].Controls.Add(newButton);

}

And also you can handel the click of new button created :

public void Button_Click(object sender, EventArgs e)
{
Button button = (Button)sender ;
MessageBox.Show("Button is pressed "+button .Text );

}

how can i store value in button at runtime?

The Tag property is probably what you want.

You are already using it in your example, but just have:

b2.Tag = integerValue;

Then in your click handler use Convert.ToInt32(object) method to get the integer value back:

int retrievedValue = Convert.ToInt32(clicked.Tag);

Adding button with Text dynamically to UI at runtime in Unity

I highly advise you to instantiate a prefab instead of creating the button from scratch.

A gameobject with a RectTransform and button only won't be visible, and won't react to clicks, because you need additionnal components (such as Canvas Renderer and Image / Raw Image).

// Drag & Drop the prefab of the button you will instantiate
public GameObject buttonPrefab ;

public void MakeButton(string direction)
{
// Instantiate (clone) the prefab
GameObject button = (GameObject) Instantiate( buttonPrefab ) ;

var panel = GameObject.Find("CommandPanel");
button.transform.position = panel.transform.position;
button.GetComponent<RectTransform>().SetParent(panel.transform);
button.GetComponent<RectTransform>().SetInsetAndSizeFromParentEdge(RectTransform.Edge.Left,0,10);
button.layer = 5;

}

Moreover, you have to be careful to one additional thing : when you ask Unity to create a button (Using GameObject > UI > Button), Unity creates several gameobjects (the button + child) with all the appropriates components (button, canvas renderer, text, ...).

Adding the Button component won't add all the other components and children Unity does. Thus button.GetComponentsInChildren<Text>()[0].text = "New Super Cool Button Text"; won't work (since you haven't added the child and its Text component in your script)

Additional note : Check this link if you have some problems with placing your object : https://docs.unity3d.com/Manual/HOWTO-UICreateFromScripting.html

How to create shortcut of a button on a panel at runtime?

You can create a clone method which accepts a button as input and creates another button based on the input button's properties, also handle click event of the cloned button and just call PerformClick method of the input button:

public Button Clone(Button input)
{
var output = new Button();
output.Text = input.Text;
// do the same for other properties that you need to clone
output.Click += (s,e)=>input.PerformClick();
return output;
}

Then you can use it this way:

var btn = Clone(button1);
panel1.Controls.Add(btn);

Also instead of a panel, it's better to use a FlowLayoutPanel or TableLayoutPanel, so you don't need to handle the location and the layout yourself.

Note: If it's a dynamic UI and users can reorder command buttons or create whatever you called shortcut, the probably for the next step you may need to store the status of the panel to be able to reload buttons at the next load of the application after the application closed. In this case it's better to consider a pattern like command pattern. Then you can have your commands as classes. The then you can say which button is responsible to run which command at run-time and you can simply store the relation between buttons and commands using their names.

How to set the many button text at runtime in WinForms?

If buttons are arranged in the order from 1 to 20 you do not need extracting number from a button name, just use autoincrement index variable:

int index = 0;
// either form.Controls or this.Controls dedepnds on where you put this code
foreach (var control in form.Controls)
{
var button = control as Button;
if (button != null)
{
button.Text = String.Format("Button #{0}", index);
index++;
}
}

EDIT: Try it out, have nopt checked since have no environment setup in hand

To avoid affecting Up/Down buttons mark it by special tag value like Tag="ControlButton"

using System.Linq;
var buttons = this.tableLayoutPanel1.Controls
.OfType<Button>()
.Where(b => b.Tag != "ControlButton");
int index = buttons.Count();
foreach (var button in buttons)
{
button.Text = String.Format("Button #{0}", index);
index--;
}

Getting values from buttons created runtime in c# Winforms

Controls all have a Tag property that can have any object assigned to it. You don't even really need to use the Name property when creating the buttons programmatically. Here I've used simply strings, but any unique action the button can take can be distilled to its required elements and the things it needs to do that can be put into an object and assigned to the Tag property.

Button btn = new Button();
Controls.Add(btn);
btn.Tag = "Hello from Button #1";
btn.Click += btn_Click;

btn = new Button();
Controls.Add(btn);
btn.Tag = "Hello from Button #2";
btn.Click += btn_Click;

In the event handler you are passed the sender, which is a reference to the control that raised the event. You can then access its Tag property with a simple cast :

private void btn_Click(object sender, EventArgs e)
{
if (sender is Control) {
MessageBox.Show(((Control)sender).Tag.ToString());
}
}

To show the example that the Tag can be anything :

Button btn = new Button();
Controls.Add(btn);
btn.Tag = Color.Blue;
btn.Click += btn_Click;

btn = new Button();
Controls.Add(btn);
btn.Tag = Color.Red;
btn.Click += btn_Click;

and

    if (sender is Control) {
this.BackColor = (Color)((Control)sender).Tag;
}

How to add buttons dynamically to my form?

It doesn't work because the list is empty. Try this:

private void button1_Click(object sender, EventArgs e)
{
List<Button> buttons = new List<Button>();
for (int i = 0; i < 10; i++)
{
Button newButton = new Button();
buttons.Add(newButton);
this.Controls.Add(newButton);
}
}


Related Topics



Leave a reply



Submit