Why OnRowEditing is required even though it has no logic? - c#

The buttonfield with command EDIT doesn't work until I put
OnRowEditing="grdviewContractorTypes_RowEditing"
Problem:
I wrote this code
<asp:GridView runat="server" ID="grdviewContractorTypes" OnRowEditing="grdviewContractorTypes_RowEditing" OnRowCommand="grdviewContractorTypes_RowCommand" DataKeyNames="pk_ContractorTypes_ContractorTypeID" AutoGenerateColumns="false" CssClass="table table-condensed table-bordered table-striped table-responsive">
<Columns>
<asp:BoundField DataField="pk_ContractorTypes_ContractorTypeID" HeaderText="ID" />
<asp:BoundField DataField="ContractorTypeName" HeaderText="Contractor Type" />
<asp:ButtonField CommandName="edit" ImageUrl="~/assets/global/images/shopping/edit.png" ButtonType="Image" ControlStyle-Width="25px" ControlStyle-Height="25px" />
</Columns>
</asp:GridView>
.cs
protected void grdviewContractorTypes_RowCommand(object sender, GridViewCommandEventArgs e)
{
try
{
if (e.CommandName == "edit")
{
byte ContractorTypeID = Convert.ToByte(grdviewContractorTypes.DataKeys[Convert.ToInt32(e.CommandArgument)].Value);
//HFActID.Value = ID.ToString();
btnAddContractorType.Visible = false;
btnUpdated.Visible = true;
DataTable dt = MngContractorTypes.SelectContractorTypesByContractorTypeID(ContractorTypeID);
DataRow r = dt.Rows[0];
txtBoxContractorTypeName.Text = r["ContractorTypeName"].ToString();
HdnFieldContractorTypeID.Value = r["pk_ContractorTypes_ContractorTypeID"].ToString();
//txtSearch.Text = "Testing...";
//Response.Write("DONE");
}
}
catch (Exception ex)
{
Response.Write(Convert.ToString(ex.Message));
}
}
The above code runs when I click button field with 'edit' command in DEBUGGER but doesn't do anything in actual, on screen until I put this.
protected void grdviewContractorTypes_RowEditing(object sender, GridViewEditEventArgs e)
{
}

Related

Nested GridViews in ASP.Net using C# problem with change page

