ASP.NET Gridview delete row only on confirmation - c#

I have a gridview with the onRowDeleting method implemented. I would like to prompt the user with a pop up message to confirm whether they wish to delete this item or not.
If the user clicks "OK", "Confirm" or something similar then I would like the onRowsDeleting to be process and the record deleted. But if the user pressed "No" then I would like the method to be cancelled and the record not deleted.
How can this be done?
Here is my gridview and onRowDeleting method in the code behind.
<asp:GridView runat="server" ID="gvShowQuestionnaires" HeaderStyle-CssClass="table_header" CssClass="view" AlternatingRowStyle-CssClass="alt" AlternatingRowStyle-BackColor="#f3f4f8" AutoGenerateColumns="False"
DataKeyNames='QuestionnaireID' OnRowDeleting="gvShowQuestionnaires_RowDeleting" OnRowEditing="gvShowQuestionnaires_RowEdit" OnSelectedIndexChanged="gvShowQuestionnaires_SelectedIndexChanged" FooterStyle-CssClass="view_table_footer" >
<Columns>
<asp:BoundField DataField="QuestionnaireID" HeaderText="ID" HeaderStyle-Width="80px" ItemStyle-CssClass="bo"></asp:BoundField>
<asp:BoundField DataField="QuestionnaireName" HeaderText="Questionnaire Name" />
<asp:ButtonField CommandName="select" ButtonType="Link" Text="view results" />
<asp:CommandField HeaderText="Options" CausesValidation="true" ShowDeleteButton="True" ShowEditButton="true" EditText="Edit">
</asp:CommandField>
</Columns>
</asp:GridView>
protected void gvShowQuestionnaires_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
int questionnaireID = (int)gvShowQuestionnaires.DataKeys[Convert.ToInt32(e.RowIndex)].Value;
GetData.DeleteQuestionnaire(questionnaireID);
gvShowQuestionnaires.DataSource = DT;
gvShowQuestionnaires.DataBind();
lblActivity.Visible = true;
lblActivity.Text = "Your questionnaire has been deleted";
}

You should do that on clientside with javascript.
Therefore you can handle GridView's RowDataBound event to add this to the Delete-Button's OnClientClick:
protected void gvShowQuestionnaires_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
// reference the Delete LinkButton
LinkButton db = (LinkButton)e.Row.Cells[3].Controls[0];
db.OnClientClick = "return confirm('Are you certain you want to delete this questionnaire?');";
}
}
http://msdn.microsoft.com/en-us/library/bb428868.aspx
This js-function will return whether the user clicked ok or cancel. If a js-eventhandler returns false, the page will not postback to the server.

The "return confirm(..") Javascript is on the right track.
The problem is that ASP.NET will append js to call __doPostBack
so you'll get something like this in your HTML for the delete button:
OnClickClient="return confirm('Are you sure you want to delete this record?');";javascript:__doPostBack('ctl00$Main$PlansGrid','Delete$101')"
What happens is:
1) User clicks Delete button.
2) Confirm dialog displayed.
3) User clicks on OK button.
4) Confirm returns True.
5) return at beginning of statement executes and __doPostBack is not called.
The solution is to return only if confirm returns false:
OnClientClick="if(!confirm('Are you sure you want to delete this Plan?')) return;"
If user clicks OK confirm returns True and then __doPostBack executes.

Simply call a JavaScript function returning a boolean by "return" caller so if returns false this link button will not work.
ASPX
<asp:LinkButton runat="server" OnClientClick="return DeleteItem();" locationID='<%# DataBinder.Eval (Container.DataItem,"Id").ToString() %>' ID="linkDelete" OnClick="linkDelete_Click" title='<%# "Delete " + DataBinder.Eval (Container.DataItem,"City").ToString() %>' Style="float: left;"><img src="Asset/img/icon/bin.gif" alt="" hspace="3" /></asp:LinkButton>
Javascript
<script type="text/javascript">
function DeleteItem() {
if (confirm("Delete this Location?")) {
return true;
} else {
return false;
}
}
</script>
Server Side
protected void linkDelete_Click(object sender, EventArgs e)
{
int locationID =0;
int.TryParse(((LinkButton)sender).Attributes["locationID"].ToString(),out locationID);
if (locationID > 0)
{
Location loc = Location.GetById(locationID);
CurrentDataContext.CurrentContext.DeleteObject(loc);
CurrentDataContext.CurrentContext.SaveChanges();
bindGv();
}
}

