Dynamically generating buttons in ASP.NET and passing values to Codebehind - asp.net

I'm using a foreach loop to generate content how do I listen for a button click to call codebehind function. I can't set a value for a ASP button. How should I go about this ? When the user clicks on a button I want the ID for the user they clicked on to get passed to codebehind

You can pass the ID in the CommandArgument property of a button and you can assign the onclick event all inside the loop:
//for loop
//...
Button btn = new Button();
//etc
btn.CommandArgument = theID;
btn.Click += new EventHandler(btn_Click);
//...
//end for loop
protected void btn_Click(object sender, EventArgs e)
{
//Need to know which btn was clicked
Button btn = sender as Button;
if(btn == null)
{
//throw exception, etc
}
int id = Convert.ToInt32(btn.CommandArgument);
//etc
}

You can use Runtime generated Button Id to pass values to it.
//Counter for Dynamic Buttons.
int DynamicButtonCount = 1;
//This event generates Dynamic Buttons.
private void btnGenerate_Click(object sender, EventArgs e)
{
string name = "Dynamic Button_" + DynamicButtonCount;
Button btnDynamicButton = new Button();
btnDynamicButton.Name = name;
btnDynamicButton.Text = name;
btnDynamicButton.Id= DynamicButtonCount; //Use this id value
btnDynamicButton.Size = new System.Drawing.Size(200, 30);
btnDynamicButton.Location = new System.Drawing.Point(40, DynamicButtonCount * 40);
btnDynamicButton.Click += new EventHandler(this.btnDynamicButton_Click);
Controls.Add(btnDynamicButton);
DynamicButtonCount++;
}
//This event is triggered when a Dynamic Button is clicked.
protected void btnDynamicButton_Click(object sender, EventArgs e)
{
Button dynamicButton = (sender as Button);
MessageBox.Show("You clicked. " + dynamicButton.Name);
}

Related

ASP.NET dynamically added button click event doesnt work

In my webform app I have gridview with SQLDataSource. Now, I need to add button dynamically into one cell of each row (button must have value of cell) of this gridview. I added button for each cell, and also added click event for these buttons. But when I click these buttons click event doesn't work. Can everyone help?
protected void gvEmployee_RowDataBound(object sender, Obout.Grid.GridRowEventArgs e)
{
Button btn = new Button();
btn.Text = e.Row.Cells[8].Text;
if (e.Row.Cells[8].Text == "1")
{
btn.BackColor = Color.Red;
}
else
{
btn.BackColor = Color.Green;
}
e.Row.Cells[8].Text = "";
btn.Click += btn_Click;
e.Row.Cells[8].Controls.Add(btn);
}
protected void btn_Click(object sender, EventArgs e)
{
Button btn = (Button)sender;
GridViewRow gvr = (GridViewRow)btn.NamingContainer;
}

retrieve data key of selected row in gridview in asp.net

I have a button (item template) in any rows of a gridView.
I want when user clicks on this button, I retrieve dataKey of row that there is that button in it.
how can I do this?
(sorry,I can't speak and write English very well)
Assuming you have one DataKey and it is an int and the row of the button isn't necessarily selected and you have connected the following function to the buttons in your template field:
protected void RowClicked(object sender, EventArgs e)
{
Button TempButton = sender as Button;
if (TempButton != null)
{
GridViewRow GVR = TempButton.Parent.Parent as GridViewRow;
if (GVR != null)
{
int ID = (int) GridView1.DataKeys[GVR.DataItemIndex].Value;
}
}
}
Try the SelectedIndexChanged event. Something like this:
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e){
TextBox1.Text = GridView1.SelectedRow.Cells[1].Text;
TextBox2.Text = GridView1.SelectedRow.Cells[2].Text;
.
.
.
}

Wire up button created at runtime

Im creating some buttons based on a value of some runtime variable (i dont even know how many).
My code for the button is as follows:
Button cancel = new Button();
cancel.Text = "Cancel";
cancel.ID = "cancelEnrollmentForStudent" + zapsanePredmetyList.ElementAt(i).ID.ToString() + "-" + i ;
cancel.Click += new EventHandler(cancelEnrollment);
string toCancel = selectedSubject.SelectedValue + ";" + studentToEnroll.SelectedValue;
cancel.CommandArgument = toCancel;
while the code for the click method is
protected void cancelEnrollment(object sender, EventArgs e)
{
//do something when button clicked.
Button sourceButton = (Button)sender;
string[] data = sourceButton.CommandArgument.Split(';');
}
However, the click method is not firing up when the button is clicked. I suppose this has something to do with the fact, that I build the button at runtime. Cld someone advise on how to get this method fire up?
Thanks,
Ondrej
You have to override OnInit add the code in OnInit method.
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
Button btn = new Button();
btn.ID = "btn1";
btn.Text = "Button1";
btn.Click += new EventHandler(btn_Click);
this.form1.Controls.Add(btn);
}
void btn_Click(object sender, EventArgs e)
{
Button bt = (Button)sender;
bt.Text = "Changed";
}

