This question already has answers here:
Passing variable values between methods...?
(3 answers)
Closed 3 years ago.
I have a Checkbox, when marked it will create a Listbox, Button and a Textbox.
The generated Button, should have the Click event to fill the generated Listbox with the value of the generated Textbox.
But I get compile time error inside public System.Windows.Forms.Button AddNewButton() :
The name Txb does nost exist in the current context
The name lb does nost exist in the current context
Here is the code:
private void cbDd_CheckedChanged(object sender, EventArgs e)
{
AddNewListBox();
AddNewTextBox();
AddNewButton();
}
public System.Windows.Forms.ListBox AddNewListBox()
{
System.Windows.Forms.ListBox lb = new System.Windows.Forms.ListBox();
this.Controls.Add(lb);
lb.Top = 74;
lb.Left = 500;
cLeft = cLeft + 1;
return lb;
}
public System.Windows.Forms.TextBox AddNewTextBox()
{
System.Windows.Forms.TextBox txb = new System.Windows.Forms.TextBox();
this.Controls.Add(txb);
txb.Top = 180;
txb.Left = 500;
txb.Text = "item name";
cLeft = cLeft + 1;
return txb;
}
public System.Windows.Forms.Button AddNewButton()
{
System.Windows.Forms.Button btn = new System.Windows.Forms.Button();
this.Controls.Add(btn);
btn.Top = 210;
btn.Left = 500;
btn.Text = "Add item";
btn.Click += (s, e) => { if (string.IsNullOrEmpty(txb.Text)) return;
};
lb.Items.Add(cbTxb.Text);
return btn;
}
In addition to AddNew(ListBox|TextBox|Button)
public System.Windows.Forms.ListBox AddNewListBox()
{
return new System.Windows.Forms.ListBox() {
Location = new Point(500, 74),
parent = this, // instead of this.Controls.Add(...)
};
}
public System.Windows.Forms.TextBox AddNewTextBox()
{
return new System.Windows.Forms.TextBox() {
Location = new Point(500, 180),
Text = "item name",
Parent = this,
};
}
public System.Windows.Forms.Button AddNewButton()
{
return new System.Windows.Forms.Button() {
Location = new Point(500, 210),
Text = "Add item",
Parent = this,
};
}
I suggest implementing AddNewControls() where created controls can interact with one another:
private void AddNewControls() {
var lb = AddNewListBox();
var txb = AddNewTextBox();
var btn = AddNewButton();
btn.Click += (s, e) => {
// now btn (button) can use txb (TextBox)
if (string.IsNullOrEmpty(txb.Text))
return;
//TODO: put relevant code here
}
cLeft += 3;
//TODO: check lb and cbTxb.Text
lb.Items.Add(cbTxb.Text);
}
Then you can put
private void cbDd_CheckedChanged(object sender, EventArgs e)
{
AddNewControls();
}
Related
I am trying to creat a dynamic button in a my application. So basically I have this code but when I run it I don’t see the bottom in the other form . The panel is empty. I create the bottom on a button click in a first form then it has to show the button in the second form’s panel.
private void btnsend_Click(object sender, EventArgs e)
{
this.Hide();
Form wrr = new Interface();
wrr.Show();
createnutton();
}
int i = 0;
int x = 0;
private void createnutton()
{
Button btn = new Button();
btn.Location = new Point(3 + i, 14 + x);
btn.BackColor = System.Drawing.Color.Red;
btn.ForeColor = System.Drawing.Color.Yellow;
btn.Text = "Tabel" + libtno.Text;
btn.Click += new EventHandler(btn_Click);
panel3.Controls.Add(btn);
i += 10;
x += 10;
}
void btn_Click(object sender,EventArgs e)
{
MessageBox.Show("me");
}
You have to set one more property "Visible=true" for your Button.
You need a reference to the instance of Interface that you created. Pass wrr to your createnutton function. For this to work, you have to change the MODIFIERS property of panel3 to PUBLIC. You also can't reference the Form with the generic Form type. It has to be of that specific Form type, which is Interface (a horrible name by the way, since interface has different meaning in C#):
private void btnsend_Click(object sender, EventArgs e)
{
this.Hide();
Interface wrr = new Interface();
wrr.Show();
createnutton(wrr); // <-- pass "wrr" to the function
}
int i = 0;
int x = 0;
private void createnutton(Interface frmInterface) // <-- parameter added
{
Button btn = new Button();
btn.Location = new Point(3 + i, 14 + x);
btn.BackColor = System.Drawing.Color.Red;
btn.ForeColor = System.Drawing.Color.Yellow;
btn.Text = "Tabel" + libtno.Text;
btn.Click += new EventHandler(btn_Click);
frmInterface.panel3.Controls.Add(btn); // <-- use the passed in form
i += 10;
x += 10;
}
BUT...this seems like a horrible design. I wouldn't do this if I were personally writing from the ground up.
I'm trying to have panel displaying the result differently each time a user select items from pre-loaded combobox and dynamically created combobox.
Initially it will load a comboBox with item of ("HelloWorld"), each time when I do a SelectedIndexChanged with "HelloWorld", the panel will show 1.
However, problem lies on whenever I hit on add button and do SelectedIndexChanged with "HelloWorld" on the newly created button. It simply doesn't show 2 but instead when I hit on pre-loaded comboBox, it show 3.
Is it something to do with life-cycle events?
class form{
int index = 0;
private void formMain_Load(object sender, EventArgs e)
{
Button add = new Button();
panel.Controls.Add(search());
add.Click += new EventHandler((object o, EventArgs e) => { panel.Controls.Add(search()); });
panel.Controls.Add(add);
}
public ComboBox search()
{
ComboBox searchField = new ComboBox();
searchField.Items.Add("HelloWorld");
searchField.SelectedIndexChanged += new EventHandler((object io, EventArgs ie) =>
{
index++;
Label display = new Label();
display.Text = index.ToString();
panel.Controls.Add(display);
});
return searchField;
}
}
I have tried many days and couldn't understand it ... Any helps would be appreciated. Thanks
int index { get; set; }
public Form2()
{
InitializeComponent();
index = 0;
Button add = new Button();
add.Text = "Add";
add.Location = new Point(search().Location.X + search().Width + 10, search().Location.Y);
panel.Controls.Add(search());
add.Click += new EventHandler((object o, EventArgs e) => {
panel.Controls.Add(search());
});
panel.Controls.Add(add);
}
public ComboBox search()
{
ComboBox searchField = new ComboBox();
searchField.Items.Add("HelloWorld");
searchField.Name = "cmb " + index.ToString();
searchField.Location = new Point(10, (index + 1) * 20);
searchField.SelectedIndexChanged += new EventHandler((object io, EventArgs ie) =>
{
index++;
Label display = new Label();
display.Location = new Point(250, search().Location.Y-12);
panel.Controls.Add(display);
display.Text = index.ToString();
});
return searchField;
}
i need to use a button to make a number of textboxes with related buttons each button will add 1 to the textbox (that i want to be related to it HOW?)
i have a windows form with button1 and three panels
==========================================
using System;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
namespace AdvancedCounter
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
if (panel3.Controls != null)
{
var btn = panel3.Controls.Find("_B", true).First();
btn.Click += new EventHandler(Btn_Click);
}
}
int a = 0;
int counter=0;
private void button1_Click(object sender, EventArgs e)
{
counter++;
Button btn = new Button();
btn.Location = new Point(0, 100);
btn.Text = "ADD";
btn.Name ="_B";
btn.Dock = DockStyle.Left;
btn.Click += new EventHandler(Btn_Click);
TextBox txt = new TextBox();
txt.Name = "_T";
txt.Location = new Point(500, 100);
txt.Dock = DockStyle.Left;
txt.Text = a.ToString();
panel3.Controls.Add(txt);
panel3.Controls.Add(btn);
foreach (var item in panel3.Controls.Find("_B", true))
{
item.Text = "ass";
}
}
private void Btn_Click(object sender, EventArgs e)
{
// MessageBox.Show(sender.ToString());
// throw new NotImplementedException();
var txtbx= panel3.Controls.Find("_T", true).First();
var btnbx = panel3.Controls.Find("_B", true).First();
a++;
// find[1].Dispose();
txtbx.Text = a.ToString();
}
}
}
First you are giving same Name property for every TextBox and Button, you should not do that. Instead do like this for example:
btn.Name = "_B_"+ counter;
So you will have different Name for Buttons and TextBoxes. And in event handler:
private void Btn_Click(object sender, EventArgs e)
{
Button btn = sender as Button;
string index = btn.Name.Split('_')[2];
string tbName = "_T_" + index;
var txtbx= panel3.Controls.Find(tbName, true).First();
a++;
txtbx.Text = a.ToString();
}
I'm creating dynamically buttons into a repeater like somebody recommend in previous questions I make into a Page_Init and I make some conditions but the problem persist, the button don't fire the assigned event
this is the first condition
public bool AssignClicked
{
get
{
return Convert.ToBoolean(ViewState["AssignClicked"]);
}
set
{
ViewState["AssignClicked"] = value;
}
}
then this is the code when I make click in the button that create the buttons changing into true the condition:
protected void DButton(object sender, EventArgs e)
{
AssignClicked = true;
Page_Init(sender, e);
Page_Load(sender, e);
}
And start the creations of the buttons
protected void Page_Init(object sender, EventArgs e)
{
if (AssignClicked)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "Pop", "showAndHide();", true);
Button Btn_clic = (Button)sender;
var name = Btn_clic.Text;
List.ListUsers listArea = new List.ListUsers();
List<Data.Area> Area = listArea.AreaList();
List<Data.Area> ListOfEquiposOk = Area.Where(x => x.AREA == name && x.STANDBY == 0).ToList();
var TeamFCH = ListOfEquiposOk.Select(x => x.TEAM).Distinct().ToList();
foreach (var team in TeamFCH)
{
Button newButton = new Button();
newButton.CommandName = "Btn" + Convert.ToString(team);
newButton.ID = "Btn_" + Convert.ToString(team);
newButton.Text = team;
newButton.CommandArgument = name;
newButton.Click += new EventHandler(newButton_Click);
Repeater1.Controls.Add(newButton);
newButton.CssClass = "btn-primary outline separate";
}
}
}
but when I click over the button created this doesn't do anything
I have a form that pops up at a specific event. It draws up buttons from an array and sets the Tag value to a specific value. So if you are to press or click this button the function should return the Tag value.
How can I do this? And how do I know which button was clicked?
At this moment the code returns DialogResult, but I want to return the Tag value from the function. How shall I modify my code so that it can do this?
public static DialogResult SelectBox(string title, string[] btnArray, string[] btnValueArray)
{
Form form = new Form();
Button[] buttonArray;
buttonArray = new Button[5];
form.Text = title;
for (int i = 0; i < btnArray.Length; i++)
{
buttonArray[i] = new Button();
buttonArray[i].Text = btnArray[i];
buttonArray[i].Tag = new int();
buttonArray[i].Tag = btnValueArray[i];
buttonArray[i].TabStop = false;
buttonArray[i].Location = new System.Drawing.Point(0, i * 40);
buttonArray[i].Size = new System.Drawing.Size(240, 40);
}
form.ClientSize = new Size(240, 268);
form.Controls.AddRange(new Control[] { buttonArray[0], buttonArray[1], buttonArray[2] });
form.FormBorderStyle = FormBorderStyle.FixedDialog;
form.StartPosition = FormStartPosition.CenterScreen;
form.MinimizeBox = false;
form.MaximizeBox = false;
DialogResult dialogResult = form.ShowDialog();
return dialogResult;
}
Add a private variable in the form:
private object SelectedTag;
Add a button click handler:
private void Button_Click(object sender, EventArgs e) {
SelectedTag = ((Button)sender).Tag;
}
Assign the handler to each button you create:
..
buttonArray[i].OnClick += form.Button_Click;
..
Then in your static function, simply return form.SelectedTag instead of the dialogresult.
You could call the same click event for all buttons. then in your handler:
private void ButtonClick(object sender, EventArgs args)
{
Button oButton = (Button) sender;
object data = oButton.Tag;
}
The DialogResult property already tells you which button was clicked. You can set each individual button to return a different DialogResult, and then check for that at the bottom of the function.
And if you want to return the clicked button's Tag property instead, you need to change the function's return value to Object (because the Tag property is of type Object).
You can add a ButtonClick event handler in a TestForm, set the button's tag to the Form's tag.
Here is the sample.
Main Form:
private void Form1_Load(object sender, EventArgs e)
{
Object tag;
SelectBox("test", new String[] { "One", "Two", "Three" }, new String[] {"one value", "Two value", "three value" }, out tag);
MessageBox.Show(tag.ToString());
}
public static DialogResult SelectBox(string title, string[] btnArray, string[] btnValueArray, out Object tagValue)
{
TestForm form = new TestForm();
Button[] buttonArray;
buttonArray = new Button[5];
form.Text = title;
for (int i = 0; i < btnArray.Length; i++)
{
buttonArray[i] = new Button();
buttonArray[i].Text = btnArray[i];
buttonArray[i].Tag = new int();
buttonArray[i].Tag = btnValueArray[i];
buttonArray[i].TabStop = false;
buttonArray[i].Location = new System.Drawing.Point(0, i * 40);
buttonArray[i].Size = new System.Drawing.Size(240, 40);
// subscribe to button click event..
// the handler is in TestForm
buttonArray[i].Click += form.HandleOnButtonClick;
}
form.ClientSize = new Size(240, 268);
form.Controls.AddRange(new Control[] { buttonArray[0], buttonArray[1], buttonArray[2] });
form.FormBorderStyle = FormBorderStyle.FixedDialog;
form.StartPosition = FormStartPosition.CenterScreen;
form.MinimizeBox = false;
form.MaximizeBox = false;
DialogResult dialogResult = form.ShowDialog();
// set the out args value
tagValue = form.Tag;
return dialogResult;
}
TestForm that whose instance we create in the SelectBox dialog:
public partial class TestForm : Form
{
public TestForm()
{
InitializeComponent();
}
public void HandleOnButtonClick(Object sender, EventArgs e)
{
Button button = sender as Button;
if (button != null)
this.Tag = button.Tag;
}
}
Edit:
If you want to capture every button's value then expose a Dictionary<String, Object> Tags property.