I am trying to open my nested gridview for a single Parent Row and gets correctly open with one single record of the child row.
The paging of the rows is provided in the main gridview.
My problem is the page change, when I try change page I have this error :
GridView paging event gvProducts_PageIndexChanging not firing
How to do resolve this ?
My code below.
Thanks in advance for any help.
Code Markup
<asp:GridView ID="gvProducts" runat="server" AutoGenerateColumns="false" CssClass="Grid"
DataKeyNames="CustomerID" OnRowDataBound="gvProducts_RowDataBound">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<img alt = "" style="cursor: pointer" src="images/plus.png" />
<asp:Panel ID="pnlOrders" runat="server" Style="display: none">
<asp:GridView ID="gvOrders" runat="server" AutoGenerateColumns="false" CssClass = "ChildGrid">
<Columns>
<asp:BoundField ItemStyle-Width="150px" DataField="OrderId" HeaderText="Order Id" />
<asp:BoundField ItemStyle-Width="150px" DataField="OrderDate" HeaderText="Date" />
</Columns>
</asp:GridView>
</asp:Panel>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField ItemStyle-Width="150px" DataField="ContactName" HeaderText="Contact Name" />
<asp:BoundField ItemStyle-Width="150px" DataField="City" HeaderText="City" />
</Columns>
<PagerTemplate>
<asp:ImageButton ID="ImageButton1" runat="server" ImageUrl="/aspnet/img/bot_back_doppio.gif"
CommandArgument="First" CommandName="Page" />
<asp:ImageButton ID="ImageButton2" runat="server" ImageUrl="/aspnet/img/bot_back.gif"
CommandArgument="Prev" CommandName="Page" />
Page
<asp:DropDownList ID="ddlPages" runat="server" AutoPostBack="True" CssClass="ddl_Class"
OnSelectedIndexChanged="ddlPages_SelectedIndexChanged">
</asp:DropDownList>
of
<asp:Label ID="lblPageCount" runat="server"></asp:Label>
<asp:ImageButton ID="ImageButton3" runat="server" ImageUrl="/aspnet/img/bot_next.gif"
CommandArgument="Next" CommandName="Page" />
<asp:ImageButton ID="ImageButton4" runat="server" ImageUrl="/aspnet/img/bot_next_doppio.gif"
CommandArgument="Last" CommandName="Page" />
</PagerTemplate>
</asp:GridView>
Code Behind
protected void gvProducts_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
string customerId = gvProducts.DataKeys[e.Row.RowIndex].Value.ToString();
sql = #String.Format(" SELECT ... ");
GridView gvOrders = e.Row.FindControl("gvOrders") as GridView;
gvOrders.DataSource = GetData(sql);
gvOrders.DataBind();
}
if (e.Row.RowType == DataControlRowType.Pager)
{
DropDownList ddl = (DropDownList)(e.Row.FindControl("ddlpages"));
Label lblPageCount = (Label)e.Row.FindControl("lblPageCount");
if (lblPageCount != null)
lblPageCount.Text = gvProducts.PageCount.ToString();
for (int i = 1; i <= gvProducts.PageCount; i++)
{
ddl.Items.Add(i.ToString());
}
ddl.SelectedIndex = gvProducts.PageIndex;
if (gvProducts.PageIndex == 0)
{
((ImageButton)e.Row.FindControl("ImageButton1")).Visible = false;
((ImageButton)e.Row.FindControl("ImageButton2")).Visible = false;
}
if (gvProducts.PageIndex + 1 == gvProducts.PageCount)
{
((ImageButton)e.Row.FindControl("ImageButton3")).Visible = false;
((ImageButton)e.Row.FindControl("ImageButton4")).Visible = false;
}
}
}
protected void ddlPages_SelectedIndexChanged(object sender, EventArgs e)
{
GridViewRow gvrPager = gvProducts.BottomPagerRow;
DropDownList ddlPages = (DropDownList)gvrPager.Cells[0].FindControl("ddlPages");
gvProducts.PageIndex = ddlPages.SelectedIndex;
BindData();
}
protected void Paginate(object sender, CommandEventArgs e)
{
int intCurIndex = gvProducts.PageIndex;
switch (e.CommandArgument.ToString().ToLower())
{
case "First":
gvProducts.PageIndex = 0;
break;
case "Prev":
gvProducts.PageIndex = intCurIndex - 1;
break;
case "Next":
gvProducts.PageIndex = intCurIndex + 1;
break;
case "Last":
gvProducts.PageIndex = gvProducts.PageCount - 1;
break;
}
gvProducts.DataBind();
}
protected void gvProducts_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
gvProducts.PageIndex = e.NewPageIndex;
BindData();
}
Please try this :
[Solution] The GridView 'GridView1' fired event PageIndexChanging which wasn't handled
I hope I was helpful.

Why do checkboxes in the gridview firstly after checking and afterwards unchecking in the PreRender stage eventually are checked?