Make event for a multiple buttons and know which button been clicked

I am writing an web app in asp.net,
In the code behind I have this code:
foreach(UserDetails _UD in m_TeachersDetailsList)
{
Button button = new Button();// a Button control
button.Text = "click";
button.ID = "SelectedTeacher";
TableCell tableCell = new TableCell();// a Cell control
tableCell.Controls.Add(button);
TableRow tableRow = new TableRow();
tableRow.Cells.Add(tableCell); // a table row
TableSearchResult.Rows.Add(tableRow); // a table that had been created in the aspx
}
How can I make an event that when you click on the button you go to a function,
and how can I know which button had been click and Brought me to my function.
thanks.
You do this
int id = 0;
foreach(UserDetails _UD in m_TeachersDetailsList)
{
Button button = new Button();// a Button control
button.Text = "click";
button.ID = "selectedTeacher" + id++;
TableCell tableCell = new TableCell();// a Cell control
tableCell.Controls.Add(button);
TableRow tableRow = new TableRow();
tableRow.Cells.Add(tableCell); // a table row
TableSearchResult.Rows.Add(tableRow); // a table that had been created in the aspx
button.Click += new EventHandler(this.button_Click);
}
And common event handler
protected void button_Click(object sender, EventArgs e)
{
//This way you will get the button clicked
Button button = (Button)sender;
}
Important
You will need to add the controls in OnInit.
Hope this works for you.
ASPX
asp:Button ID="btnTest" runat="server" onclick="btn_Click"
Codebehind
protected void btn_Click(object sender, EventArgs e)
{
Button mybutton = (Button)sender;
Response.Write(mybutton.ID);
}
Just use btn_Click as the onclick for each of your buttons. Then use the "sender" to determine which control sent the request.
Don't set the button's id, let it default. Set the button's CommandArgument property instead:
foreach (UserDetails _UD in m_TeachersDetailsList)
{
Button button = new Button();// a Button control
button.Text = "click";
button.CommandArgument = _UD.UserDetailID.ToString(); // some unique identifier
// this is optional, if you need multiple actions for each UserDetail:
button.CommandName = "SomeAction"; // optional
button.Command += new EventHandler(detailButton_Handler);
// ...etc...
}
Then your handler needs to check the CommandName and CommandArgument values:
public void detailButton_Handler(object sender, EventArgs e)
{
string DetailID = e.CommandArgument.ToString();
switch (e.CommandName.ToString())
{
case "SomeAction":
/// Now you know which Detail they clicked on
break;
case "OtherAction":
break;
}
}

CheckedChanged event for Dynamically generated Checkbox column in DataGrid(Asp.Net)

I have a datagrid (Asp.Net) with dynamically generated checkbox column..I am not able to generate the checkedChanged event for the checkbox..
Here is my code:
public class ItemTemplate : ITemplate
{
//Instantiates the checkbox
void ITemplate.InstantiateIn(Control container)
{
CheckBox box = new CheckBox();
box.CheckedChanged += new EventHandler(this.OnCheckChanged);
box.AutoPostBack = true;
box.EnableViewState = true;
box.Text = text;
box.ID = id;
container.Controls.Add(box);
}
public event EventHandler CheckedChanged;
private void OnCheckChanged(object sender, EventArgs e)
{
if (CheckedChanged != null)
{
CheckedChanged(sender, e);
}
}
}
and Here is the event
private void OnCheckChanged(object sender, EventArgs e)
{
}
Thanks In advance
When do you add your custom column? If it is on load, then it is too late. Load it on init. I.e. following works with your code:
protected void Page_Init(object sender, EventArgs e)
{
ItemTemplate myTemplate = new ItemTemplate();
myTemplate.CheckedChanged += new EventHandler(myTemplate_CheckedChanged);
TemplateField col = new TemplateField();
col.ItemTemplate = myTemplate;
col.ItemStyle.Wrap = false;
grid.Columns.Add(col);
}
If your checkbox ID's are not being set the same way on every postback, then they can never be connected to the event handlers when it comes time to process the events. Where is your field "id" coming from?

Resources