Add Event at runtime - c#

my method is :
private void button1_Click(object sender, EventArgs e)
{
for (int i = 1; i < 10; i++)
{
Button btn = new Button();
btn.Name = "btn" + i.ToString();
btn.Text = "btn" + i.ToString();
btn.Click += new EventHandler(this.btn_Click);
this.flowLayoutPanel1.Controls.Add(btn);
}
}
void btn_Click(object sender, EventArgs e)
{
Button btn = (Button)sender;
if (btn.Name == "btn1")
{
this.Text = "stack";
}
}
There is a better approach ?

The code you used:
btn.Click += new EventHandler(this.btn_Click);
Is the correct code to add the handler. Creating the buttons and adding them to their container looks good.
The only thing I would add is just make sure you are creating the controls on postback too, prior to viewstate being restored, so that the events can actually be called.

Or maybe:
private void button1_Click(object sender, EventArgs e)
{
for (int i = 1; i < 10; i++)
{
Button btn = new Button();
btn.Text = "btn" + i.ToString();
btn.Tag = i;
btn.Click += delegate
{
if ((int)btn.Tag == 1)
this.Text = "stack";
};
this.flowLayoutPanel1.Controls.Add(btn);
}
}

Related

Creating a dynamic button

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.

How to change button color on button click in C#?

I am creating an online test application, in which I am generating approximately 100 buttons at run time on form load. Here is the piece of code:w
private void addQuestion_Reviewbutton()
{
for (int i = 1; i <= clsGlobalVars.gnTotalQuestion; i++)
{
Button button = new Button();
button.Location = new Point(160, 30 * i + 10);
button.Click += new EventHandler(ButtonClickOneEvent);
button.Tag = i;
button.Name = "Question" + i;
button.Text = i.ToString();
button.BackgroundImage = ((System.Drawing.Image)(Properties.Resources.button));
button.BackgroundImageLayout = ImageLayout.Stretch;//.Zoom;
button.FlatAppearance.BorderSize = 0;
button.Size = new System.Drawing.Size(47, 41);
button.BackColor = Color.Transparent;
button.FlatStyle = FlatStyle.Flat;
button.Font = new System.Drawing.Font("Segoe UI Semibold", 12);
button.ForeColor = Color.White;
button.Cursor = Cursors.Hand;
flowLayoutPanel1.Controls.Add(button);
}
}
and on this button click, I am changing the background-color.
void ButtonClickOneEvent(object sender, EventArgs e)
{
Button button = sender as Button;
//button.BackColor = Color.Yellow;
button.BackgroundImage = ((System.Drawing.Image)(Properties.Resources.button_Orange));
lblQuestionNo.Text = ((int)button.Tag).ToString()+".";
btnNext.Focus();
}
I have a button on the form Named "Next". Now my problem is that if I am currently in question "1." and I press the button next I want to change the background image of the button whose text is "2".
Yo check this !
tldr; the guidance are
Is the click event go to ButtonClickOneEvent ?
How to call other button
...
profit?
protected void Page_Load(object sender, EventArgs e)
{
addQuestion_Reviewbutton();
}
void ButtonClickOneEvent(object sender, EventArgs e)
{
Button button = sender as Button;
var currentbtn_id = button.ID;
int nextid = Convert.ToInt32( currentbtn_id.Substring("Question".Length)) + 1;
var nextBtn = flowLayoutPanel1.FindControl("Question"+ nextid.ToString() );
(nextBtn as Button).BackColor = Color.Red;
}

Select part of Button's text

I'm using this code to create buttons with two lines text
private void button1_Click(object sender, EventArgs e)
{
int top = 50;
int left = 100;
int n = 0;
int s = 99;
for (int i = 0; i < 20; i++)
{
Button button = new Button();
button.Left = left;
button.Top = top;
panel1.Controls.Add(button); // here
button.Size = new Size(50, 50);
if (i == 4 || i == 9||i==14||i==19)
{
top = 30;
left = 23;
top +=button.Top+2;
left += button.Width+2;
}
else
left += button.Width + 2;
n = n + 1;
s = s + 1;
button.Text = Convert.ToString(n) + Environment.NewLine + Convert.ToString(s);
button.Click += Button_Click;
}
}
private void Button_Click(object sender, EventArgs e)
{
string s;
Button button = (Button)sender;
s = button.Text + Environment.NewLine;
MessageBox.Show(s);
}
So I need to select only second line brom my button text when I click dynamic button. How will I do this?
you can store some data in Tag property:
button.Text = Convert.ToString(n) + Environment.NewLine + Convert.ToString(s);
button.Tag = new int[] { n, s };
and later retrive it and use:
private void Button_Click(object sender, EventArgs e)
{
Button button = (Button)sender;
var data = button.Tag as int[];
string s = data[1].ToString();
MessageBox.Show(s);
}
private void Button_Click(object sender, EventArgs e)
{
string s;
Button button = (Button)sender;
s = button.Text + Environment.NewLine;
MessageBox.Show(button.Text.Split(new[] { Environment.NewLine }, StringSplitOptions.None)[1]);
}

LinkButton.OnClick Method with Parameter