Please help me with following, just something weird is going on.
I have a gridview with paging where the first column is filled with checkboxes.
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataSourceID="..." DataKeyNames="EventID" EnableViewState="false"
GridLines="None" AllowSorting="True"
AllowPaging="True" Width="100%"
onpageindexchanging="GridView1_PageIndexChanging"
onprerender="GridView1_PreRender">
<HeaderStyle Wrap="false" />
<Columns>
<asp:TemplateField HeaderStyle-HorizontalAlign="Left">
<HeaderTemplate>
<asp:CheckBox ID="SelectAllEvs" runat="server" EnableViewState="false" />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="EventSelector" runat="server" EnableViewState="false" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField ... >
<ItemStyle Wrap="False" />
</asp:BoundField>
<asp:BoundField ... >
</asp:BoundField>
<asp:BoundField ... >
</asp:BoundField>
</Columns>
</asp:GridView>
CodeBehind:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
if (Session["PageIndex"] != null)
{
GridView1.PageIndex = Convert.ToInt32(Session["PageIndex"]);
}
}
}
protected void GridView1_PreRender(object sender, EventArgs e)
{
// loading checkbox values from the session collection
GridView gv = (GridView)sender;
LoadCheckboxState(gv);
Session["PageIndex"] = gv.PageIndex;
}
private void LoadCheckboxState(GridView gv)
{
for (int i = 0; i < gv.Rows.Count; i++)
{
var chkBox = GridView1.Rows[i].FindControl("EventSelector") as CheckBox;
int id = gv.PageIndex * gv.PageSize + i;
if (SelectedIndexes.Contains(id))
{
chkBox.Checked = true;
}
else
{
chkBox.Checked = false;
}
}
}
private List<int> SelectedIndexes
{
get
{
if(Session["selectedRows"] == null)
{
Session["selectedRows"] = new List<int>();
}
return (List<int>)Session["selectedRows"];
}
}
private void SaveCheckboxState(GridView gv)
{
for (int i = 0; i < GridView1.Rows.Count; i++)
{
var chkBox = GridView1.Rows[i].FindControl("EventSelector") as CheckBox;
int id = gv.PageIndex * gv.PageSize + i;
if (chkBox.Checked)
{
//see if we have an id added already
if (!SelectedIndexes.Contains(id))
{
SelectedIndexes.Add(id);
}
}
else
{
if (SelectedIndexes.Contains(id))
{
SelectedIndexes.Remove(id);
}
}
}
}
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
// saving current page checkbox values to the session collection
GridView gv = (GridView)sender;
SaveCheckboxState(gv);
GridView1.PageIndex = e.NewPageIndex;
}
When I first get to my page I check some checkboxes and then press F5. Apparently after pressing it I dont have any values in SelectediIndexes and all unselected checkboxes must be checked = false on the PreRender stage but they appear checked after all this. And the problem of the same nature: I checked some on the first page; went to the second page (currently having 2 indexes in the SelectedValues) and after pressing F5 the same I have checked the same checkboxes as on the first page, though they mustn't. I'm absolutely confused with this. How can I fix this? Thanx for any help.
I've found the reason to that strange behavior. I'm using Firrefox. And one of the features of this browser is saving state of some fields when refreshing the page. If you want to refresh a page fully you should refresh it with pressed shift button. Tested in Google Chrome - works just fine.

GridView with Jump to Page DropDownList

