This question already has answers here:
How can I programmatically call my .net button's onclick in page load?
(5 answers)
Closed 5 years ago.
I have created 100 buttons and want to first button clicked by default when page load first time(without clicking on button).
HtmlTable myTable = new HtmlTable();
int n = 0;
for (int i = 0; i < 20; i++)
{
HtmlTableRow row = new HtmlTableRow();
for (int c = 1; c <= 5; c++)
{
n = (5 * i) + c;
HtmlTableCell cell = new HtmlTableCell();
Button btn = new Button();
btn.Text = n.ToString();
btn.ID = n.ToString();
//btn.BackColor = Color.Transparent;
btn.Width = 30;
btn.Height = 25;
btn.Click += new EventHandler(btn_Click);
cell.Controls.Add(btn);
row.Controls.Add(cell);
myTable.Controls.Add(row);
cell.Attributes.Add("Class", "htTableCellCss");
}
row.Attributes.Add("Class", "htTableRowCss");
}
myTable.Attributes.Add("Class", "htTableCss");
btndiv.Controls.Add(myTable);
Well, before you start coding, place yoursef in protected void Page_Load method
and there you should just call the onlick method event directly, like this ( lets say yyour button is named myButton, and lets say it's allready defined what's that gonna do):
myButton_Click(this, EventArgs.Empty);
You can place this method invokation exactlly where you need it, so on your page load also
Related
I'm trying to make dynamicly created radiobuttons in my dynamicly created panel, but I'm not recieving what I'm trying to accomplish.
Here is my code:
private void Form1_Load(object sender, EventArgs e)
{
//Creating 3 panels
int counTer = 3;
for (int x = 0; x <= counTer; x++)
{
Panel panel = new Panel();
panel.Name = "panel" + x;
panel.Location = new Point(10 * (5 * x), 10);
panel.Size = new Size(150, 275);
//panel.BackColor = Color.Black; <-- Only for checking if they exist
panel.Controls.Add(panel);
//Creating 10 RadioButtons
int hoeveelHeid = 10;
for (int i = 0; i <= hoeveelHeid; i++)
{
RadioButton iets= new RadioButton();
iets.Name = "Waarde" + i;
iets.Text = "Waarde " + i;
iets.Location = new Point(5, 20 * i);
panel.Controls.Add(iets);
}
}
}
I'm not recieving any panels nor radiobuttons, does anyone see the mistake i made?
Thanks.
You are trying to add the panel you created to it's OWN control collection:
panel.Controls.Add(panel);
which means add the panel to the panel.
To add the panel to the form use:
this.Controls.Add (panel);
or even just:
Controls.Add (panel);
As suggested by Sinatr, you have to add the panel to your form like that:
this.Controls.Add (panel);
Otherwise your panel does exist, but it's not on your form.
For anyone who wants to hate with the reason that I only want to gain reputation, this answer's marked as community wiki.
what I want to do is to add more than one control from code behind to my website, I know how to add one control, but I want to add two controls at the same time, when someone click on an other button!
here is my code, but it only add the second button!
protected void Unnamed2_Click(object sender, EventArgs e)
{
Button b = new Button();
for (int i = 0; i < 2; i++)
{
b.ID = i.ToString();
b.Text = i.ToString();
b.Width=250;
b.Height = 100;
b.Style.Add("background-color", "red");
Page.Form.Controls.Add(b);
}
}
The new Button() also needs to be in the loop... otherwise you only create one instance.
for (int i = 0; i < 2; i++)
{
Button b = new Button();
b.ID = i.ToString();
b.Text = i.ToString();
b.Width=250;
b.Height = 100;
b.Style.Add("background-color", "red");
Page.Form.Controls.Add(b);
}
I create buttons in my application by:
List<Button> btnslist = new List<Button>();
for (int i = 0; i < nbrofbtns; i++)
{
Button newButton = new Button();
btnslist.Add(newButton);
this.Controls.Add(newButton);
newButton.Width = btnsidelength;
newButton.Height = btnsidelength;
newButton.Top = btnsidelength
* Convert.ToInt32(Math.Floor(Convert.ToDouble(i / Form2.puzzlesize)));
newButton.Left = btnsidelength
* Convert.ToInt32(
Math.Floor(Convert.ToDouble(i))
- Math.Floor((Convert.ToDouble(i))
/ (Form2.puzzlesize)) * (Form2.puzzlesize));
newButton.BackgroundImage = Lights_out_.Properties.Resources.LightsOutBlack;
newButton.Tag = (i+1).ToString();
newButton.Click += new EventHandler(Any_Button_Click);
Then I have a method for when any of the buttons are clicked.
void Any_Button_Click(object sender, EventArgs e)
{
//the variable b has all the insformation that the single button had itself.
Button b = (Button)sender;
if (b.BackgroundImage == Lights_out_.Properties.Resources.LightsOutBlack)
{
MessageBox.Show(b.Tag.ToString());
MessageBox.Show(btnslist[Convert.ToInt32(b.Tag)].BackgroundImage.ToString());
btnslist[Convert.ToInt32(b.Tag)].BackgroundImage =
Lights_out_.Properties.Resources.LightsOutWhite;
MessageBox.Show(btnslist[Convert.ToInt32(b.Tag)].BackgroundImage.ToString());
}
else
{
MessageBox.Show("b.backgroundimage != lightsoutblack. Backgroundimage = "
+ b.BackgroundImage.ToString());
}
}
How do I change the data in the actual button (then said button is clicked)? I want specificly to change the backgroundimage. How could I do this?? (I also need to change the backgroundimage of some other buttons created by the code.)
The sender object is the button:
Button b = (Button)sender;
... so you should be able to change properties on it directly:
b.WhateverPropsToChange = yourSetting;
PS: I don't think this is necessary, but if the button is not updated directly, you might try to using b.Refresh() to let it know something has changed.
You're handling Click event of every button you've created - and sender in Any_Button_Click is actually the button was clicked.
So just change b.BackgroundImage to whatever you need.
I have associated a Button ID while generating Buttons dynamically and created a Button event handler as follows:
btn.Click += new EventHandler(btn_Click);
Button Click event:
protected void btn_Click(object sender,EventArgs e)
{
Button b = new Button();
b = (Button)sender;
string i = b.ID.Substring(b.ID.Length - 1, 1);
int j1 =Convert.ToInt32(i);
id1 = to[j1];
Page.ClientScript.RegisterClientScriptBlock(Type.GetType("System.String"),
"addScript", "PassValues('" + id1 + "')", true);
ScriptManager.RegisterStartupScript(this, this.GetType(),
"sendMessage", "javascript:sendMessage(); ", true);
}
However this event is not getting called i have placed all my controls inside an UpdatePanel
EDIT: What is happening is on button click somehow a function is getting called which is present on Page.Load
protected void getEntriesRight()
{
j = (int)Session["j"];
int n1 = j + 3;
for (; j <= n1; j++)
{
if (j < fr.data.Length)
{
HtmlGenericControl listItem = new HtmlGenericControl("li");
HtmlGenericControl a1 = new HtmlGenericControl("a");
Label anchor = new Label();
Image im = new Image();
btn = new Button();
im.ImageUrl = fr.data[j].pic_square;
im.Height = 45;
im.Width = 47;
btn.CssClass = "btn-add";
btn.Text = "Invite";
to[j] = fr.data[j].uid;
btn.ID = "btn" + j;
a1.Attributes.Add("href", "#");
anchor.Text = fr.data[j].name;
a1.Controls.Add(btn);
a1.Controls.Add(im);
a1.Controls.Add(anchor);
listItem.Controls.Add(a1);
list.Controls.Add(listItem);
btn.Click += new EventHandler(btn_Click);
}
}
Session["j"] = j;
}
Help!
Dynamically generated controls have to be recreated on every postback in order for their events to fire. This is one of the most commonly-encountered problems with generating controls programmatically in .NET, and it is discouraged if you can find a way around it.
For example, if you have a button that should only be present when another button is clicked, have the button in the page to begin with, and use the Visible property to control whether it is shown or not.
Regarding your edit. Every post-back to the server, even inside an UpdatePanel, is going to call Page_Load. If you want to detect whether a request has come from an UpdatePanel then you need to check !Page.IsAsync before calling the function.
So in my program i created a struct with a button and a number value... like this
struct box
{
public int numberValue;
public Button button;
}
I then made a 2D array of this struct
box[,] boxes = new box[20, 20];
Now what i did was make 400 buttons and assigned them to each index of the array... like this
private void createBoxes()
{
int positionX;
int positionY;
for (int i = 0; i < 20; i++)
{
for (int j = 0; j < 20; j++)
{
positionX = 20 + (25 * i);
positionY = 20 + (25 * j);
boxes[i, j].button = new System.Windows.Forms.Button();
boxes[i, j].button.Location = new System.Drawing.Point(positionX,positionY);
boxes[i, j].button.Size = new System.Drawing.Size(25, 25);
this.Controls.Add(boxes[i, j].button);
boxes[i, j].button.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
boxes[i, j].button.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
boxes[i, j].button.Visible = true;
boxes[i, j].button.Name = "button";
boxes[i, j].button.Click += new EventHandler(buttonClick);
}
}
}
Now when i make the event handler i want to send "boxes[i,j]" not just "boxes[i,j].button" is there anyway to do this?
Short of defining your own anonymous event handler, there's an easy way to do what you want:
boxes[i, j].button.Tag = boxes[i, j];
Then later:
private void buttonClick(object sender, EventArgs e)
{
var box = ((Button)sender).Tag as box;
}
This can be solved via an anonymous event handler.
var box = boxes[i, j]; // You must use a new variable within this scope
box.button.Click += (obj, args) => buttonClick(box, args);
This is the quickest solution with the least code. Just be aware that anonymous event handlers are notorious for hidden gotchas, and the need to assign a new box variable is an example. The following code will run, but no matter which button you press, the last-assigned values of i and j would be used within the handler.
boxes[i,j].button.Click += (obj, args) => buttonClick(boxes[i,j], args);
No, this is not possible. The individual button control is the one that raises the event, thus it is the object referenced by the sender parameter. The array that contains the button control is irrelevant.
This behavior is by-design. If you wanted to change a property of the button in response to the user clicking on it, it would be impossible to do unless you knew which individual button was clicked. Having only a reference to the array that contains all of the buttons would not provide sufficient information about the individual button that was clicked.