Another way:
if (e.Row.RowType == DataControlRowType.DataRow)
{
// loop all data rows
foreach (DataControlFieldCell cell in e.Row.Cells)
{
// check all cells in one row
foreach (Control control in cell.Controls)
{
// Must use LinkButton here instead of ImageButton
// if you are having Links (not images) as the command button.
LinkButton button = control as LinkButton;
if (button != null && button.CommandName == "Delete")
// Add delete confirmation
button.OnClientClick = "return confirm('Are you sure " +
"you want to delete this record?');";
}
}
}

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
string id = e.Row.Cells[2].Text;
if (e.Row.RowType == DataControlRowType.DataRow)
{
LinkButton db = (LinkButton)e.Row.Cells[6].Controls[0];
db.OnClientClick = "return confirm('Are you want to delete this Work Description : " + id + "?');";
}
}

Get by command button type
protected void gvShowQuestionnaires_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
// handle the Command Column Index
var commandColumnIndex = GvOperators.Columns
.OfType<DataControlField>()
.Select((x, i) => new { Index = i, Column = x })
.FirstOrDefault(x => x.Column is CommandField)
.Index;
var commandButtons = e.Row.Cells[commandColumnIndex].Controls.OfType<LinkButton>();
// reference the Delete LinkButton
var db = commandButtons.FirstOrDefault(x => x.CommandName == "Delete");
if(db!=null)
db.OnClientClick = "return confirm('Are you certain you want to delete this questionnaire?');";
}
}

Related

How to hide a link in a cell of a gridview?

I have a gridview which displays a data from the database. In one of the tables in this database have a column to store details about attanchment file. If the attachment is available that column value will set as "YES". Otherwise it will set as "NO". What I want to do is, show a link to view the attachment. But if cell value of the column is "NO" (when there is no attachment) the link must be hidden.
Note : I know how to view a file. Here what Im expecting is to hide the link in the cell which doesn't have an attachment.
This is what I have done upto now.
if (ds.Tables[0].Rows.Count > 0)
{
grdSo.DataSource = ds;
grdSo.DataBind();
for(int i=0; i <ds.Tables[0].Rows.Count; i++)
{
if (ds.Tables[0].Rows[i][6].Equals("NO"))
{
grdSo.Rows[i].Cells[6].Visible = false;
}
else
{
grdSo.Rows[i].Cells[6].Visible = true;
}
}
}
I could hide the cell using this code. But unfortunately this hides the lines of the cell too. How can I avoid it happening?
One of the ways to do this is to use server side control like LinkButton to view the link that you want to show and set the visibility of the control as per your requirement in the OnRowDataBound event of the gridview.
Below is the code to show/hide LinkButton on OnRowDataBound event.
protected void gridId_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DataSourceClass varData = (DataSourceClass)e.Row.DataItem;
// check if your data have flag to show the link
if(varData.show)
((LinkButton)e.Row.FindControl("linkbuttonId")).Visible = true;
else
((LinkButton)e.Row.FindControl("linkbuttonId")).Visible = false;
}
}
ASPX Code :
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" OnRowDataBound="GridView1_RowDataBound">
<Columns>
<asp:BoundField Visible="false" DataField="id" />
<asp:TemplateField HeaderText="Has Attachment">
<ItemTemplate>
<asp:Label ID="lblAtt" runat="server" Text='<%#Eval("HasAtt") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="View Attachment">
<ItemTemplate>
<asp:LinkButton ID="lbtnAtt" runat="server" OnClick="lbtnAtt_Click" Visible="false">View</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
CS Code :
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
this.BindGrid();
}
}
private void BindGrid()
{
//Here you write databind logic
// Datasource table of GridView1 should contain 'HasAtt' and 'id' as its binded to label.
}
private void ViewAttachment(int id)
{
//Here you write your logic to view attachment.
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow) // checking if row is datarow or not
{
Label lblHasAtt = e.Row.FindControl("lblAtt") as Label;
LinkButton lbtnViewAtt = e.Row.FindControl("lbtnAtt") as LinkButton;
lbtnViewAtt.Visible = (lblHasAtt.Text.ToLower() == "yes");
}
}
protected void lbtnAtt_Click(object sender, EventArgs e)
{
LinkButton lbtnViewAtt = sender as LinkButton;
GridViewRow grw = lbtnViewAtt.NamingContainer as GridViewRow;
int id = Convert.ToInt32(this.GridView1.Rows[grw.RowIndex].Cells[0].Text); // retriving value of first column on 'lbtnAtt' click row.
this.ViewAttachment(id);
}
I recall being able to parse through the grid view by using a for each for the rows and using a for statement for columns.
If I recall correctly, you can grab an item ie
row.Item[i]
foreach(GridViewRow row in GridView1.Rows)
{
for(int i = 0; i < GridView1.Columns.Count; i++)
{
// here you can do the logic to decide whether to show or hide the text for this cell
}
}
Sorry for formatting responding on my phone.