Hi I want to have a DropDownList outside of my GridView that displays a list of page numbers. When the user clicks on a page number, the GridView should go to that page. I am able to populate the DropDownList, but it's not working with the GridView
Here is my GridView and DropDownList
<asp:DropDownList ID="ddlPageNumber" runat="server" AutoPostBack="True" OnSelectedIndexChanged="ddlPaging_SelectedIndexChanged">
</asp:DropDownList> of
<%=GridView1.PageCount%>
<asp:GridView ID="GridView1" runat="server" AllowPaging="True"
AllowSorting="True" AutoGenerateColumns="False" BorderStyle="Solid" GridLines="Both" HeaderStyle-BackColor="#990033" Width="1000px"
DataSourceID="EntityDataSource1" OnRowDataBound="GridView1_RowDataBound" OnDataBound="GridView1_DataBound">
<HeaderStyle ForeColor="White"></HeaderStyle>
<Columns>
<asp:BoundField DataField="intBatchID" HeaderText="Batch ID" ReadOnly="True"
SortExpression="intBatchID" />
<asp:BoundField DataField="vcharName" HeaderText="Name" ReadOnly="True"
SortExpression="vcharName" />
<asp:BoundField DataField="dtmScheduled" HeaderText="Date Scheduled"
ReadOnly="True" SortExpression="dtmScheduled" />
<asp:BoundField DataField="intBatchPriorityLevel"
HeaderText="Priority Level" ReadOnly="True"
SortExpression="intBatchPriorityLevel" />
</Columns>
<PagerSettings Mode="NumericFirstLast" Position="TopAndBottom" PageButtonCount="4" PreviousPageText="Previous" NextPageText="Next" FirstPageText="First" LastPageText="Last" />
<PagerStyle HorizontalAlign="Center" />
</asp:GridView>
Here's my code behind
protected void GridView1_DataBound(object sender, EventArgs e)
{
for (int cnt = 0; cnt < GridView1.PageCount; cnt++)
{
int curr = cnt + 1;
ListItem item = new ListItem(curr.ToString());
if (cnt == GridView1.PageIndex)
{
item.Selected = true;
}
ddlPageNumber.Items.Add(item);
}
}
protected void ddlPaging_SelectedIndexChanged(object sender, EventArgs e)
{
GridView1.PageIndex = ddlPageNumber.SelectedIndex;
}
After you update the PageIndex you need to rebind the grid, like this:
protected void ddlPaging_SelectedIndexChanged(object sender, EventArgs e)
{
GridView1.PageIndex = ddlPageNumber.SelectedIndex;
GridView1.DataBind();
}
UPDATE:
Since you are dynamically building the drop down list items for the page numbers, then you need to re-build them whenever a post back to the server happens or whenever the grid is rebound, like this:
private void BuildPageNumbers()
{
ddlPageNumber.Items.Clear();
for (int cnt = 0; cnt < GridView1.PageCount; cnt++)
{
int curr = cnt + 1;
ListItem item = new ListItem(curr.ToString());
if (cnt == GridView1.PageIndex)
{
item.Selected = true;
}
ddlPageNumber.Items.Add(item);
}
}
Now in your DataBound and Page_Load events, you can call this method, like this:
protected void Page_Load(object sender, EventArgs e)
{
BuildPageNumbers();
}
protected void GridView1_DataBound(object sender, EventArgs e)
{
BuildPageNumbers();
}

Popup confirmation [duplicate]

