How to maintain view state of dynamic control linkbutton in C# asp? - c#

I am adding dynamic LinkButton in Data Gridview, which will take me to a new page in C# asp.net. In starting, I am select value from Dropdown control. It will reload the page and display data in Gridview. In Gridview every row has dyanmic Linkbutton. When I click on Linkbutton in gridview, it is not working and page was reloaded and it hide the linkbutton.
My code is working when dropdown code pasted on page_load method.
I have researching since last 7 hours, view most of the answers but nothing is working on my problem.
As per my research, I found that after page reload LinkButton lost is state(I am not sure.).
Thanks in Advance...
using System;
using System.Web.UI.WebControls;
namespace aweFinalTTA.TTA.BatchReport
{
public partial class CenterBatchList : System.Web.UI.Page
{
protected aweFunctionNew aweApi = new aweFunctionNew();
protected aweCodePublic aweCode = new aweCodePublic();
protected LinkButton linkButton01;
protected GridView gdv;
protected DropDownList ddlTTCCode;
override protected void OnInit(EventArgs e)
{
aweApi.showForm(aweApi.getManageFieldDT("select * from manage_field where table_name='TTCBatchList'"), frmBatchList);
ddlTTCCode = (DropDownList)frmBatchList.FindControl(frmBatchList.ID + "ddlTTCCode");
ddlTTCCode.SelectedIndexChanged += new EventHandler(ddlTTCCode_SelectedIndexChanged);
frmBatchList.Controls.Add(aweApi.addGridViewNew("EmpGrid", "List of Batch Created"));
gdv = (GridView)frmBatchList.FindControl("EmpGrid");
gdv.RowDataBound += OnRowLinkBound;
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
aweApi.getDDL(ddlTTCCode, "select TTCCode,TTCCode from TTCDetail where TTARNO='" + Session["TTARNO_01"].ToString() + "' and TTCDetail.TTCCode in (Select TTCCode from TTCCourseListOfTTC) and TTCDetail.TTCCode in (Select TTCCode from TTCInfraDetail) and TTCDetail.TTCCode in (Select TTCCode from TTCFacility) order by LastUpdatedDate desc", true);
TemplateField tfieldCheckbox = new TemplateField();
tfieldCheckbox.HeaderText = "Select";
gdv.Columns.Add(tfieldCheckbox);
}
}
protected void ddlTTCCode_SelectedIndexChanged(object sender, EventArgs e)
{
gdv.DataSource = aweApi.getResultsDT("select * from BatchMain where TTCCode='TTC0000002008'");
gdv.DataBind();
gdv.HeaderRow.TableSection = TableRowSection.TableHeader;
}
protected void OnRowLinkBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
LinkButton linkButton = new LinkButton();
linkButton.ID = "link";
linkButton.Text = "Edit";
linkButton.ForeColor = System.Drawing.Color.Blue;
linkButton.Click += linkButton_Click;
e.Row.Cells[0].Controls.Add(linkButton);
}
}
protected void linkButton_Click(object sender, EventArgs e)
{
// GridViewRow gr = ((sender as LinkButton).NamingContainer as GridViewRow);
/// Session["TTCBatchId_01"] = gr.Cells[2].Text.Trim(); /*For first cell value of Row */
Response.Write("linkbutton_click is working");
aweCode.showMessage(this, "aaaaaa");
//Response.Redirect("~/TTA/BatchReport/BatchAddCandidate");
}
}
}

Related

dynamic linkbutton not calling command when clicked