Change text in button (gridview) using if else

I have one button to change based on the page. I have 3 page which is confirmed, pending and rejected.
On confirmed and rejected the text inside the button is same but different for pending. How can change the word in the button. The button placed in the grid view.
Below the code in aspx file:
<asp:TemplateField>
<HeaderTemplate>Actions</HeaderTemplate>
<ItemTemplate>
<asp:Button ID="lnkbtnInfo" runat="server" CssClass="btn btn-success" Text="" CommandArgument='<%# DataBinder.Eval(Container.DataItem, "Id") %>' CommandName="Detail" /></td>
</ItemTemplate>
</asp:TemplateField>
How can i do in the cs file, to use the if else.
For rejected and confirmed page, the button is "view" and pending page is "review"
I figured that you need to use RowDataBound event handler on gridview and create if statement based on button's CommandArgument state:
protected void GridView_RowDataBound(Object sender, GridViewRowEventArgs e)
{
for (int i = 0; i < GridView.Rows.Count - 1; i++)
{
Button status = (Button)GridView.Rows[i].FindControl("lnkbtnInfo"); // find control from your button ID
String state = status.CommandArgument.ToString(); // assume the value given by Eval data binding
if (state.Equals("confirmed") || state.Equals("rejected"))
{
status.Text = "view";
}
else // if (state.Equals("pending"))
{
status.Text = "review";
}
}
}
Reference: Change button text in asp:gridview based on cell value C#
What you can also do is use Eval with ternary for changing Button Text on .aspx page,
Ternary Operator syntax
(your condition) ? "if true value":" if false value";
Here is Example " if you want to check that your 'Id' is 3 then Button Text should be View else It should be Review."
<asp:Button ID="lnkbtnInfo" runat="server" CssClass="btn btn-success" Text='<%# ((int)Eval("Id") == 3) ? "view":"Review" %>' CommandArgument='<%# DataBinder.Eval(Container.DataItem, "Id") %>' CommandName="Detail" />
Here my answer that works on my situation:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
for (int i = 0; i < GridView1.Rows.Count; i++)
{
Button name = (Button)GridView1.Rows[i].FindControl("lnkbtnInfo"); // find control from your button ID
Label status= (Label)GridView1.Rows[i].FindControl ("lblStatus");
if (status.Text == "Complete" || status.Text == "Rejected" || status.Text == "Cancelled" ||
status.Text == "Returned" || status.Text == "UserRejected")//refer to confirm and reject order
{
name.Text = "View";
}
else // refer to pending order
{
name.Text = "review";
}
}
}

Cancel row command does not work for GridView

