It reloads the page empty when I click the button. How do I fire click event on button click? I think Page.IsPostBack is the reason it reloads the page empty instead of showing the label.
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack == false)
{
account account = new account();
accountManager accountManager = new accountManager();
group group = new group();
groupManager groupManager = new groupManager();
string emailAddress;
emailAddress = HttpContext.Current.User.Identity.Name;
account = accountManager.getAccInfoByEmailAddress(emailAddress);
group = groupManager.getGroupLeader(account.groupNo);
if (account.groupNo == 0)
{
divMessage.InnerHtml = "You are not in any group.";
}
else
{
try
{
Button btn = new Button();
btn.Text = "Click";
btn.Click += new EventHandler(button_Click);
form1.Controls.Add(btn);
}
catch (Exception)
{
divMessage.InnerHtml = "Unable to retrieve data. Please contact administrator if the problem persists.";
}
}
}
}
.
private void button_Click(object sender, EventArgs e)
{
Label Label1 = new Label();
Label1.Text = "rthfg";
form1.Controls.Add(Label1);
}
When you click the button, or somehow else generate a postback, ASP.NET creates the page (as it always does) and tries to find the source of the request, that is the button you clicked. In your case this button is no longer on the page, so ASP.NET cannot find anything, end does not fire the event.
Resolution seems easy enough in your case - just always create the button and put it on the page, regardless of the postback:
if (!Page.IsPostBack)
{
...
}
Button btn = new Button();
btn.Text = "Click";
btn.Click += new EventHandler(button_Click);
form1.Controls.Add(btn);
Btw, why make the button dynamic? Dynamic controls are always harder to manage.
Related
I am looping my customers, and for each customer I need to create one button in case
I would like to delete that specific customer.
So here is my code:
foreach (var item in customersList)
{
Button btn = new Button();
btn.Content = "Customer": + " " + item.Value;
btn.Height = 40;
btn.Click += btn_Click;
TextBox cust = new TextBox();
cust.Height = 40;
cust.Text = item.Value;
stackCustomers.Children.Add(cust);
stackCustomers.Children.Add(btn);
}
How could I attach event Click on my button so when I click on It I get customer?
void btn_Click(object sender, RoutedEventArgs e)
{
//I tried this but it is not working, unfortunatelly...
Customer cust = (Customer)sender;
}
The easy way: attach customer to the Button.Tag property
Button btn = new Button();
btn.Tag = item; // .Value maybe?
// ...
void btn_Click(object sender, RoutedEventArgs e)
{
var button = sender as Button;
Customer cust = (Customer)button.Tag;
}
What might be better: Create a visual representation of each customer item, where the button is contained. Use Button.Command and Button.CommandParameter={Binding PathToCustomer} instead of Button.Click.
I have a small ASP web application which can be used to determine whether or not 2 users have been assigned the same seat number.
To display the results / functionality, I decided to go with an asp:Table, where each row has 2 buttons (one for each user).
The administrator can click either one of the buttons to clear that user's seat number value from the system.
Here is the code which builds the table cells:
BuildDuplicateTable (called in Page_Load)
private void BuildDuplicateTable(List<Duplicate> duplicates)
{
foreach (var dup in duplicates)
{
var row = new TableRow();
var user1cell = new TableCell();
var seatcell = new TableCell();
var user2cell = new TableCell();
var button1 = new Button();
button1.Text = $"{dup.UserOne.UserName}";
var button1cell = new TableCell();
button1cell.Controls.Add(button1);
button1.Click += new EventHandler(Test);
var button2 = new Button();
button2.Text = $"{dup.UserTwo.UserName}";
var button2cell = new TableCell();
button2cell.Controls.Add(button2);
button2.OnClientClick = "return true";
button2.Click += (sender, eventArgs) =>
{
ActiveDirectory.ClearProperty(dup.UserTwo.UserName, "extensionAttribute2");
};
user1cell.Text = dup.UserOne.UserName;
seatcell.Text = dup.UserOne.SeatNumber;
user2cell.Text = dup.UserTwo.UserName;
row.Cells.Add(button1cell);
row.Cells.Add(seatcell);
row.Cells.Add(button2cell);
MyAspTable.Rows.Add(row);
}
}
My issue is that when I click on any of the buttons, the page is simply refreshed, and the data is no longer displayed (as I am handling postback in Page_Load). My event handler never fires ... Notice that in the code above I left in 2 separate methods of attaching an event handler that I tried - neither of them works!
Duplicate
class Duplicate
{
public UserSeatNumberRelationship UserOne;
public UserSeatNumberRelationship UserTwo;
public Duplicate(UserSeatNumberRelationship userone, UserSeatNumberRelationship usertwo)
{
UserOne = userone;
UserTwo = usertwo;
}
}
UserSeatNumberRelationship
class UserSeatNumberRelationship
{
public string UserName;
public string SeatNumber;
public UserSeatNumberRelationship(string username, string seatnumber)
{
UserName = username;
SeatNumber = seatnumber;
}
}
Page_Load
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack) return;
DuplicateList = FindDuplicates();
BuildDuplicateTable(DuplicateList);
}
Test
protected void Test(object sender, EventArgs e)
{
ActiveDirectory.ClearProperty(UserName, "extensionAttribute2");
}
As ConnersFan mentioned in the comments, this was being caused by my PostBack handler in Page_Load.
So after removing this line
if (Page.IsPostBack) return;
The event handlers work fine.
I'm creating dynamically generated buttons, and when I click on the button, the Add_Click method doesn't get fired up.
Here is a sample from my code:
protected void SearchRec(object sender, EventArgs e)
{
SearchResultsPanel.Controls.Clear();
string text_to_search = SearchTB.Text;
Friends RecToSearch = new Friends();
List<Friends> ListNFU = DBS.getNonFriendUsers(User.Identity.Name.ToString(), text_to_search);
if (ListNFU.Count != 0)
{
foreach (Friends NFRIndex in ListNFU)
{
string _FriendsOutput = FR_output(NFRIndex);
HyperLink RecHyperLink = new HyperLink();
RecHyperLink.Text = _FriendsOutput;
RecHyperLink.CssClass = "HyperLinkFriends";
RecHyperLink.ID = NFRIndex.UdName;
SearchResultsPanel.Controls.Add(new LiteralControl("<div style='height:32px'>"));
SearchResultsPanel.Controls.Add(RecHyperLink);
Button addUser = new Button();
addUser.CssClass = "ApproveBTN";
addUser.Text = "send";
addUser.Click += new EventHandler(Add_Click);
addUser.ID = NFRIndex.UdName + "3";
SearchResultsPanel.Controls.Add(addUser);
}
}
else
{
Label NoResultsLabel = new Label();
NoResultsLabel.Text = "Nothing is found";
SearchResultsPanel.Controls.Add(NoResultsLabel);
}
SearchResultsPanel.Controls.Add(new LiteralControl("</div>"));
}
private void Add_Click(object sender, EventArgs e)
{
Button btn = (Button)sender;
string _tempID = btn.ID;
string id = _tempID.Substring(0, _tempID.LastIndexOf('3'));
DateTime cdate = new DateTime();
cdate = DateTime.Now;
DBS.AddFriend(User.Identity.Name, id, cdate);
btn.Visible = false;
btn.NamingContainer.FindControl(id).Visible = false;
}
Note: I did something very similar on page_load and it does work.
That is because when the page is reloaded, the control is most probably not recreated. That means that the event won't fire indeed.
You need to place this kind of code in the Page_Load so it gets recreated at postback.
I am trying to build an app, where user can select category and according to it displays its sub categories , these sub categories are buttons, which are dynamically created.
Now, as buttons are dynamically created so I am confuse how to write code under button_click event as I dont know how many subcategories are there.
So is there any way I can execute click event of a particular button , so that I can execute certain commands?
EDITED
This is the code that i tried
Button btnDynamicButton = new Button();
private void btnclick_Click(object sender, EventArgs e)
{
label2.Text = btnDynamicButton.Text;
}
private void btnappetizer_Click(object sender, EventArgs e)
{
groupBox2.Visible =false;
DataTable dt = new DataTable();
dt = itemmasterbl.SelectallrecordFromtblItem(btnappetizer.Text);
for (int i = 0; i < dt.Rows.Count; i++)
{
string name = "Appetizer" + DynamicButtonCount;
Button btnDynamicButton1 = new Button();
btnDynamicButton1.Name = name;
btnDynamicButton1.Text = name;
btnDynamicButton1.Size =
new System.Drawing.Size(150, 30);
btnDynamicButton1.Location =
new System.Drawing.Point(180, DynamicButtonCount * 30);
btnDynamicButton1.Click +=new EventHandler(btnclick_Click);<br>
Controls.Add(btnDynamicButton1);
DynamicButtonCount++;
btnDynamicButton = btnDynamicButton1;
}
}
Once I do this it creates three buttons according to number of values in itemmaster DB under appetizer, but once I click on any of the three buttons the label displays only last buttons text,because in last line I have :
btnDynamicButton = btnDynamicButton1;
Which will last buttons infos,but rather I want which ever button I press, label should display respective text. How can I achieve this.
you can put all your logic into one handler:
System.Windows.Forms.Button b = new System.Windows.Forms.Button();
b.Click += new EventHandler(b_Click);
//finally insert the button where it needs to be inserted.
...
void b_Click(object sender, EventArgs e)
{
MessageBox.Show(((System.Windows.Forms.Button)sender).Name + " clicked");
}
To your edit:
You are storing the reference for your button(s) inside the Field btnDynamicButton. Hence it always gets overwritten with the latest button you have created. You should not reference the button by using a field. The sender parameter of the click-handler contains the button element that has been clicked. See the code above: Simple cast sender to Button and you know which button has been clicked:
private void btnclick_Click(object sender, EventArgs e)
{
Button btn = (Button)sender
label2.Text = btn.Text;
}
I am doing following code to generate dynamic buttons with their click event.
protected void Button1_Click(object sender, EventArgs e)
{
for (int i = 0; i < int.Parse(TextBox1.Text); i++)
{
Button bt = new Button();
bt.Text = "ok";
bt.Click += new EventHandler(bt_click);
this.form1.Controls.Add(bt);
}
}
protected void bt_click(object sender, EventArgs e)
{
Label1.Text = "Clicked";
}
but i am not able to generate the click event of that dynamically generated button.
Can any one help me?
For ASP.NET to be able to execute your event, control which triggered it should also exist on your page after postback. What is going on with your code looks like this:
page has several buttons you placed in design mode
you click button which generates new buttons
page loads again and looks for button you clicked, in the page
button is found, asp looks for event handler and executes it
new dynamic buttons are added and events attached, page renders again
It was all ok up till now, now problem occurs
you click button which was added dynamically
page loads again and looks for button you clicked (so it can find it's handler)
button is not found because it is not created yet. it was created dynamically to be rendered, and it wasn't created after postback at stage where asp is looking for it
General rule is that if you're adding controls dynamically and you want them to trigger events, you should do it latest in Page_Load.
For more details please read ASP.NET Page Life Cycle Overview
My previous submission was on WinForms which I have deleted. Here is the one on asp.net
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
for (int i = 0; i < int.Parse(TextBox1.Text); i++)
{
CreateButton(i);
}
}
}
protected void Button1_Click(object sender, EventArgs e)
{
}
protected void bt_click(object sender, EventArgs e)
{
Button btn = sender as Button;
Label1.Text = btn.Text + " Clicked";
}
private void CreateButton(int id)
{
Button bt = new Button();
bt.Text = "ok" + id.ToString();
bt.Click += new EventHandler(bt_click);
bt.ID = "btn" + id.ToString();
this.Form.Controls.Add(bt);
}
You need to set the position of those new buttons, or they will cover each other.
I'm not sure if its your problem, but you might want to set the location property of eachbutton you add like:
bt.Location = new Point(25,i+55);
you need to add this code in either page load or page_init event of page. then only you can access it. How to add controls dynamically asp.net
protected void Page_Load()
{
for (int i = 0; i < int.Parse(textBox1.Text); i++)
{
Button bt = new Button();
bt.Text = "ok";
bt.Click += new EventHandler(bt_click);
this.Controls.Add(bt);
}
}