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.
Related
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)
{
}
I have a requirement to replace a label in gridview when I click on the Edit button added manually in grid view.
Please see below the code:
protected void btnchange_Click(object sender, EventArgs e)
{
Button btn = (Button)sender;
GridViewRow gvr = (GridViewRow)btn.NamingContainer;
int getindex = gvr.RowIndex;
gvorderdetail.Rows[getindex].Cells[3].Style.Value = "red";
gvorderdetail.Rows[getindex].Cells[0].Attributes["style"] = "background-color:Red";
gvorderdetail.Rows[getindex].Cells[1].Attributes["style"] = "background-color:Red";
gvorderdetail.Rows[getindex].Cells[2].Attributes["style"] = "background-color:Red";
TextBox tbx = (TextBox)gvorderdetail.Rows[getindex].FindControl("txtitemqty");
}
protected void gvorderdetail_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "change")
{
TextBox tbx = (TextBox)gvorderdetail.Rows[0].FindControl("txtitemqty");
}
}
Can anyone help?
'>
'>
How do I use the AutoGenerateEditButton to update my gridview Table (has a dataset bound to it -Dataset Retrieved from an sql database)
--Removed the Broken code in the question to put Fixed code in the Answer--
To get the values of the updated row add this to your "RowUpdating" event handler
protected void grdViewDetails_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
GridViewRow row = (GridViewRow)grdViewDetails.Rows[e.RowIndex];
foreach (Control item in row.Controls)
{
if (item.Controls[0] is TextBox)
{
TextBox textbox = (TextBox)item.Controls[0];
string x = textbox.Text; //theres your value you can do stuff with
}
if (item.Controls[0] is Label)
{
Label mylabel = (Label)item;
//do stuff - just do the same as the textbox
}
}
}
and in "RowEditing" event handler
protected void grdViewDetails_RowEditing1(object sender, GridViewEditEventArgs e)
{
grdViewDetails.EditIndex = e.NewEditIndex;
//e.newedit index:- will be provide index of row for which edit button is selected
grdViewDetails.DataSource = yourdatasource //mine was a datset
grdViewDetails.DataBind();
}
My newly created button in my gridviewrow is not firing its EventHandler or the RowCmmand Event and then when the page Reload after pressing the Button newly added row is missing probably because I can't call my BindData method. I have removed the Click eventHandler from the Button and just used the OnRowCommand Event and I still am getting nothing
protected void CustomGridView_DataBound(object sender, EventArgs e)
{
int count = ((GridView)sender).Rows.Count;
GridViewRow row = new GridViewRow(-1, -1, DataControlRowType.DataRow, DataControlRowState.Insert);
TableCell cell = new TableCell();
Button button = new Button();
button.Text = "Insert";
button.ID = "Insert";
button.CommandName = "Insert";
button.Click += new EventHandler(insertButton_Click);
cell.Controls.Add(button);
row.Cells.Add(cell);
for (int i = 0; i < ((GridView)sender).Columns.Count; i++)
{
cell = new TableCell();
cell.Controls.Add(new TextBox { ID = "Text" + i });
row.Cells.Add(cell);
}
Table table = ((GridView)sender).Rows[0].Parent as Table;
table.Rows.AddAt(count + 1, row);
}
protected void insertButton_Click(object sender, EventArgs e)
{
lblInsert.Text = "Hello World";
}
protected void CustomGridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Insert")
{
lblInsert.Text = "Hello World";
}
}
Remove the button.Click += new EventHandler(insertButton_Click); statement from your code. The RowCommand event of GridView controll will be fired when button is pressed. For more info - How to: Respond to Button Events in a GridView Control.
You need to attach to the grid's RowCommand event before the databound. Do it on the constructor or Init event of the page or usercontrol, not in the databound. In the databound you will set the CommandName and CommandArgument properties.
Hope it helps.
I've created a gridview dynamically, now i want to fire an event when the selectedindex has changed.
GridView NewDg = new GridView();
NewDg.ID = "SubGridView" + e.Row.RowIndex.ToString();
NewDg.DataKeyNames = new string[]{"logentry_id"};
NewDg.SelectedIndexChanged += new EventHandler(NewDg_SelectedIndexChanged);
NewDg.RowDataBound += new GridViewRowEventHandler(NewDg_RowDataBound);
The RowDataBound works but it doesn't produce the right postback URL i guess.
In the RowDataBound i have the following code:
GridView sendingGridView = (GridView)sender;
e.Row.Attributes["onclick"] = ClientScript.GetPostBackClientHyperlink(sendingGridView, "Select$" + e.Row.RowIndex);
this produces the following code:
javascript:__doPostBack('SubGridView4','Select$0')
Only this doesn't lead to the postback to this function:
void NewDg_SelectedIndexChanged(object sender, EventArgs e)
{
GridView sendingGridView = (GridView)sender;
ViewDetails(Convert.ToInt32(sendingGridView.SelectedDataKey["logentry_id"].ToString()));
}
Does anyone know what i'm doing wrong?
First, you are recreating the grid on every page load? This is a requirement for creating the grid this way. Second, try tapping into RowCommand, and looking for the command name that way; maybe that will fire successfully; you get a reference to the command through the command argument as in :
void rowcmd(..) {
if (e.CommandName != null && e.CommandName.StartsWith("Select")) {
//Dothis
}
}
I found the answer to my question on Code Project:
I now use a gridview in my gridview
<asp:TemplateField>
<ItemTemplate>
<asp:GridView ID="SubGridView"
Because of the extender on GridView, The gridview will be displayed when I click on the plus sign (see link)
on page load i perform the following:
protected void Page_Load(object sender, EventArgs e)
{
GridView1.RowCreated += new GridViewRowEventHandler(GridView1_RowCreated);
GridView1.DataSource = dc.GetLogEntriesWithUsername();
GridView1.DataBind();
I already have a DataBound and a Selected Index Changed event on this gridview.
On the row created event i perform the following:
void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
GridView SubGridView = e.Row.FindControl("SubGridView") as GridView;
List<GetLogEntriesWithUsernameByParentIdResult> subLogEntries = dc.GetLogEntriesWithUsernameByParentId(((GetLogEntriesWithUsernameResult)e.Row.DataItem).logentry_id).ToList();
if (subLogEntries.Count > 0)
{
SubGridView.DataSource = subLogEntries;
SubGridView.DataBind();
(e.Row as ExtGridViewRow).ShowExpand = SubGridView.Rows.Count > 0;
}
}
}
On the subgridview i also have a DataBound and a SelectedIndex Changed event. This works now!
I use this DataBound event:
protected void GridView_RowDataBound(object sender, GridViewRowEventArgs e)
{ // only apply changes if its DataRow
GridView sendingGridView = (GridView)sender;
if (e.Row.RowType == DataControlRowType.DataRow)
{
// when mouse is over the row, save original color to new attribute, and change it to highlight yellow color
e.Row.Attributes.Add("onmouseover",
"this.originalstyle=this.style.backgroundColor;this.style.backgroundColor='#C0C0C0';this.style.cursor='pointer';");
// when mouse leaves the row, change the bg color to its original value
e.Row.Attributes.Add("onmouseout",
"this.style.backgroundColor=this.originalstyle;this.style.cursor='cursor'");
//e.Row.Attributes.Add("onclick", ClientScript.GetPostBackClientHyperlink(sendingGridView, "Select$" + e.Row.RowIndex));
e.Row.Cells[1].Attributes["onclick"] = ClientScript.GetPostBackClientHyperlink(sendingGridView, "Select$" + e.Row.RowIndex);
e.Row.Cells[2].Attributes["onclick"] = ClientScript.GetPostBackClientHyperlink(sendingGridView, "Select$" + e.Row.RowIndex);
e.Row.Cells[3].Attributes["onclick"] = ClientScript.GetPostBackClientHyperlink(sendingGridView, "Select$" + e.Row.RowIndex);
e.Row.Cells[4].Attributes["onclick"] = ClientScript.GetPostBackClientHyperlink(sendingGridView, "Select$" + e.Row.RowIndex);
e.Row.Cells[5].Attributes["onclick"] = ClientScript.GetPostBackClientHyperlink(sendingGridView, "Select$" + e.Row.RowIndex);
And the selected index changed event:
protected void GridView_SelectedIndexChanged(object sender, EventArgs e)
{
GridView sendingGridView = (GridView)sender;
ViewDetails(Convert.ToInt32(sendingGridView.SelectedDataKey["logentry_id"].ToString()));
}
The ViewDetails function show the details of the selected logentry in a different div.
Now i'm busy on the final step, that is keep showing the data as it was before i clicked on a row.
Thanks for the help, but this is the solution to my problem.