i have a gridview which is inside an update panel. when i click "cance" after the edit, nothing happens. When i debug it does go into my gvWorkhours_RowCommand function and inside the cancel if, but nothing happens on screen (the edit fields are all still visible)
here is what i have:
<asp:GridView ID="gvWorkhours" runat="server" AutoGenerateColumns="false" CssClass="GridViewStyle" OnRowEditing="gvWorkhours_RowEditing"
OnRowCommand="gvWorkhours_RowCommand" >
<EmptyDataTemplate>
no data returned
</EmptyDataTemplate>
<Columns>
<asp:commandfield buttontype="Link" showeditbutton="true" edittext="Edit" />
<asp:TemplateField HeaderText="Organization">
<ItemTemplate>
<%# Eval("org.orgCode").ToString() + "- " + Eval("org.orgSubCode").ToString()%>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Year-Qtr">
<ItemTemplate>
<%# Eval("year").ToString() + "- " + Eval("qtr").ToString()%>
</ItemTemplate>
</asp:TemplateField>
.......
protected void gvWorkhours_RowEditing(Object sender, GridViewEditEventArgs e)
{
populateGrid(); //pulls from the Db and binds to the grid
gvWorkhours.EditIndex = e.NewEditIndex; //This is the selected row to edit
gvWorkhours.DataBind(); //Make the edit Template show up
}
protected void gvWorkhours_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 == "Cancel")
{
gvWorkhours.EditIndex = -1;
populateGrid();
}
}
private void populateGrid()
{
//getting all variables for update here.
Workhours wh = new Workhours(selectedItem, year, qtr);
gvWorkhours.DataSource = wh.exposures;
gvWorkhours.DataBind();
}
catch (Exception ex)
{
lblMessage.Text = ex.Message;
// throw(ex);
}
}
what am i missing here?
You don't have the UpdatePanel shown in your example, so I don't know how you have it set up, but if you have the UpdateMode set to Conditional, you probably need to manually call the Update method on the update panel:
if (e.CommandName == "Cancel")
{
gvWorkhours.EditIndex = -1;
populateGrid();
UpdatePanel1.Update(); // whatever the name of the UpdatePanel is
}
try to give other word than cancel like "CancelRecord" and then try with it
Yes it's an old question, but no answer.
Cancel needs to be in a RowCancelEdit method ... seems 'Cancel' is a protected word in this scenario
protected void gvResults_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
GridView gv = (GridView)sender;
gv.EditIndex = -1;
BindGrid2();
}

Confirm radio button inside gridview's event doesn't fire

In my Asp project, I have a radio button inside my gridview. The radio button only allows user to select once every time.
However when user clicks a radio button, a confirm message will appear and the record will only be saved if the user clicks "OK".
Everything is working, but now I'm facing a problem. The radio button oncheckedchanged seems to not fire when user clicks "OK". How can I fire the radio button event once the user clicks "Ok"?
Here is my code:
Javascript
function RadioCheck(rb) {
var gv = document.getElementById('Content_PageContent_ucSubMenuItem_module_sales_customer_submenuitem_contactpersonlist_ascx_gvContactPersonList');var rbs = gv.getElementsByTagName("input");
for (var i = 0; i < rbs.length; i++) {
if (rbs[i].type == "radio") {
//if radio button is check but not the selected value then false
if (rbs[i].checked && rbs[i] != rb) {
rbs[i].checked = false;
break;
}
}
}
return confirm('Confirm Save?');
}
client-side
<asp:TemplateField HeaderText="Default" ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:RadioButton ID="rdbtnDefault" runat="server" onclick="RadioCheck(this);" oncheckedchanged="rdbtnDefault_CheckedChanged" Visible='<%#((string)Eval("DEFAULT")) == "Y" ? false : true %>'/>
<asp:Image ID="imgDefault" runat="server" Height="13px" ImageUrl="~/Styles/images/tick-48x48.png" Width="13px" Visible='<% ((string)Eval("DEFAULT")) == "Y" ? true : false %>' />
</ItemTemplate>
Server side
//--Register for in post back--
if (Page.ClientScript.IsClientScriptBlockRegistered(DataUCContactListing) == false) {
ScriptManager.RegisterClientScriptBlock(this, typeof(Page), "gvRdBtnSelectOnce", blcGenerateScript.gvRdBtnSelectOnce(gvContactPersonList.ClientID,true), true);
ScriptManager.RegisterClientScriptBlock(this, typeof(Page), "gvSelectAllChkBox", blcGenerateScript.gvSelectAllChkBox(gvContactPersonList.ClientID), true);
}
//**Register for script**
protected void rdbtnDefault_CheckedChanged(object sender, EventArgs e) {
try {
RadioButton lnBTNDone = (RadioButton)sender;
GridViewRow row = (GridViewRow)lnBTNDone.NamingContainer;
string accountID = gvContactPersonList.DataKeys[row.RowIndex].Values[0].ToString();
int contactID = int.Parse(gvContactPersonList.DataKeys[row.RowIndex].Values[1].ToString());
using (TransactionScope scope = new TransactionScope()) {
dlcCustomerDB.updateAccountOtherDefaultN(accountID);
dlcCustomerDB.updateAccountDefaultY(accountID, contactID);
scope.Complete();
}
createGridView();
this.Session[gbcMessageSessionID.message1] = gbcMessageAlert.saveSuccessfully;
Response.Redirect(Request.Url.ToString());
} catch (Exception ex) {
logger.Error(ex.Message);
throw;
}
}
Look into following URLs
http://www.asp.net/web-forms/tutorials/data-access/enhancing-the-gridview/adding-a-gridview-column-of-radio-buttons-vb
Radiobutton checked change event not firing in gridview
Please look into this code
<asp:RadioButton ID="rdbtnDefault" runat="server" onclick="return RadioCheck(this);" oncheckedchanged="rdbtnDefault_CheckedChanged" Visible='<%#((string)Eval("DEFAULT")) == "Y" ? false : true %>' AutoPostBack="True" />
I have added "return" keyword for onclick event of RadioButton.

