Storing value in ASP.NET button - c#

I have this code:
DataTable characterDataTable = character.getAllCharacters();
foreach(DataRow row in characterDataTable.Rows)
{
Button button = new Button();
button.Text = row["character"].ToString();
button.ID = row["character"].ToString() + "_btn";
button.Click = "character_btn_Click";
}
The characterDataTable returns 3 rows with a character and id column for instance char1, char2 and char3. Now I'm trying to create buttons depending on how many rows are retrieved and then trying to set a value to the button so when a button is clicked it will retrieve the value.. I want the value to be set as the ID of the row..
This is what I have at the moment:
protected void character_btn_Click(object sender, EventArgs e)
{
// Get value of clicked button
}
Does anyone know how to store a value in an ASP.NET button and retrieve it when it has been clicked?

To add a click handler to a Button, you should do this:
button.Click += character_btn_Click;
You can use CommandName to pass a "value" to the event handler. So the code becomes:
DataTable characterDataTable = character.getAllCharacters();
foreach(DataRow row in characterDataTable.Rows)
{
Button button = new Button();
button.Text = row["character"].ToString();
button.ID = row["character"].ToString() + "_btn";
button.CommandName = row["id"].ToString();
button.Click += character_btn_Click;
}
The click handler is then:
void character_btn_Click(object sender, EventArgs e)
{
Button btn = sender as Button;
string value = btn.CommandName;
}

Related

Get object/item on button click (dynamically created button) - stack panel

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.

C# Dynamic button not firing click event

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.

c# add button event programmatically

Trying to add buttons programmatically to a webform.
Some work - others don't.
In the code below I add btnY and btnX in the Page_Load.
These both work - they show on the page and fire the event
and the code in the event handler works....
In the page load I also run bindData which gets a DataTable
and uses the data to create controls.
in the example I am only creating Button.
These buttons will appear on the page correctly but when clicked
they only do a postback ..
the code in the event handler doesn't work - does it get called?
The event handler is the same for all the buttons.
Any ideas why or how I can make it work?
protected void Page_Load(object sender, EventArgs e)
{
PlaceHolder1.Controls.Add(btn("btnY", "Y"));
Pages P = new Pages();
bindData(P.DT);
PlaceHolder1.Controls.Add(btn("btnX", "X"));
}
Button btn(string id, string text)
{
Button btn1 = new Button();
btn1.ID = id;
btn1.Text = text;
btn1.Click += new System.EventHandler(this.btn_click);
return btn1;
}
protected void bindData(DataTable dt)
{
foreach (DataRow row in dt.Rows)
{
render(Convert.ToInt32(row["PageKey"]));
}
}
protected void render(int pageKey)
{
PlaceHolder1.Controls.Add(btn("btn_" + pageKey.ToString(), "Edit"));
}
protected void btn_click(object sender, EventArgs e)
{
Button btn = (Button)sender;
string id = btn.ID;
Pages P = new Pages();
bindData(P.DT);
lt.Text = "ID=" + id;
}
Never mind .. figured it out .. example above should work, my actual code had a if (!Page.PostBack) that caused the problem

how to execute click event on dynamically created button in c#.net

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;
}

Click EventHandler not firing

My newly created button in my gridviewrow is not firing its EventHandler or the RowCmmand Event and then when the page Reload after pressing the Button newly added row is missing probably because I can't call my BindData method. I have removed the Click eventHandler from the Button and just used the OnRowCommand Event and I still am getting nothing
protected void CustomGridView_DataBound(object sender, EventArgs e)
{
int count = ((GridView)sender).Rows.Count;
GridViewRow row = new GridViewRow(-1, -1, DataControlRowType.DataRow, DataControlRowState.Insert);
TableCell cell = new TableCell();
Button button = new Button();
button.Text = "Insert";
button.ID = "Insert";
button.CommandName = "Insert";
button.Click += new EventHandler(insertButton_Click);
cell.Controls.Add(button);
row.Cells.Add(cell);
for (int i = 0; i < ((GridView)sender).Columns.Count; i++)
{
cell = new TableCell();
cell.Controls.Add(new TextBox { ID = "Text" + i });
row.Cells.Add(cell);
}
Table table = ((GridView)sender).Rows[0].Parent as Table;
table.Rows.AddAt(count + 1, row);
}
protected void insertButton_Click(object sender, EventArgs e)
{
lblInsert.Text = "Hello World";
}
protected void CustomGridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Insert")
{
lblInsert.Text = "Hello World";
}
}
Remove the button.Click += new EventHandler(insertButton_Click); statement from your code. The RowCommand event of GridView controll will be fired when button is pressed. For more info - How to: Respond to Button Events in a GridView Control.
You need to attach to the grid's RowCommand event before the databound. Do it on the constructor or Init event of the page or usercontrol, not in the databound. In the databound you will set the CommandName and CommandArgument properties.
Hope it helps.

Categories

Resources