New to dynamic controls, but until now I have been creating them successfully in a
template field in my gridview, recently switched from a hyperlink to a link button
and had to make some changes but still not working
In my page I have the following code (abridged to salient parts)
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
...
...
TemplateField tf = new TemplateField();
tf.HeaderText = "Action";
tf.ItemTemplate = new AssignPage.MyTemplate(..., mylb);
GridView1.Columns.Add(tf);
protected void Page_PreInit(object sender, EventArgs e)
{
LinkButton lb = new LinkButton();
lb.Text = "AssignAll";
lb.Command += new CommandEventHandler(AssignAll_Click);
lb.CommandName = "XXX";
this.mylb = lb;
protected void AssignAll_Click(object sender, CommandEventArgs e)
{
string[] arg = new string[2]; // BREAK POINT HERE
arg = e.CommandArgument.ToString().Split(';');
...
...
Response.Redirect("BaseAndRepeats.aspx?id=" + r.Event.ID);
In the template class I have I have
LinkButton lb;
public MyTemplate(..., LinkButton _lb)
{
...
lb = _lb;
...
public void InstantiateIn(System.Web.UI.Control container)
{
...
...
// various conditional statements
lb.CommandArgument = mylist[rowCount].ReqtID.ToString() + ";" + mylist[rowCount].RotaUser;
container.Controls.Add(lb);
...
The break point in the handler is never reached
I thought I was creating the linkbutton in the right place
the linkbutton appears in the grid quite happily
when I click on the linkbutton there is a call
to Page_PreInit and to Page_Load and as I expected
it is a postback.
But AssignAll_Click is never called.
In the browser footer it shows "javascript: __dooPsotabck(..." when you hover
over the buttonlink
I believe the problem is this line:
lb.Command += new CommandEventHandler(AssignAll_Click);
Change it to:
lb.Command += AssignAll_Click;
Edit:
Also you want to move it from Page_PreInit to Page_Init but you may find more success with it in Page_Load (outside the IsPostBack). Here's an example that works for me:
On the ASPX page:
<asp:Panel ID="TestPanel" runat="server" />
Codebehind:
protected void Page_Init(object sender, EventArgs e)
{
//Init used because TestPanel doesn't exist yet
CreateTestButton();
}
private void CreateTestButton()
{
var lb = new LinkButton();
lb.Text = "hello";
lb.Command += lb_Command;
TestPanel.Controls.Add(lb);
}
void lb_Command(object sender, CommandEventArgs e)
{
throw new NotImplementedException();
}
Going over your code it looks like your adding another column into your GridView and creating a button inside that column for each row - but you've got the column being added on Page_Load and the button being created and bound to it before in Page_PreInit

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)
{
}

RowEditing is fired when update button is clicked in GridView

I have created a GridView as below:
protected void Page_Load(object sender, EventArgs e)
{
GridView gv = new GridView();
gv.ID = pId.ToString();
gv.AutoGenerateEditButton = true;
gv.DataKeyNames = ids;
gv.RowEditing += gv_RowEditing;
gv.RowUpdating += gv_RowUpdating;
bindGv(pId, gv);
}
I have also written the following methods:-
RowUpdating:
void gv_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
GridView gv = sender as GridView;
GridViewRow row = (GridViewRow)gv.Rows[e.RowIndex];
ProductCategory pc = context.ProductCategories.First(s => s.Name ==gv.ID );
TextBox txtName = row.FindControl("txtName") as TextBox;
pc.Name = txtName.Text;
}
RowEditing:
void gv_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView gv = sender as GridView;
gv.EditIndex = e.NewEditIndex;
bindGv(Convert.ToInt32(gv.ID), gv);
}
But when I ran the codes in debugging mode, clicking on the update button invokes gv_RowEditing method instead of gv_RowUpdating. What is the problem?
The Sequence of firing the events of gridview when you click on edit button to update any record it calls rowediting event and after that when you click on update button it calls rowupdating event.
rowediting event always invokes first then rowupdating.

Why can I not catch the value of Gridview row?

Here is my code.
problem: When click om a row och on select the page is refreshing and i dont get the text in the lable17.text.
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
GridViewRow row = GridView1.SelectedRow;
Label17.Text = row.Cells[2].Text.ToString() ;
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Attributes.Add("onmouseover", "this.style.cursor='Pointer';this.style.backgroundColor='Yellow'");
}
}
protected void GridView1_SelectedIndexChanging(object sender, GridViewSelectEventArgs e)
{
GridViewRow row = GridView1.Rows[e.NewSelectedIndex];
Label17.Text = "you selected" + row.Cells[2].Text;
}
Is your GridView in an UpdatePanel? If not the entire Page will postback when you click on the Button. Also, make sure that if you are setting the Text of Label17 in the Page_Load event that you only do it the first time i.e.
public void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
Label17.Text = "Default Text";
}
}

GridView getting the data trough the id asp.net

The problem really is that i do can trough the selects on the gridview get the data trough the id, but then i use the search option i implemented on the page and the gridview shows the ones it gets that match the result but if i press select it will redirect to the page with the wrong id, isntead of getting the id of the one i selected it gets the id of the field that was on the 1st position of the cell.
Here is the code:
protected void Page_Load(object sender, EventArgs e)
{
TeamGest.DBLayer.DBLTeams dbl = new TeamGest.DBLayer.DBLTeams();
GridView1.DataSource = dbl.List();
GridView1.DataBind();
TeamGest.DBLayer.DBLPlayers dbl1 = new TeamGest.DBLayer.DBLPlayers();
GridView2.DataSource = dbl1.List();
GridView2.DataBind();
}
protected void MyMenu_MenuItemClick(object sender, MenuEventArgs e)
{
{
MyMultiView.ActiveViewIndex = Int32.Parse(e.Item.Value);
int i;
for (i = 0; i <= MyMenu.Items.Count - 1; i++)
{
if (i == Convert.ToInt32(e.Item.Value))
{
MyMenu.Items[i].Text = MyMenu.Items[i].Text;
}
else
{
MyMenu.Items[i].Text = MyMenu.Items[i].Text;
}
}
}
}
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
GridViewRow row = GridView1.SelectedRow;
Response.Redirect("DetalhesClube.aspx?Id="+row.Cells[0].Text);
}
protected void Button1_Click1(object sender, EventArgs e)
{
string searchStringTeam = TextBox1.Text;
GetTeamResults(searchStringTeam);
}
protected void GridView2_SelectedIndexChanged(object sender, EventArgs e)
{
GridViewRow row = GridView2.SelectedRow;
Response.Redirect("DetalhesJogador.aspx?Id=" + row.Cells[0].Text);
}
protected void Button2_Click(object sender, EventArgs e)
{
string searchStringPlayer = TextBox2.Text;
GetPlayerResults(searchStringPlayer);
}
Don't use the cell values. That's what the DataKeys collection is for:
<asp:GridView ID="GridView1" runat="server" DataKeyNames="ID, SomeOtherColumn" ...>
And in code-behind all you need is the row index:
var rowIndex = 0;
var ID = (int)GridView1.Rows[rowIndex]["ID"];

Categories

Resources