Event handler not firing on dynamic button click - c#

I have a dynamically created button with an onclick event handler. The problem is that when I click the button it does not hit the event in the code-behind.
protected void gvOrder_RowDataBound(object sender, GridViewRowEventArgs e)
{
DataTable dt = ds.Tables[0];
DropDownList ddl = new DropDownList();
TextBox txt = new TextBox();
int index = 1;
if (e.Row.RowType == DataControlRowType.DataRow)
{
ddl = e.Row.FindControl("ddlNewO") as DropDownList;
txt = e.Row.FindControl("txtNewT") as TextBox;
}
foreach (DataRow r in dt.Rows)
{
string listitem = Convert.ToString(index);
ddl.Items.Add(listitem);
index++;
}
ddl.SelectedIndex = e.Row.RowIndex;
if (e.Row.RowIndex == 0)
{
ddl.Enabled = false;
txt.Enabled = false;
}
else if (e.Row.RowIndex != 0)
{
ddl.Items.Remove("1");
//Create ED button
if (e.Row.RowType == DataControlRowType.DataRow)
{
Button btnED = new Button();
btnED.ID = "btnED";
btnED.CssClass = "buttonsmall";
//btnED.CommandName = "ED";
btnED.EnableViewState = true;
btnED.Click += new EventHandler(btnED_Click);
foreach (DataRow r in dt.Rows)
{
btnED.Attributes.Add("ID", r.ItemArray[2].ToString());
if (r.ItemArray[3].ToString() == "1")
{
btnED.Text = "Disable";
}
else
{
btnED.Text = "Enable";
}
//Add button to grid
e.Row.Cells[5].Controls.Add(btnED);
}
}
}
}
protected void btnED_Click(object sender, EventArgs e)
{
// Coding to click event
}

So the problem here is that when the page is being recreated on post back - there is no more button! Dynamic controls need to be added on the page on every post back to fire events properly. In your case however on the first load when the GridView is binding you add the button to the page. But on the post back after the click the button is not added again, because GridView is not data bound again. Therefore ASP.NET cannot derive the source of the event, and supresses it.
Fix here is to bind GridView with data on every post back. Literally if you had if (!IsPostBack) - remove it. Or you can add the button in the template field and play with visibility - may be an approach as well.

You need to add a click handler on Row Created not on Data Bound I believe.
protected void gvOrderRowCreated(object sender, GridViewRowEventArgs e)
{
switch (e.Row.RowType) {
case DataControlRowType.DataRow:
Button btn = (Button)e.Row.FindControl("btnED");
btn.Command += btnED_Click;
break;
}
}

Related

No OnClick Event firing after page is open for a few minutes

