I have a GridView, here I am adding the LinkButtons at runtime to the GridView cells.
I am also attacing an click event on these LinkButtons.
The issue is that when I populate the GridView from the Page_load the LinkButton click works,
but if I move GridView polulation code in the Page_PreRender
event the click event doesn't executes.
Code:
private void Page_PreRender(object sender, System.EventArgs e)
{
//does not fires the Click event of dynamically generated LinkButtons
GridView1.DataSource = getDataTable();
GridView1.DataBind();
}
protected void Page_Load(object sender, EventArgs e)
{
//fires the Click event of dynamically generated LinkButtons
GridView1.DataSource = getDataTable();
GridView1.DataBind();
}
protected DataTable getDataTable()
{
//get data in a dataset
try
{
connStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Server.MapPath("~/db/demo.mdb");
myConnection = new OleDbConnection(connStr);
sql = "select ProductId, ProductName from Products order by ProductId asc";
da = new OleDbDataAdapter(sql, myConnection);
dsData.Clear();
da.Fill(dsData, "Products");
It is because of ASP.NET Page Life Cycle. Event is fired before after load and before pre-render. And as you are adding control dynamically it will not exists in load so it will not fire event for that.
Please remember to click “Mark as Answer” on the post that helps you, and to click “Unmark as Answer” if a marked post does not actually answer your question. This can be beneficial to other community members reading the thread.
Marked as answer by ajaysharmaapjs on Jun 30, 2010 06:37 AM
Just out of curiosity but how does reviewing the page life cycle solve the current problem ajay is having? I am currently at a loss as to binding a command dynamically to a list of link buttons inside of a grid view. Each id needs to be increment and have
an event which will fire. Any way to do this?
If anybody is interested I found out how to do this. I had to create a method for the gridview event OnRowDataBound. I also had to create a new column in which to reference the ID in order for the sort to work. The command method was set statically inside
the gridview linkbutton tag:
//This needs to override the link control in order to bind the text to the link
protected void notesTableGV_RowDataBound(Object sender, GridViewRowEventArgs e)
{
store = (Store)ViewState["store"];
//this is for setting the header sort images
string imgAsc = @" <img src='images\sort_down.png' title='Ascending' width='20' height='10' />";
string imgDes = @" <img src='images\sort_up.png' title='Descendng' width='20' height='10' />";
string sortExpression = ViewState["SortExpression"] as string;
string sortDirection = ViewState["SortDirection"] as string;
if (e.Row.RowType == DataControlRowType.Header && sortExpression != null)
{
foreach (TableCell cell in e.Row.Cells)
{
LinkButton lbSort = (LinkButton)cell.Controls[0];
if (lbSort.Text == sortExpression)
{
if (sortDirection == "ASC")
lbSort.Text += imgAsc;
else
lbSort.Text += imgDes;
}
if (sortExpression == "noteID" && lbSort.Text == "Note Content")
{
if (sortDirection == "ASC")
lbSort.Text += imgAsc;
else
lbSort.Text += imgDes;
}
}
}
//This is for setting the links
if (e.Row.RowType == DataControlRowType.DataRow)
{
GridViewRow gvr = e.Row;
DataRowView drv = (DataRowView)gvr.DataItem;
//Cell 3 is an invisible cell with the id of the note
int noteindex = 0;
if (e.Row.Cells[3].Text != "")
noteindex = Int32.Parse(e.Row.Cells[3].Text);
else
noteindex = gvr.RowIndex;
//if the sort didn't happen yet then bind the data
foreach (Control X in gvr.Cells[2].Controls)
{
if (X is LinkButton)
{
LinkButton LB = X as LinkButton;
string noteText = store.Notes[noteindex, 2];
//SWT just get the first 10 characters and have ... afterwards
string previewString = noteText.Substring(0, 10) + "...";
//LinkButton lbNote = (LinkButton)notesTableGV.Rows[row.RowIndex].FindControl("noteLink");
LB.ToolTip = noteText;
LB.Text = previewString;
LB.CommandArgument = noteindex.ToString();
//string link = ((DataRowView)e.Row.DataItem)["Note Content"].ToString();
}
}
}
}
//This will set the note in the edit text box
public void noteLink_Command(object sender, CommandEventArgs e)
{
sample= (Sample)ViewState["sample"];
int id = Int32.Parse(e.CommandArgument.ToString());
noteIDLbl.Text = id.ToString();
//SWT the id is for the row index of the notes
sampleNotesEditor.Content = sample.Notes[id, 2];
modifyNoteBtn.Text = "Edit Note";
}
ajaysharmaap...
Member
209 Points
52 Posts
Event handling in PreRender vs Page_Load
Jun 29, 2010 12:41 PM|LINK
Hi,
I have a GridView, here I am adding the LinkButtons at runtime to the GridView cells.
I am also attacing an click event on these LinkButtons.
The issue is that when I populate the GridView from the Page_load the LinkButton click works,
but if I move GridView polulation code in the Page_PreRender event the click event doesn't executes.
Code:
private void Page_PreRender(object sender, System.EventArgs e)
{
//does not fires the Click event of dynamically generated LinkButtons
GridView1.DataSource = getDataTable();
GridView1.DataBind();
}
protected void Page_Load(object sender, EventArgs e)
{
//fires the Click event of dynamically generated LinkButtons
GridView1.DataSource = getDataTable();
GridView1.DataBind();
}
protected DataTable getDataTable()
{
//get data in a dataset
try
{
connStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Server.MapPath("~/db/demo.mdb");
myConnection = new OleDbConnection(connStr);
sql = "select ProductId, ProductName from Products order by ProductId asc";
da = new OleDbDataAdapter(sql, myConnection);
dsData.Clear();
da.Fill(dsData, "Products");
lblError.Text = dsData.Tables[0].Rows.Count.ToString();
}
catch(Exception ex)
{
lblError.Text = ex.Message;
}
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
for (int i = 0; i < columnsToGenerate; i++)
{
LinkButton lnkKeyword = new LinkButton();
//link text set
lnkKeyword.Text = e.Row.Cells[i].Text;
//event handler declaration
lnkKeyword.Command += new CommandEventHandler(keyword_Clicked);
//parameter passed to event handler
lnkKeyword.CommandArgument = e.Row.Cells[i].Text;
//css setting
lnkKeyword.CssClass = "keywordLinks";
e.Row.Cells[i].Controls.Add(lnkKeyword);
}
}
}
private void keyword_Clicked(object sender, CommandEventArgs e)
{
lblError.Text = e.CommandArgument.ToString();
//Response.Redirect("test.aspx?item=" + e.CommandArgument.ToString());
}
Regards
Ajay Sharma
-------------------------------------------
nayan.paregi
Member
82 Points
11 Posts
Re: Event handling in PreRender vs Page_Load
Jun 29, 2010 12:55 PM|LINK
It is because of ASP.NET Page Life Cycle. Event is fired before after load and before pre-render. And as you are adding control dynamically it will not exists in load so it will not fire event for that.
You can read more about page life cycle http://msdn.microsoft.com/en-us/library/ms178472.aspx
Nayan Paregi (MCTS)
Please remember to click “Mark as Answer” on the post that helps you, and to click “Unmark as Answer” if a marked post does not actually answer your question. This can be beneficial to other community members reading the thread.
spmamidi
Participant
1157 Points
184 Posts
Re: Event handling in PreRender vs Page_Load
Jun 29, 2010 01:31 PM|LINK
Page Load and Load Complete events set the properties and events to the controls, Where as Pre Render make final changes to the contents of the page.
For more information - http://msdn.microsoft.com/en-us/library/ms178472.aspx
Shiva Mamidi
gaurabchatte...
Participant
1655 Points
325 Posts
Re: Event handling in PreRender vs Page_Load
Jun 29, 2010 01:42 PM|LINK
U will not be able fire the click event in Page_PreRender ..
Microsoft Technologies
zuice22
Member
4 Points
2 Posts
Re: Event handling in PreRender vs Page_Load
Dec 12, 2012 05:01 PM|LINK
Just out of curiosity but how does reviewing the page life cycle solve the current problem ajay is having? I am currently at a loss as to binding a command dynamically to a list of link buttons inside of a grid view. Each id needs to be increment and have an event which will fire. Any way to do this?
zuice22
Member
4 Points
2 Posts
Re: Event handling in PreRender vs Page_Load
Dec 12, 2012 05:09 PM|LINK
If anybody is interested I found out how to do this. I had to create a method for the gridview event OnRowDataBound. I also had to create a new column in which to reference the ID in order for the sort to work. The command method was set statically inside the gridview linkbutton tag:
Gridview.aspx:
<asp:GridView ID="notesTableGV" runat="server" AllowSorting="true" OnRowDataBound="notesTableGV_RowDataBound" AutoGenerateColumns="false" OnSorting="notesTableGV_OnSorting" GridLines="none" CellSpacing="15" CellPadding="15"> <Columns> <asp:BoundField DataField="User Name" HeaderText="User Name" SortExpression="User Name" /> <asp:BoundField DataField="Time Stamp" HeaderText="Time Stamp" SortExpression="Time Stamp" /> <asp:TemplateField HeaderText="Note Content" SortExpression="noteID"> <ItemTemplate> <asp:LinkButton ID="noteLink" runat="server" OnCommand="noteLink_Command" Text="test"></asp:LinkButton> </ItemTemplate> </asp:TemplateField> <asp:BoundField DataField="noteID" HeaderText="" SortExpression="noteID"> <ItemStyle CssClass="invisible"></ItemStyle> </asp:BoundField> </Columns> <%--OnItemCreated="notesTableDG_OnItemCreated"--%> </asp:GridView>Gridview.aspx.cs:
//This needs to override the link control in order to bind the text to the link protected void notesTableGV_RowDataBound(Object sender, GridViewRowEventArgs e) { store = (Store)ViewState["store"]; //this is for setting the header sort images string imgAsc = @" <img src='images\sort_down.png' title='Ascending' width='20' height='10' />"; string imgDes = @" <img src='images\sort_up.png' title='Descendng' width='20' height='10' />"; string sortExpression = ViewState["SortExpression"] as string; string sortDirection = ViewState["SortDirection"] as string; if (e.Row.RowType == DataControlRowType.Header && sortExpression != null) { foreach (TableCell cell in e.Row.Cells) { LinkButton lbSort = (LinkButton)cell.Controls[0]; if (lbSort.Text == sortExpression) { if (sortDirection == "ASC") lbSort.Text += imgAsc; else lbSort.Text += imgDes; } if (sortExpression == "noteID" && lbSort.Text == "Note Content") { if (sortDirection == "ASC") lbSort.Text += imgAsc; else lbSort.Text += imgDes; } } } //This is for setting the links if (e.Row.RowType == DataControlRowType.DataRow) { GridViewRow gvr = e.Row; DataRowView drv = (DataRowView)gvr.DataItem; //Cell 3 is an invisible cell with the id of the note int noteindex = 0; if (e.Row.Cells[3].Text != "") noteindex = Int32.Parse(e.Row.Cells[3].Text); else noteindex = gvr.RowIndex; //if the sort didn't happen yet then bind the data foreach (Control X in gvr.Cells[2].Controls) { if (X is LinkButton) { LinkButton LB = X as LinkButton; string noteText = store.Notes[noteindex, 2]; //SWT just get the first 10 characters and have ... afterwards string previewString = noteText.Substring(0, 10) + "..."; //LinkButton lbNote = (LinkButton)notesTableGV.Rows[row.RowIndex].FindControl("noteLink"); LB.ToolTip = noteText; LB.Text = previewString; LB.CommandArgument = noteindex.ToString(); //string link = ((DataRowView)e.Row.DataItem)["Note Content"].ToString(); } } } } //This will set the note in the edit text box public void noteLink_Command(object sender, CommandEventArgs e) { sample= (Sample)ViewState["sample"]; int id = Int32.Parse(e.CommandArgument.ToString()); noteIDLbl.Text = id.ToString(); //SWT the id is for the row index of the notes sampleNotesEditor.Content = sample.Notes[id, 2]; modifyNoteBtn.Text = "Edit Note"; }