I'm creating a linkButton Dynamically on ASP.net. I need help on when I click the linkButton, it will store the linkbutton name to my Label1 (for example only).
Here is the code:
protected void Page_Load(object sender, EventArgs e)
{
for (int ctr = 0; ctr <= 2; ctr++)
{
LinkButton link = new LinkButton();
link.ID = "lnk" + ctr.ToString();
link.Text = "lnkName" + ctr.ToString();
link.Click += new EventHandler(DynamicClick);
this.form1.Controls.Add(link);
}
}
//when I click the buttonLink
public void DynamicClick(object sender, EventArgs e)
{
//label1.text will get the .text of the button that i pressed
Label1.Text = "";
}
I would do it in that way
public void DynamicClick(object sender, EventArgs e)
{
LinkButton linkButton = sender as LinkButton;
if (linkButton != null)
{
Label1.Text = linkButton.Text;
}
}
protected void Page_Load(object sender, EventArgs e)
{
for (int ctr = 0; ctr <= 2; ctr++)
{
LinkButton link = new LinkButton();
link.ID = "lnk" + ctr.ToString();
link.Text = "lnkName" + ctr.ToString();
link.Click += delegate { Label1.Text = link.ID; };
this.form1.Controls.Add(link);
}
}
I would do this with a slight variation to Valeh's answer.
protected void Page_Load(object sender, EventArgs e)
{
for (int ctr = 0; ctr <= 2; ctr++)
{
LinkButton link = new LinkButton();
link.ID = "lnk" + ctr.ToString();
link.Text = "lnkName" + ctr.ToString();
link.Click += (s, ea) =>
{
Label1.Text = link.Text;
};
this.form1.Controls.Add(link);
}
}
Creating a separate method public void DynamicClick(object sender, EventArgs e) - especially one that is public - is a bad thing when it is not necessary as it breaks encapsulation. It's perfectly understandable to do so when we're working with a designer, but when we're writing the code ourselves it's a bad idea.

Creating unique event handlers for dynamically created buttons

I want to add buttons to my page dynamically. It will depend on the number of results from a SELECT statement. I
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
for (int i = 0; i < Query.length; i++)
{
Button btn = new Button();
btn.ID = "Button" + i;
btn.Click += new EventHandler(btn_Click());
btn.Text = i.ToString();
pagingPanel.Controls.Add(btn);
}
}
}
But I want each button to have it's own custom event handler. If I click one button, I want it do have a different result than if I click another. I would like to do something like this where I can pass an aditional parameter:
protected void btn_Click(object sender, EventArgs e, string test)
{
System.Diagnostics.Debug.WriteLine(test);
}
Perhaps I don't know which objects to pass? Or maybe I am approaching this the wrong way.
How do I achieve the desired results?
Try this:
protected void Page_Load(object sender, EventArgs e)
{
// you do not use !IsPostBack here
//count of func must be equal with 'Query.Length'
string[,] arr ={
{"func1","hello world"},
{"func2","Hello ASP.NET"}
};
for (int i = 0; i < Query.Length; i++)//I assume length is 2
{
Button btn = new Button();
btn.ID = arr[i, 0];
btn.CommandArgument = arr[i, 1];
btn.Click += new EventHandler(btn_Click);
btn.Text = i.ToString();
pagingPanel.Controls.Add(btn);
}
}
protected void btn_Click(object sender, EventArgs e)
{
Button btn = (Button)sender;
System.Reflection.MethodInfo methodInfo = typeof(_Default2).GetMethod(btn.ID); //_Default2 is class name of code behind
if (methodInfo != null)
{
object[] parameters = new object[] { btn.CommandArgument};
methodInfo.Invoke(this,parameters);
}
}
public void func1(object args)
{
string test = args.ToString();
Response.Write(test);
}
public void func2(object args)
{
string test = args.ToString();
Response.Write(test);
}
First and foremost - you have to create buttons whether it is postback or not. The button click is the reason for the postback, if you don't have buttons - what will be clicking?
Second, add to your page class:
Dictionary<Button, ButtonInfo> fButtonLookup = new Dictionary<Button, ButtonInfo>();
Then, where you create buttons:
fButtonLookup.Clear();
for (int i = 0; i < Query.length; i++)
{
Button btn = new Button();
fButtonLookup.Add(btn, new ButtonInfo() { whatever information about this button you want to keep});
...
}
Then, in your button click:
protected void btn_Click(object sender, EventArgs e)
{
Button btn = (Button)sender;
if (fButtonLookup.ContainsKey(btn))
{
ButtonInfo info = fButtonLookup[btn];
// do waht you need with button information
}
}
You could just check sender to see which button was clicked:
protected void btn_Click(object sender, EventArgs e)
{
if (sender == btnOne)
performBtnOne("foo");
else if (sender == btnTwo)
performButtonTwo("bar");
}
To expand on itsme86...
protected void btn_Click(object sender, EventArgs e)
{
Button btn = (Button)sender; //Now you have an instantiated version of the button pressed.
switch (btn.Name)
{
case "foo":
performBtnOne();
break;
case "bar":
performBtnTwo();
break;
default:
performUnexpectedButton();
break;
}
}

Categories