I've searched for this but didn't find any matching question:
I have a DNN Website hosted on a local server in our company, and I have my own modules, where I have some Forms with TextBoxes and Buttons. I now have the following problem:
When I enter text the time I open the page and click on the Button the OnClick-Event is fired and everything is okay. When I now have the page open for a few minutes and then click on a Button, the page just reloads and the Event is not firing.
I also tried to tebug this multiple times, but the debugger never stops at the OnClick Method if the page is open more than around 5 minutes (I don't know the exact timeout since I don't know which parameter is leading to this)
I am not sure if this is a Problem from IIS, ASP or DNN - so I hoped to find help here. If you need further information, please ask.
Since you asked for the Code, I reduced it to the important lines (total would be a few thousand lines):
View.ascx
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="View.ascx.cs" Inherits="View" %>
...
<asp:Panel runat="server" ID="pnlGridView"></asp:Panel>
...
View.ascx.cs
public partial class View : FremdeBestellungenModuleBase, IActionable
{
...
protected void Page_Load(object sender, EventArgs e)
{
try
{
...
BuildGrids(true);
...
}
catch (Exception exc) //Module failed to load
{
Exceptions.ProcessModuleLoadException(this, exc);
}
}
...
private void BuildGrids(bool all)
{
...
GridView gv = new GridView()
{
ID = "GridView_" + role,
AllowSorting = true,
AutoGenerateColumns = false,
...
};
...
gv.RowDataBound += new GridViewRowEventHandler(Generated_GridView_RowDataBound);
gv.Sorting += new GridViewSortEventHandler(GridviewBestellung_Sorting);
if (Session["sort"] == null)
{
Session[gv.ID] = gv.DataSource = list.Where(elem => elem != null).OrderByDescending(x => x.BestellNr).ToList();
}
else
{
gv.DataSource = Session[gv.ID];
}
gv.DataBind();
if (FindControl(gv.ID) == null)
{
pnlGridView.Controls.Add(gv);
}
}
...
protected void Generated_GridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
GridView gv = sender as GridView;
if (e.Row.RowType == DataControlRowType.DataRow)
{
...
CheckBox chkManager = new CheckBox()
{
ID = "chkManager"
};
e.Row.Cells[ManagerColumns.CheckUndHidden].Controls.Add(chkManager);
...
if (e.Row.RowType == DataControlRowType.Footer)
{
...
Button btnFreigeben = new Button()
{
ID = "btnFreigeben",
Text = "Freigeben",
UseSubmitBehavior = false
};
btnFreigeben.Click += new EventHandler(BtnFreigeben_Click);
...
}
}
protected void BtnFreigeben_Click(object sender, EventArgs e)
{
Button btn = (Button)sender;
GridView gv = (GridView)btn.NamingContainer.NamingContainer;
foreach (GridViewRow r in gv.Rows)
{
CheckBox chkManager = r.FindControl("chkManager") as CheckBox;
if (chkManager.Checked)
{
//do stuff;
BuildGrids(true);
Response.Redirect(Request.RawUrl);
}
}

button click event to create new asp.net combobox

I have an existing drop down list(namely ddlA). On selecting a value in which, I am getting a cascading drop down list(ddlB). The requirement is, I need to create a button on the webform. By clicking the button, I would need to create drop down list dynamically of type ddlA. But here is the tricky part, I am required to present all the values in this dropdown except the selected value in the previous selection(s) of type ddlA.
Here is my code:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
List<DropDownList> DDLList = new List<DropDownList>();
Session["DDLs"] = DDLList;
}
else
{
List<DropDownList> existingDropDowns = (List<DropDownList>)Session["DDLs"];
//Add all existing DropDownLists to Panel
foreach (DropDownList dropdown in existingDropDowns)
{
Panel1.Controls.Add(dropdown);
dropdown.AutoPostBack = true;
Panel1.Controls.Add(new LiteralControl("<br/>"));
}
Session["DDLs"] = existingDropDowns;
}
}
and here is my button click event code:
protected void ddlAdditionBtn_Click(object sender, EventArgs e)
{
List<DropDownList> existingDropDowns = (List<DropDownList>)Session["DDLs"];
DropDownList newDropDown = new DropDownList();
newDropDown.ID = "DDL" + existingDropDowns.Count.ToString();
existingDropDowns.Add(newDropDown);
Panel1.Controls.Add(newDropDown);
newDropDown.AutoPostBack = true;
Panel1.Controls.Add(new LiteralControl("<br/>"));
Session["DDLs"] = existingDropDowns;
}
Below is the code to connect the existing dropdown list with the database.
protected void GetDropDowndata()
{
DataTable ddlData= lookupCache.AccessLookupData(Constants.GroupSelectionFilter.ToString());
if (ddlData != null && ddlData.Rows.Count > 0)
{
ddlData.DefaultView.Sort = "DropDownValue";
ddlData = groupsData.DefaultView.ToTable();
ddlSelectGrp.DataSource = ddlData;
ddlSelectGrp.DataTextField = "DropDownValue";//ddlSelectGrp is the existing dropdown id
ddlSelectGrp.DataValueField = "DropDownBoxID";
ddlSelectGrp.DataMember = "DropDownGroup";
ddlSelectGrp.DataBind();
ddlSelectGrp.Items.Insert(1, Constants.GroupAll.ToString());
ddlSelectGrp.SelectedIndex = 1;
btnGroupSave.Enabled = true;
btnGroupSave.CssClass = "saveButton";
}
}
But I have no idea on how to connect the dynamically generated dropdownlist with the datasource and that too without the selected value(s) in the previous dropdown list(s).

how to create button click event in gridview RowDataBound c# asp.net