This question already has answers here:
I want to delete record from GridView.Before to this ask for confirmation like "Are you sure to delete?"
(4 answers)
Closed 9 years ago.
I need popup confirmation on button click deleting rows from asp.net gridview using c#.
Below is the code for button click for deleting rows from the gridview. I require popup confirmation before deleting.
Here is the code
protected void annDelete_Click(object sender, EventArgs e)
{
foreach (GridViewRow row in GridView1.Rows)
{
CheckBox cb = (CheckBox)row.FindControl("chk_delete");
if (cb.Checked && cb != null)
{
{
int ID_No = Convert.ToInt32(GridView1.DataKeys[row.RowIndex].Value);
MySqlCommand com = new MySqlCommand();
com.CommandText = "Delete from announcement where id = '" + ID_No + "'";
com.Connection = con;
//con.Open();
com.ExecuteNonQuery();
con.Close();
GridView1.DataSource = null;
}
}
}
LoadIssueData();
}
this works for my delete button in gridview:
html:
<asp:GridView ID="gv" runat="server" AutoGenerateColumns="False"
AllowPaging="True" AllowSorting="True"
onpageindexchanging="gv_PageIndexChanging"
onsorting="gv_Sorting" GridLines="None" DataKeyNames="ID"
PageSize="20" onrowdeleting="gv_RowDeleting"
onrowdatabound="gv_RowDataBound" >
<PagerSettings FirstPageText="First" LastPageText="Last"
Mode="NumericFirstLast" NextPageText="Next" PageButtonCount="5"
PreviousPageText="Previous" />
<Columns>
<asp:BoundField DataField="SECURITIES_NAME" HeaderText="Securities Name"
SortExpression="SECURITIES" />
<asp:BoundField DataField="FIN_YEAR" HeaderText="Financial Year"
SortExpression="FIN_YEAR" />
<asp:BoundField DataField="RECORD_DATE" HeaderText="Record Date"
SortExpression="RECORD_DATE" />
<asp:BoundField DataField="AGM_DATE" HeaderText="AGM Date"
SortExpression="AGM_DATE" />
<asp:BoundField DataField="CA_SEQ_NO" HeaderText="CA SEQ NO"
SortExpression="CA_SEQ_NO" />
<asp:TemplateField HeaderText="Action">
<ItemTemplate>
<div class="actions">
<asp:LinkButton ID="lbView" runat="server" CausesValidation="True" CommandName="Select" Text="View"></asp:LinkButton>
<asp:LinkButton ID="lbEdit" runat="server" CausesValidation="True" CommandName="Edit" Text="Edit"></asp:LinkButton>
<asp:LinkButton ID="lbDelete" runat="server" OnClientClick="return confirm('Are you sure want to delete the Corporate Action?')" CausesValidation="False"
CommandName="Delete" Text="Delete"></asp:LinkButton>
</div>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<PagerStyle CssClass="pagination-flickr" BorderStyle="None" />
<HeaderStyle BorderStyle="None" />
<AlternatingRowStyle CssClass="altrow" />
</asp:GridView>
the codebehind cs:
protected void Page_Load(object sender, EventArgs e)
{
IsAuthenticated.CheckSession();
if (!IsPostBack)
{
if (Session["setFlash"] != null)
{
if (Session["setFlash"].ToString() == "1")
{
ltrMsg.Text = #"<div class='message-green'>Save Successfully</div>";
Session["setFlash"] = null;
}
else
{
ltrMsg.Text = #"<div class='message'>Not Save Successfully</div>";
Session["setFlash"] = null;
}
}
common.gv(#"Select SECURITIES_ID,BO_FNC_GET_SECURITIES_NAME(SECURITIES_ID) SECURITIES_NAME,
CA_SEQ_NO,FIN_YEAR,RECORD_DATE,AGM_DATE,SETUP_DATE,ID,ROWID From CA_MST", gv);
ViewState["sortingOrder"] = string.Empty;
DataBindGrid("", "");
}
}
protected void gv_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
string wh = "ID='" + gv.DataKeys[e.RowIndex].Values[0].ToString() + "'";
DataProcess.Save("CA_MST", wh);
common.gv(#"Select SECURITIES_ID,BO_FNC_GET_SECURITIES_NAME(SECURITIES_ID) SECURITIES_NAME,
CA_SEQ_NO,FIN_YEAR,RECORD_DATE,AGM_DATE,SETUP_DATE,ID,ROWID FROM CA_MST", gv);
}
protected void gv_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
gv.PageIndex = e.NewPageIndex;
common.gv(#"Select SECURITIES_ID,BO_FNC_GET_SECURITIES_NAME(SECURITIES_ID) SECURITIES_NAME,
CA_SEQ_NO,FIN_YEAR,RECORD_DATE,AGM_DATE,SETUP_DATE,ID,ROWID FROM CA_MST", gv);
}
private void DataBindGrid(string sortExpr, string sortOrder)
{
// GetDataTable returns a filled table
DataTable dt = DataProcess.getDataTable(#"Select SECURITIES_ID,BO_FNC_GET_SECURITIES_NAME(SECURITIES_ID) SECURITIES_NAME,
CA_SEQ_NO,FIN_YEAR,RECORD_DATE,AGM_DATE,SETUP_DATE,ID,ROWID FROM CA_MST");
// any check to validate dt
if (dt != null)
{
DataView dv = dt.DefaultView;
if (sortExpr != string.Empty)
dv.Sort = sortExpr + " " + sortOrder;
this.gv.DataSource = dv;
this.gv.DataBind();
}
else
{
this.gv.DataSource = null;
this.gv.DataBind();
}
}
protected void gv_Sorting(object sender, GridViewSortEventArgs e)
{
DataBindGrid(e.SortExpression, sortingOrder);
}
public string sortingOrder
{
get
{
if (ViewState["sortingOrder"].ToString() == "desc")
ViewState["sortingOrder"] = "asc";
else
ViewState["sortingOrder"] = "desc";
return ViewState["sortingOrder"].ToString();
}
set
{
ViewState["sortingOrder"] = value;
}
}
protected void gv_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
LinkButton lbv = (LinkButton)e.Row.FindControl("lbView");
lbv.PostBackUrl = "CaMstVw.aspx?rid=" + gv.DataKeys[e.Row.RowIndex].Values[0].ToString();
LinkButton lb = (LinkButton)e.Row.FindControl("lbEdit");
lb.PostBackUrl = "CaMstIns.aspx?rid=" + gv.DataKeys[e.Row.RowIndex].Values[0].ToString() ;
}
}
Assuming annDelete is an asp.net button control you may put following code to ask client confirmation:
HTML:
<asp:Button ID="annDelete" OnClientClick="if(!confirm('Confirm delete?')) return false;"></asp:Button>
return false will avoid server side hit.
Let's assume you have a <asp:Button> control.
Just add the OnClientClick event like:
<asp:Button id="btnDelete" OnClick="annDelete_Click"
OnClientClick="return confirm('Are you sure?');" />
the confirm javascript call will open a OK / Cancel alert and will return true if the user pressed OK of false otherwise, that you will return to the button.
the button will continue to invoke the __Post event only if you return true.
You can add OnClientClick attribute:
<asp:Button ID="annDelete" OnClientClick="return confirm('do you really want to delete?');" runat="server" Text="Button" OnClick="annDelete_Click" />
If user will choose ok, confirm function will return true and __doPostBack() function will be called, otherwise - not.

