Popup confirmation [duplicate] - c#

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.

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 OnRowEditing is required even though it has no logic?

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

Adding Dynamic Rows in Gridview and How to retain selected option from user control in Gridview

I have created user control named CRE.ascx,this control has 3 dropdownlist.
First dropdownlist bind data on pageload.Second and third based on SelectedIndexChanged.
<table cellspacing="0" cellspading="0" style="width:550px;height:30px;">
<tr>
<td style="width:30%;">
<asp:DropDownList ID="ddlCRE" runat="server" Height="20px" Width="145px" OnSelectedIndexChanged="ddlCRE_SelectedIndexChanged" AutoPostBack="true">
</asp:DropDownList>
</td>
<td style="width:30%;">
<asp:DropDownList ID="ddlDataPoints" runat="server" Height="20px" Width="145px" OnSelectedIndexChanged="ddlDataPoints_SelectedIndexChanged" AutoPostBack="true">
</asp:DropDownList>
</td>
<td style="width:30%;">
<asp:DropDownList ID="ddlErrorCode" runat="server" Height="20px" Width="145px" OnSelectedIndexChanged="ddlErrorCode_SelectedIndexChanged" AutoPostBack="true">
</asp:DropDownList>
</td>
<td style="width:10%;">
<asp:TextBox ID="tbxErrorScore" runat="server" style="height:17px;border:0px;font-family:'Segoe UI';font-size:13px;font-weight:500;color:white;background-color:#333333;
width:65px;" ReadOnly="true"> </asp:TextBox>
</td>
</tr>
</table>
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//Get Ticket Type Values
dbtickettype = helpdsktcktusrHandler.GetTicketType("DPT0001");
ddlCRE.DataSource = dbtickettype;
ddlCRE.DataValueField = "Type_ID";
ddlCRE.DataTextField = "Type_Name";
ddlCRE.DataBind();
ddlCRE.Items.Insert(0, new ListItem("Select Type", "SLCT0000"));
}
else
{
}
}
protected void ddlCRE_SelectedIndexChanged(object sender, EventArgs e)
{
string selectedTypeID = ddlCRE.SelectedValue.ToString();
try
{
if (selectedTypeID == "SLCT0000")
{
ddlDataPoints.Items.Clear();
ddlErrorCode.Items.Clear();
tbxErrorScore.Text = string.Empty;
}
else
{
//Get Category Details
dbticketCategory = helpdsktcktusrHandler.GetTicketCategoryDetails(selectedTypeID);
//Binding Ticket Type values to Listbox
ddlDataPoints.DataSource = dbticketCategory;
ddlDataPoints.DataValueField = "Category_ID";
ddlDataPoints.DataTextField = "Category_Name";
ddlDataPoints.DataBind();
ddlDataPoints.Items.Insert(0, new ListItem("Select Category", "SLCT0000"));
//Clear Items
ddlErrorCode.Items.Clear();
tbxErrorScore.Text = string.Empty;
}
}
catch (Exception ex)
{
}
}
protected void ddlDataPoints_SelectedIndexChanged(object sender, EventArgs e)
{
string selectedCatID = ddlDataPoints.SelectedValue.ToString();
try
{
if (selectedCatID == "SLCT0000")
{
ddlErrorCode.Items.Clear();
tbxErrorScore.Text = string.Empty;
}
else
{
//Get Category Details
dbticketSubCategory = helpdsktcktusrHandler.GetTicketSubCategoryDetails(selectedCatID);
//Binding Ticket Type values to Listbox
ddlErrorCode.DataSource = dbticketSubCategory;
ddlErrorCode.DataValueField = "Sub_Category_ID";
ddlErrorCode.DataTextField = "Sub_Category_Name";
ddlErrorCode.DataBind();
ddlErrorCode.Items.Insert(0, new ListItem("Select Subcategory", "SLCT0000"));
//Clear Items
tbxErrorScore.Text = string.Empty;
}
}
catch (Exception ex)
{
}
}
protected void ddlErrorCode_SelectedIndexChanged(object sender, EventArgs e)
{
string selectedSubcatID = ddlErrorCode.SelectedValue.ToString();
try
{
if (selectedSubcatID == "SLCT0000")
{
tbxErrorScore.Text = string.Empty;
}
else
{
//Get Category Details
dbticketIssues = helpdsktcktusrHandler.GetTicketIssueDetails(selectedSubcatID);
////Binding Ticket Type values to Listbox
//ddlstIssue.DataSource = dbticketIssues;
//ddlstIssue.DataValueField = "IssueID";
//ddlstIssue.DataTextField = "Issue_Name";
//ddlstIssue.DataBind();
tbxErrorScore.Text = dbticketIssues.Rows[0][1].ToString();
}
}
catch (Exception ex)
{
}
}
then register directive and an instance of the user control added to the page.
In this main page, i have added one Gridview, user control UC1 and two buttons
included in the ItemTemplate.
<%# Register src="~/CRE.ascx" TagName="InsertNewCRE" TagPrefix="uc1" %>
<asp:UpdatePanel ID="MainUpdatePanel" runat="server">
<ContentTemplate>
<div id="dvsubCRE" class="dvsubCRE" runat="server">
<!-----[[[ GRIDVIEW ADDING CRE ]]]----->
<div id="dvAddingErrorInfo" class="dvAddingErrorInfo">
<!-- LOAD CRE DROPDOWN INFO GRID -->
<asp:GridView ID="gvCREInfo" runat="server" CssClass="gvErrorInfo" AlternatingRowStyle-CssClass="" ShowFooter="false" ShowHeader="false"
EnableViewState="True" GridLines="None" EmptyDataText="No records found" AutoGenerateColumns="true" CaptionAlign="Left" CellPadding="0"
ShowHeaderWhenEmpty="True" OnRowCreated="gvCREInfo_RowCreated" OnRowCommand="gvCREInfo_RowCommand" >
<Columns>
<asp:BoundField DataField="RowNumber" />
<asp:TemplateField ItemStyle-Width="25%" ItemStyle-Height="20px">
<ItemTemplate>
<uc1:InsertNewCRE id="UC1InserCRE" runat="server" EnableViewState="true" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField ItemStyle-Width="5%">
<ItemTemplate>
<asp:ImageButton ID="imgbtnAddCRE" runat="server" Width="20px" Height="20px" value="" ImageUrl="~/Images/Tracker/add.png"
CommandName="ButtonAddCRERow" CommandArgument="<%# ((GridViewRow) Container).RowIndex %>" />
<asp:ImageButton ID="imgbtnReoveCRE" runat="server" Width="20px" Height="20px" value="" Visible="false" ImageUrl="~/Images/Tracker/delete.png" CommandName="ButtonRemoveCRERow" CommandArgument="<%# ((GridViewRow) Container).RowIndex %>" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<!-- LOAD CRE DROPDOWN INFO GRID CLOSE -->
</div>
<!-----[[[ GRIDVIEW ADDING CRE CLOSE ]]]----->
</div>
</ContentTemplate>
</asp:UpdatePanel>
When main page loads, user control UC1 loaded in the gridview and pull out the data from CRE.ascx page.I have bind dummy data on page load to the gridview.Add new row along with user control mentioned in the RowCommand.
protected void Page_Load(object sender, EventArgs e)
{
try
{
if (!IsPostBack)
{
DataTable dt = new DataTable();
DataRow dr = null;
dt.Columns.Add(new DataColumn("RowNumber", typeof(string)));
dr = dt.NewRow();
dr["RowNumber"] = 1;
dt.Rows.Add(dr);
ViewState["CurrentTable"] = dt;
gvCREInfo.DataSource = dt;
gvCREInfo.DataBind();
}
else
{
}
}
catch (Exception ex)
{
}
}
protected void gvCREInfo_RowCommand(object sender, GridViewCommandEventArgs e)
{
#region ADD NEW CRE ROW
if (e.CommandName == "ButtonAddCRERow")
{
int index = Convert.ToInt32(e.CommandArgument);
GridViewRow row = gvCREInfo.Rows[index];
int count = gvCREInfo.Rows.Count;
DataRow drCurrentRow = null;
UserControl UC1 = (UserControl)(row.Cells[0].FindControl("UC1InserCRE"));
DataTable dtCurrentTable = (DataTable)ViewState["CurrentTable"];
for (int i = 0; i <= (count - 1); i++)
{
drCurrentRow = dtCurrentTable.NewRow();
dtCurrentTable.Rows.Add(drCurrentRow);
}
gvCREInfo.DataSource = dtCurrentTable;
gvCREInfo.DataBind();
}
#endregion
}
When i run this code working fine and i changed the first dropdownlist
it will pull data and bind to the second, like wise third one also.But when i click the add button selected data lost in the first row and second row control added not with data.How to retain existing selected data and load user control along with data it should not loss data event post back.Please help me and sort out this.
![enter image description here][1]
http://i.stack.imgur.com/wdYZv.jpg

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