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
Related
I'm looking to create 4 groups with 8 items in a group with check boxes. After these are checked I'd like individual webpages to open up. I'd like to be able to either click group button 1 to open up 8 pages or to individually check an item and have it open the webpage. My problem is when I click the group 1 button not all pages open up. Usually only 6 but I have had random number of pages open up. If i click individual the page opens up fine. Here is a snippet of the code.
private void btnGroup1_Click(object sender, EventArgs e)
{
foreach (Control c in groupBox1.Controls)
{
if (c is CheckBox)
{
CheckBox cb = (CheckBox)c;
if (cb.Checked == false)
{
cb.Checked = true;
btnGroup1.Text = "Uncheck 1";
}
else
{
cb.Checked = false;
btnGroup1.Text = "Check 1";
}
}
}
}
private void chkNYALL_CheckedChanged(object sender, EventArgs e)
{
if (chkNYALL.Checked == true)
{
chkNYALL.Checked = true;
System.Diagnostics.Process.Start("www.google.com");
}
else
{
chkNYALL.Checked = false;
}
}
private void NYBAT_CheckedChanged(object sender, EventArgs e)
{
if (chkNYBAT.Checked == true)
{
chkNYBAT.Checked = true;
System.Diagnostics.Process.Start("www.google.com");
}
else
{
chkNYBAT.Checked = false;
}
}
Here's a quick sample that could get you going.
In this snippet, I am dynamically creating 2 GroupBox, into which I am dynamically creating multiple CheckBoxes, and 1 Button. Each CheckBox is subscribed to a CheckedChanged event handler, and the button is subscribed to a Click event.
When checked, a Checkbox will trigger the opening of a page.
When clicked, the Button will trigger the opening of all checked pages.
You will notice I use the CheckBox.Tag property to host the value (aka URL)
using System;
using System.Drawing;
using System.Windows.Forms;
namespace OpenWebPageOnCheckboxCheck_46934789
{
public partial class Form1 : Form
{
GroupBox gb1 = new GroupBox();
GroupBox gb2 = new GroupBox();
Button btn1 = new Button();
Button btn2 = new Button();
public Form1()
{
InitializeComponent();
InitGroupBoxes();
AddCheckboxesToGroup("check1", "www.google.com", gb1);
AddCheckboxesToGroup("check2", "www.yahoo.com", gb1);
AddCheckboxesToGroup("check3", "www.bing.com", gb1);
AddCheckboxesToGroup("check4", "www.duckduckgo.com", gb1);
AddCheckboxesToGroup("check1", "www.wikipedia.com", gb2);
AddCheckboxesToGroup("check2", "www.stackoverflow.com", gb2);
InitButtons();
}
private void InitButtons()
{
btn1.Text = "Open checked";
btn1.Click += Btn1_Click;
btn1.Location = new Point(145, 5);
gb1.Controls.Add(btn1);
btn2.Text = "Open checked";
btn2.Click += Btn2_Click;
btn2.Location = new Point(145, 5);
gb2.Controls.Add(btn2);
}
private void Btn2_Click(object sender, EventArgs e)
{
foreach (Control item in gb2.Controls)
{
if (item is CheckBox)
{
if (((CheckBox)item).Checked)
{
LaunchPage(item.Tag.ToString());
}
}
}
}
private void Btn1_Click(object sender, EventArgs e)
{
foreach (Control item in gb1.Controls)
{
if (item is CheckBox)
{
if (((CheckBox)item).Checked)
{
LaunchPage(item.Tag.ToString());
}
}
}
}
private void AddCheckboxesToGroup(string cbText, string cbValue, GroupBox gb)
{
CheckBox cb = new CheckBox();
cb.CheckedChanged += Cb_CheckedChanged;
cb.Text = cbText;
cb.Tag = cbValue;
if (gb.Controls.Count > 0)
{
cb.Location = new Point(gb.Controls[gb.Controls.Count - 1].Location.X, gb.Controls[gb.Controls.Count - 1].Location.Y + gb.Controls[gb.Controls.Count - 1].Height + 2);
}
else
{
cb.Location = new Point(5, 5);
}
gb.Controls.Add(cb);
}
private void Cb_CheckedChanged(object sender, EventArgs e)
{
if (((CheckBox)sender).Checked)
{
LaunchPage(((CheckBox)sender).Tag.ToString());
}
}
private void LaunchPage(string pageURL)
{
System.Diagnostics.Process.Start(pageURL);
}
private void InitGroupBoxes()
{
gb1.Dock = DockStyle.Top;
gb1.BackColor = Color.Aqua;
gb2.Dock = DockStyle.Bottom;
gb2.BackColor = Color.DarkRed;
this.Controls.Add(gb1);
this.Controls.Add(gb2);
}
}
}
I'm creating a matching game. What I'm trying to accomplish is a check that will see if the tag of the previously clicked button, matches the tag of the "currently" clicked button. If those tags match, it would disable both the buttons as they are no longer an option in the game.
Part of my confusion is where to integrate this portion of code without screwing up the majority of my work.
Random myRandom = new Random();
var buttons = new List<Button> { button1, button2, button3, button4, button5, button6, button7, button8, button9, button10, button11, button12 };
var carString = new List<string> { "Camaro", "Mini Cooper", "Porsche 944", "Ford Focus", "Chevy Blazer", "Model T", "Camaro", "Mini Cooper", "Porsche 944", "Ford Focus", "Chevy Blazer", "Model T" };
while (matchingButtonIndex < numOfButtons)
{
int index = myRandom.Next(carString.Count);
var name = carString[index];
if (name != null)
{
buttons[matchingButtonIndex].Tag = name;
carString[index] = null;
matchingButtonIndex = matchingButtonIndex + 1;
}
}
}
void SwitchTagWithText()
{
string text = lastButton.Text;
lastButton.Text = lastButton.Tag.ToString();
lastButton.Tag = text;
}
private void button1_Click(object sender, EventArgs e)
{
if (lastButton != null)
{
SwitchTagWithText();
}
lastButton = sender as Button;
SwitchTagWithText();
buttoncount++;
label2.Text = buttoncount.ToString();
}
I would suggest that you create a new class to handle this e.g.
public class ButtonManager {
private Button lastButton;
public void SwitchTagWithText(Button button){
string text = lastButton.Text;
lastButton.Text = lastButton.Tag.ToString();
lastButton.Tag = text;
// Or whatever the logic is you need.
}
public void ButtonClicked(Button button){
this.SwitchTagWithText(button);
// Or whatever the logic is you need.
}
}
OK the above is incomplete, but hopefully the main idea comes through - that you have a separate class to deal with the reading/setting of tag values and determining whether buttons should be disabled.
So in your from load, create a new instance of ButtonManager that can be used throughout the form's code, so make it a field.
You have a button count variable which you are incrementing with each click. So you can use that:
private void button1_Click(object sender, EventArgs e)
{
thisButton = sender as Button;
buttoncount++;
SwitchTagWithText(thisButton);
if (buttoncount == 1)
{
lastButton = thisButton;
}
else if (buttoncount == 2)
{
if (lastButton.Tag == thisButton.tag)
{
// Disable both buttons.
}
else
{
// Switch buttons back
}
buttoncount = 0;
}
}
Something like:
private void button1_Click(object sender, EventArgs e)
{
if (lastButton != null)
{
SwitchTagWithText();
var thisButton = sender as Button;
if(thisButton.Text != lastButton.Text
&& thisButton.Tag.ToString() == lastButton.Tag.ToString())
{
//two different buttons with the same tag were clicked in succession
thisButton.Enabled = false;
lastButton.Enabled = false;
lastButton = null;
return;
}
lastButton = thisButton;
}
else
{
lastButton = sender as Button;
}
SwitchTagWithText();
buttoncount++;
label2.Text = buttoncount.ToString();
}
How can I get the name of the object last clicked on a panel? The trick is there is a big array of buttons on the panel (btn[1] ... btn [200]). How can I check if I clicked on button b[180], or b[11] or even outside the panel (no button)? Also the buttons are generated at page load via coding.
Thank you. Anna
EDIT:
Thank you! Another issue that arose (this generated a NULL object reference):
I have a method on the same level as buttonHandler(), it is named HowManyClicked() and it's called from within buttonHandler(). Inside HowManyClicked() I want to identify Button btn1 = Panel2.FindControl(x) as Button; where x is, for example, buttonArray[2,3]. But I always get NULL. Is the button array buttonArray not identifiable by name once out of the method that generated it??
public void buttonHandler(object sender, EventArgs e)
{
Button btn = sender as Button;
//string tt = btn.ToolTip.ToString();
btn.BackColor = Color.Red;
statusL.Text = HowManyClicked().ToString();
}
public int HowManyClicked()
{
int sum=0;
for (int a = 0; a < 10; a++)
for (int b = 0; b < 14; b++)
{
string x = "buttonArray[" + a + ", " + b + "]";
statusL.Text = x;
Button btn1 = Panel2.FindControl(x) as Button;
if (btn1.BackColor == Color.Red) sum += 1;
}
return sum;
}
As #AVD commented you can get the button originating the postback casting the sender object, you can also use the CommandName and CommandArgument properties from the button object (they are usually used when the button is inside a Grid, DataList etc but you can use them in this context if you need):
protected void Page_Init(object sender, EventArgs e)
{
var s = Enumerable.Range(1, 10);
foreach (var item in s)
{
var b = new Button();
b.Text = "My Button " + item.ToString();
b.CommandName = "custom command";
b.CommandArgument = item.ToString();
b.Click += new EventHandler(b_Click);
this.myPanel.Controls.Add(b);
}
}
void b_Click(object sender, EventArgs e)
{
var current = sender as Button;
this.lblMessage2.Text = "Clicked from array buttons: <br/>Command Name: " + current.CommandName + "<br/>Args: " + current.CommandArgument + "<br/>Button Unique ID: " + current.UniqueID + "<br/>Client ID: " + current.ClientID;
}
Page:
<asp:Panel runat="server" ID="myPanel">
</asp:Panel>
<asp:Label ID="lblMessage2" runat="server" />
This code generates something like:
As an additional note, Microsoft recommends to create dynamic controls in the PreInit event or in case you are using a master page, in the Init event
source
Edited
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
this.ViewState["count"] = 0;
}
}
protected void Page_Init(object sender, EventArgs e)
{
var s = Enumerable.Range(1, 10);
foreach (var item in s)
{
var b = new Button();
b.Text = "My Button " + item.ToString();
b.Click += new EventHandler(buttonHandler);
this.myPanel.Controls.Add(b);
}
}
void buttonHandler(object sender, EventArgs e)
{
// update here your control
var b = sender as Button;
b.BackColor = Color.Red;
HowManyClicked();
}
private void HowManyClicked()
{
var c = (int)this.ViewState["count"];
c++;
this.ViewState["count"] = c;
this.lblMessage2.Text = "Clicked controls: " + this.ViewState["count"].ToString();
}
This produced:
How can I get the name of the object last clicked on a panel?
The first parameter of click handler returns the reference of control/object has raised the event.
public void buttonHandler(object sender, EventArgs e)
{
Button btn=sender as Button;
....
}
I just figured out another fix by just redefining HowManyClicked() so I am adding it here below. Not sure still why the first method (the one in my question) didn't work also. Here goes:
public int HowManyClicked()
{
int sum=0;
foreach (Control cnt in this.Panel2.Controls)
if (cnt is Button)
{
Button btn = (Button)cnt;
if (btn.BackColor == Color.Red)
sum += 1;
}
return sum;
}
}
Thanks everyone!
public partial class Default2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
GenerateButtons generate = new GenerateButtons();
generate.Generate5Controls(PlaceHolder1);
}
}
class GenerateButtons
{
PlaceHolder placeHolder;
public void Generate5Controls(PlaceHolder placeH)
{
placeHolder = placeH;
for (int i = 0; i < 5; i++)
{
Button newBtn = new Button();
newBtn.Click += btn_Click;
newBtn.Text = "PageLoadButton Created. Number: "+i;
placeHolder.Controls.Add(newBtn);
}
}
public void btn_Click(object sender, EventArgs e)
{
Button newBTN = new Button();
newBTN.Text = "A New Button was added by the button event btn_click";
newBTN.Click += btn2_Click;
placeHolder.Controls.Add(newBTN);
}
public void btn2_Click(object sender, EventArgs e)
{
Button newBTN = new Button();
newBTN.Text = "A New Button was added by the button event btn2_click";
placeHolder.Controls.Add(newBTN);
}
}
I want the events btn_click & btn2_click to fire every post back.. When i click the button that was programmatically created it disappears after each postback and its event doesnt fire (btn2_click). I know i could generate the button at the postback.. But I dont want to do that!! I want to know how I could update the state of the placeholder... so that the only button will appear and the 5 buttons generated in Generate5Controls(PlaceHolder placeH) to disappear.
I could use a bool Viewstate to prevent this generate.Generate5Controls(PlaceHolder1); from being execute..
But the question is how do I make the programmatically generated button to appear!?
You should generate controls on every PostBack or you can generate controls once, save in session and add generated controls from session on page_load event.
protected void Page_Load(object sender, EventArgs e)
{
if(Session["GeneratedButtons"] == null)
{
GenerateButtons generate = new GenerateButtons();
generate.Generate5Controls(PlaceHolder1);
}
else
{
List<Control> generatedControls = Session["GeneratedButtons"] as List<Control>;
foreach(Control oneControl in generatedControls)
{
PlaceHolder1.Controls.Add(oneControl);
}
}
}
class GenerateButtons
{
PlaceHolder placeHolder;
public void Generate5Controls(PlaceHolder placeH)
{
placeHolder = placeH;
List<Control> generatedControls = new List<Control>();
for (int i = 0; i < 5; i++)
{
Button newBtn = new Button();
newBtn.Click += btn_Click;
newBtn.Text = "PageLoadButton Created. Number: "+i;
placeHolder.Controls.Add(newBtn);
AddControlToSession(newBtn);
}
}
public void btn_Click(object sender, EventArgs e)
{
Button newBTN = new Button();
newBTN.Text = "A New Button was added by the button event btn_click";
newBTN.Click += btn2_Click;
placeHolder.Controls.Add(newBTN);
AddControlToSession(newBtn);
}
public void btn2_Click(object sender, EventArgs e)
{
Button newBTN = new Button();
newBTN.Text = "A New Button was added by the button event btn2_click";
placeHolder.Controls.Add(newBTN);
AddControlToSession(newBtn);
}
private void AddControlToSession(Control ctrl)
{
List<Control> generatedControls = Session["GeneratedButtons"] as List<Control>;
if(generatedControls == null)
{
generatedControls = new List<Control>();
}
generatedControls.Add(ctrl);
Session["GeneratedButtons"] = generatedControls;
}
}
I have 20 radiobuttons on the page and I want to know which one of them was clicked.
protected void Page_Load(object sender, EventArgs e)
{
Button newBTN = new Button();
newBTN.Text = "Button 1";
PlaceHolder1.Controls.Add(newBTN);
for (int i = 0; i < 20; i++)
{
RadioButton r = new RadioButton();
r.ID = i.ToString();
r.CheckedChanged += RadioButton1_CheckedChanged;
PlaceHolder1.Controls.Add(r);
}
}
New Updated code.. NOTE: THE CODE DOESNT RELATE TO THE ABOVE CODE.
public List<int> ThreadID2Treat { get { return ViewState["Checked"] == null ? null : (List<int>)ViewState["Checked"]; } set { ViewState["Checked"] = value; } }
protected void CheckBox1_CheckedChanged(object sender, EventArgs e)
{
var rad = (CheckBox)sender;
int threadID = int.Parse(rad.ID.ToString());
ThreadID2Treat.Add(threadID);
}
public void DeleteButton_Clicked(object sender, EventArgs e)
{
foreach (var item in ThreadID2Treat)
{
UsefulStaticMethods.DeleteThreads(item);
}
}
How do i find out?
var rad = (RadioButton)sendder;
Response.Write("RadioButton Id :" + rad.Id.ToString());
You could try the above.
Update :
To get all select radio buttons in PlaceHolder make sure the AutoPostBack is not set on the radio buttons. You dont need to add CheckChanged Event. "r.CheckedChanged += RadioButton1_CheckedChanged;" <= remove.
StringBuilder stringBuilder = new StringBuilder();
foreach (var control in placeHolder1.Controls)
{
var rad = control as RadioButton;
if (rad != null)
{
if (rad.Checked)
stringBuilder.AppendLine(String.Format("Radion Button Checked : {0}", rad.ID));
}
}
Response.Write(stringBuilder.ToString());
With the parameter sender you have a direct reference to the event-source control.
var rb = (RadioButton)sender;
If you want to trigger this event and the postback directly, you must set the RadioButton's AutoPostBack-Property to true.
protected void RadioButton1_CheckedChanged(object sender, EventArgs e)
{
if (sender is RadioButton)
{
RadioButton radioButton = (RadioButton)sender;
//Code to use radioButton's properties to do something useful.
// get the radio button by its ID
string id = radioButton.ID;
}
}
You can try this.
RadioButton r = sender as RadioButton;
Response.Write(r.Id);
Cast sender as RadioButton:
RadioButton r = sender as RadioButton;
if(r != null)
{
//Do stuff
}