GridView OnRowUpdating does not fire due to CommandName="edit"

I already spend 2 days trying to solve this issue but no luck on how to solve this. I have a GridView to display data from the database then it also have functionality to modify and delete. This is the current ASP code for my GridView:
<asp:GridView ID="dgvSortKey" runat="server" AllowSorting="True" OnRowDataBound="gv_drb"
AutoGenerateColumns="False" AllowPaging="True" BackColor="White" BorderColor="#336666"
BorderStyle="Double" BorderWidth="3px" CellPadding="4" GridLines="Horizontal"
Height="73px" AutoGenerateEditButton="True" OnRowEditing="dgvSortKey_RowEditing"
OnRowUpdating="dgvSortKey_RowUpdating" OnRowCancelingEdit="dgvSortKey_RowCancelingEdit"
OnSelectedIndexChanging="dgvSortKey_SelectedIndexChanging" OnPageIndexChanged="dgvSortKey_PageIndexChanged"
OnPageIndexChanging="dgvSortKey_PageIndexChanging" OnRowCommand="dgvSortKey_RowCommand"
OnRowDeleted="dgvSortKey_RowDeleted" OnRowUpdated="dgvSortKey_RowUpdated" Width="561px"
PageSize="15" DataKeyNames="KeyCode,KeyDescription">
<FooterStyle BackColor="White" ForeColor="#333333" />
<RowStyle BackColor="White" ForeColor="#333333" />
<PagerStyle BackColor="#336666" ForeColor="White" HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#339966" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#336666" Font-Bold="True" ForeColor="White" HorizontalAlign="Center" />
<AlternatingRowStyle BackColor="LightCyan" />
<Columns>
<asp:TemplateField HeaderText="">
<ItemTemplate>
<asp:LinkButton ID="lnkdelete" runat="server" OnClick="lnkdelete_Click">Delete</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Instruction Key Code">
<ItemTemplate>
<asp:Label ID="lblValKeyCode" runat="server" Text='<%#System.Web.HttpUtility.HtmlEncode((string)Eval("KeyCode")) %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtValKeyCode" runat="server" Text='<%#Bind("KeyCode") %>' MaxLength="10"
CausesValidation="false"></asp:TextBox>
</EditItemTemplate>
<ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" CssClass="GvBorderGreen" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Description">
<ItemTemplate>
<asp:Label ID="lblValKeyDescription" runat="server" Text='<%#System.Web.HttpUtility.HtmlEncode((string)Eval("KeyDescription")) %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtValKeyDescription" runat="server" Text='<%#Bind("KeyDescription") %>'
Width="300" MaxLength="20" CausesValidation="false"></asp:TextBox>
</EditItemTemplate>
<ItemStyle CssClass="GvBorderGreen" />
</asp:TemplateField>
</Columns>
</asp:GridView>
The problem is I can't update a certain record after click the Update Button, please see the image below:
When I'm in debug mode, it does not pass on OnRowUpdating event instead it passes to OnRowEditing. One thing that it makes me surprise is that when it fires to OnRowCommand, the CommandName set to "Edit" when Update Button is clicked. Please see the image below:
BTW this the Code Behind.
protected void dgvSortKey_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
//Currently Unreachable code due to unknown reason. RowUpdating not trigger even clicking Update Button in the GridView
// this.dvDetialContent.Visible = true;
List<SqlDbParameter> list = new List<SqlDbParameter>();
TextBox txtValKeyDescription = dgvSortKey.Rows[e.RowIndex].FindControl("txtValKeyDescription") as TextBox;
TextBox txtValKeyCode = dgvSortKey.Rows[e.RowIndex].FindControl("txtValKeyCode") as TextBox;
if (string.IsNullOrEmpty(txtValKeyCode.Text) || string.IsNullOrEmpty(txtValKeyDescription.Text))
{
string alert = "alert('Instruction KeyCode or KeyDecription should not be empty');";
ScriptManager.RegisterStartupScript(this, this.GetType(), "scripting", alert, true);
}
else
{
//Trace.Write("txtKeyCode", HttpUtility.HtmlDecode(txtKeyCode.Text));
//Trace.Write("txtKeyDescription", txtKeyDescription.Text);
//Trace.Write("txtValKeyCode", txtValKeyCode.Text);
//Trace.Write("txtValKeyDescription", txtValKeyDescription.Text);
list.Add(new SqlDbParameter("#oldcode", HttpUtility.HtmlDecode(txtKeyCode.Text)));
list.Add(new SqlDbParameter("#oldname", HttpUtility.HtmlDecode(txtKeyDescription.Text)));
list.Add(new SqlDbParameter("#newcode", HttpUtility.HtmlDecode(txtValKeyCode.Text)));
list.Add(new SqlDbParameter("#newname", HttpUtility.HtmlDecode(txtValKeyDescription.Text)));
try
{
int result = CoreUtility.ExecuteNonQuery("update InstructionKey set KeyCode=#newcode, KeyDescription=#newname where KeyCode = #oldcode and KeyDescription = #oldname", list);
//Trace.Write("ResultValue", result.ToString());
}
catch (Exception ex)
{
string alert = "alert('Instruction KeyCode should not be duplicate');";
ScriptManager.RegisterStartupScript(this, this.GetType(), "scripting2", alert, true);
}
}
dgvSortKey.EditIndex = -1;
imgbtnFilter_Click(null, null);
this.txtKeyCode.Text = "";
this.txtKeyDescription.Text = "";
}
protected void dgvSortKey_RowEditing(object sender, GridViewEditEventArgs e)
{
// this.dvDetialContent.Visible = true;
//if (ViewState["updateFlag"] == null)
//{
//ViewState["editFlag"] = "forEdit";
//ViewState["editIndex"] = e.NewEditIndex;
dgvSortKey.EditIndex = e.NewEditIndex;
Label lblValKeyDescription = dgvSortKey.Rows[e.NewEditIndex].FindControl("lblValKeyDescription") as Label;
Label lblValKeyCode = dgvSortKey.Rows[e.NewEditIndex].FindControl("lblValKeyCode") as Label;
this.txtKeyCode.Text = lblValKeyCode.Text;
this.txtKeyDescription.Text = lblValKeyDescription.Text;
imgbtnFilter_Click(null, null);
//}
//else
//{
//RowUpdate((int)ViewState["editIndex"]);
//ViewState.Remove("updateFlag");
//ViewState.Remove("editFlag");
//ViewState.Remove("editIndex");
//}
}
protected void dgvSortKey_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
dgvSortKey.EditIndex = -1;
imgbtnFilter_Click(null, null);
}
protected void dgvSortKey_SelectedIndexChanging(object sender, GridViewSelectEventArgs e)
{
this.dvDetialContent.Visible = true;
Label lblValKeyDescription = dgvSortKey.Rows[e.NewSelectedIndex].FindControl("lblValKeyDescription") as Label;
Label lblValKeyCode = dgvSortKey.Rows[e.NewSelectedIndex].FindControl("lblValKeyCode") as Label;
this.txtKeyCode.Text = lblValKeyCode.Text;
this.txtKeyDescription.Text = lblValKeyDescription.Text;
}
protected void dgvSortKey_PageIndexChanged(object sender, EventArgs e)
{
}
protected void dgvSortKey_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
dgvSortKey.PageIndex = e.NewPageIndex;
imgbtnFilter_Click(null, null);
}
protected void dgvSortKey_RowUpdated(object sender, GridViewUpdatedEventArgs e)
{
}
protected void dgvSortKey_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
String jsScript = "";
jsScript += "var answer=confirm('Delete this Instruction Key?');\n";
jsScript += "if (!answer){\n";
jsScript += " document.getElementById('ctl00_cthContent_hdDelete').Value = 'DELETE';\n";
jsScript += "}\n";
//return;
ScriptManager.RegisterStartupScript(this, this.GetType(), "script", jsScript, true);
List<SqlDbParameter> list = new List<SqlDbParameter>();
Label lblValKeyCode = dgvSortKey.Rows[e.RowIndex].FindControl("lblValKeyCode") as Label;
Label lblValKeyDescription = dgvSortKey.Rows[e.RowIndex].FindControl("lblValKeyDescription") as Label;
list.Add(new SqlDbParameter("#code", lblValKeyCode.Text));
list.Add(new SqlDbParameter("#name", lblValKeyDescription.Text));
CoreUtility.ExecuteNonQuery("DELETE FROM [InstructionKey] WHERE KeyCode=#code and KeyDescription=#name;", list);
Initial();
this.dvDetialContent.Visible = false;
dgvSortKey.EditIndex = -1;
imgbtnFilter_Click(null, null);
}
protected void dgvSortKey_RowCommand(object sender, GridViewCommandEventArgs e)
{
string id = e.CommandName;
}
protected void dgvSortKey_RowDeleted(object sender, GridViewDeletedEventArgs e)
{
}
protected void gv_drb(object sender, GridViewRowEventArgs e)//
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
LinkButton lnkbtnresult = (LinkButton)e.Row.FindControl("lnkdelete");
//raising javascript confirmationbox whenver user clicks on link button
lnkbtnresult.Attributes.Add("onclick", "javascript:return ConfirmationBox()");
}
}
While I have not figured out the bug, there is a workaround you may want to try.
Since the autogenerated edit button is giving you trouble, why not generate it yourself?
Like this:
<asp:TemplateField HeaderText="">
<ItemTemplate>
<asp:LinkButton ID="lnkedit" runat="server" CommandName="Edit">Edit</asp:LinkButton>
</ItemTemplate>
<EditItemTemplate>
<asp:LinkButton ID="lnkedit" runat="server" CommandName="Update">Update</asp:LinkButton>
<asp:LinkButton ID="lnkedit" runat="server" CommandName="Cancel">Cancel</asp:LinkButton>
</EditItemTemplate>
</asp:TemplateField>
And handle it in your code behind:
void dgvSortKey_RowCommand(Object sender, GridViewCommandEventArgs e)
{
// If multiple buttons are used in a GridView control, use the
// CommandName property to determine which button was clicked.
if(e.CommandName=="Update")
{
}
}

Categories

Resources