i am trying to create button and click event in rowdatabound in gridview c# asp.net like below code
protected void btnerror_Click(object sender, EventArgs e)
{
GridView gv = new GridView();
gv.RowDataBound += gv_RowDataBound;
gv.RowCommand += gv_RowCommand;
gv.RowCreated += gv_RowCreated;
gv.EnableViewState = true;
gv.DataSource = _dt;
gv.DataBind();
}
void gv_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
ImageButton btnUpdate = new ImageButton();
btnUpdate.ID = "btnupdate";
btnUpdate.ImageUrl = "~/SmartAdmin/Images/update.png";
btnUpdate.ToolTip = "Click Update";
btnUpdate.CommandName = "update";
btnUpdate.Click += btnUpdate_Click;
TableCell tc = new TableCell();
tc.Controls.Add(btnUpdate);
e.Row.Cells.Add(tc);
}
}
void gv_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "update")
{
}
}
while click that button click event is not firing ...
where i made error...
thank u.......
Do you really want to create the GridView manually? I strongly doubt that. Instead add it declaratively to the aspx-page and make it visible in btnerror_Click.
Don't create the control dynamically and register the event handler in RowDataBound but in RowCreated which is triggered on every postback (as opposed to RowDataBound):
void gv_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
ImageButton btnUpdate = new ImageButton();
btnUpdate.Click += btnUpdate_Click;
TableCell tc = new TableCell();
tc.Controls.Add(btnUpdate);
e.Row.Cells.Add(tc);
}
}
void gv_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
ImageButton btnUpdate = (ImageButton)e.Row.FindControls("btnupdate")
btnUpdate.ID = "btnupdate";
btnUpdate.ImageUrl = "~/SmartAdmin/Images/update.png";
btnUpdate.ToolTip = "Click Update";
btnUpdate.CommandName = "update";
}
}
So create it in RowCreated but initialize it in RowDataBound where you can also access the datasource (if required).
Also note that you should DataBind the GridView only if(!IsPostBack) not on every postback (if that's the case). So add this check where you assign the datasource.
You need to add function for click event
btnUpdate.Click += btnUpdate_Click;
protected void btnUpdate_Click(object sender, EventArgs e)
{
}

How to create button in dynamically created Gridview?

I'm using AJAX Control Toolkit to create Tabpanels. Each panel is populated with a gridview as per below code.
Now, I want to add one button per each row. When it is clicked it should pass as parameter one of the cells of that row, but as the Gridview is dynamically created, I don't know how. Any tips?
foreach (DataTable dt in DataSet1.Tables)
{
GridView gv = new GridView();
var thepanel = new AjaxControlToolkit.TabPanel();
gv.DataSource = dt;
gv.DataBind();
thepanel.Controls.Add(gv);
TabContainer.Controls.Add(thepanel);
}
You can add a select button to your grid as follows:
Gridview1.AutoGenerateSelectButton=true;
I just found a solution for whom this may interest:
First, you should include fllwg lines BEFOREthe databind:
gv.RowDataBound += gv_RowDataBound;
gv.RowCommand += gv_RowCommand;
Then define the RowDataBound to insert the Linkbutton:
protected void gv_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
LinkButton butIgnorar = new LinkButton()
{
CommandName = "Ignorar",
ID = "butIgnorar",
Text = "Ignorar",
//optional: passes contents of cell 1 as parameter
CommandArgument = e.Row.Cells[1].Text.ToString()
};
//Optional: to include some javascript cofirmation on the action
butIgnorar.Attributes.Add("onClick", "javascript:return confirm('Are you sure you want to ignore?');");
TableCell tc = new TableCell();
tc.Controls.Add(butIgnorar);
e.Row.Cells.Add(tc);
}
}
Finally, you call the command from the RowCommand
protected void gv_RowCommand(object sender, GridViewCommandEventArgs e)
{
string currentCommand = e.CommandName;
string parameter= e.CommandArgument.ToString();
if (currentCommand.Equals("Ignorar"))
{
yourMethodName(parameter);
}
}
Hope that this is helpful for somebody!

How can I access the row in a RowCommand event

I am trying to find a DropDown element in the GridView_RowCommand but it says that GridViewCommandEventArgs does not contain a definituon for 'Row'. I need to do this in this event because i am evaluating a GridView Command. See failing code below
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Add")
{
DropDownList Myddl = null;
ClientClass client = new ClientClass();
Myddl = e.Row.FindControl("ddlClients") as DropDownList;
if (Myddl != null)
{
updated = client.InsertUpdateClient(ClientID,
int.Parse(e.CommandArgument.ToString()), departmentID);
}
else
{
Labels.Text = "There was an error updating this client";
}
}
}
Something like this:
GridViewRow row = (GridViewRow)(((LinkButton)e.CommandSource).NamingContainer);
This is assuming what's firing off the RowCommand is a LinkButton. Change that according.
In addition to the #Stephen,
if (e.CommandName == "Add")
{
DropDownList Myddl = null;
ClientClass client = new ClientClass();
//Use this if button type is linkbutton
GridViewRow row = (GridViewRow)(((LinkButton)e.CommandSource).NamingContainer);
//Use this if button type is Button
//GridViewRow row = (GridViewRow)(((Button)e.CommandSource).NamingContainer);
Myddl = row.FindControl("ddlClients") as DropDownList;
if (Myddl != null)
{
updated = client.InsertUpdateClient(ClientID,
int.Parse(e.CommandArgument.ToString()), departmentID);
}
else
{
Labels.Text = "There was an error updating this client";
}
}

Categories

Resources