how to add delete confirmation prompt for command field in detail view?

I want to prompt the user for confirmation when he tries to delete a record in a detail view? I have command filed in which showDeletebutton set to true.
I found how to do the confirmation for gridview, but how can I modify to match detail view?
Code:
protected void GridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
// loop all data rows
foreach (DataControlFieldCell cell in e.Row.Cells)
{
// check all cells in one row
foreach (Control control in cell.Controls)
{
// Must use LinkButton here instead of ImageButton
// if you are having Links (not images) as the command button.
ImageButton button = control as ImageButton;
if (button != null && button.CommandName == "Delete")
// Add delete confirmation
button.OnClientClick = "if (!confirm('Are you sure " +
"you want to delete this record?')) return;";
}
}
}
}
Anybody?
<asp:DetailsView ID="DetailsView1" runat="server" Height="50px" Width="125px"
.....
<asp:BoundField DataField="price" HeaderText="price" SortExpression="price" />
<asp:BoundField DataField="Quantity" HeaderText="Quantity"
SortExpression="Quantity" />
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<asp:LinkButton ID="LinkButton2" runat="server" CausesValidation="False"
CommandName="New" Text="New"></asp:LinkButton>
<asp:LinkButton ID="lnkDelete" runat="server" CausesValidation="False"
CommandName="Delete" Text="Delete" OnClientClick="return confirm('Are you sure you want to delete this record');"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Fields>
</asp:DetailsView
This can be done easily on the markup code. I simply added the js code to the onClientClick property of the delete button:
OnClientClick="return confirm('Are you sure you want to delete this record');"
Or if you want do this in the code behind:
protected void DetailsView1_DataBound(object sender, EventArgs e)
{
LinkButton bttn = (LinkButton)DetailsView1.FindControl("lnkDelete");
bttn.OnClientClick = "return confirm('Are you sure you want to delete this record!');";
}
I found the answer to my question.
My answer:
protected void DViewComputer_DataBound1(object sender, EventArgs e)
{
int noRow = DViewComputer.Rows.Count - 1;//get the no of record
if (noRow >0)
{
Button button = (Button)(DViewComputer.Rows[noRow].Cells[0].Controls[2]);
// Add delete confirmation
((System.Web.UI.WebControls.Button)(button)).OnClientClick = "if (!confirm('Are you sure " +
"you want to delete this record?')) return;";
}
}
Anyways thanks for your help guys.
foreach (Control control in cell.Controls)
{
// Must use LinkButton here instead of ImageButton
// if you are having Links (not images) as the command button.
ImageButton button = control as ImageButton;
if (button != null && button.CommandName == "Delete")
// Add delete confirmation
button.Attributes.Add("onclick","your javascript here");
}
Please see the below URL......
http://www.codeproject.com/Articles/32756/ASP-NET-GridView-delete-confirmation-using-asp-Com
This corrects the OP's solution. The code was translated from the code found here: http://forums.aspfree.com/net-development-11/confirm-button-when-deleting-detailsview-120113-2.html
protected void dvEvent_DataBound(object sender, EventArgs e)
{
int commandRowIndex = dvEvent.Rows.Count - 1;
if (commandRowIndex > 0)
{
DetailsViewRow commandRow = dvEvent.Rows[commandRowIndex];
DataControlFieldCell cell = (DataControlFieldCell)commandRow.Controls[0];
foreach (Control ctrl in cell.Controls)
{
if (ctrl is ImageButton)
{
ImageButton ibt = (ImageButton)ctrl;
if (ibt.CommandName == "Delete")
{
ibt.ToolTip = "Click here to Delete";
ibt.CommandName = "Delete";
ibt.Attributes["onClick"] = "if (!confirm('Are you sure " +
"you want to delete this record?')) return;";
}
}
}
}
}

Categories