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

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

Related

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

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

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.

Event handler not firing on dynamic button click

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

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

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!

Categories

Resources