How to determine which button was clicked in gridview - c#

I have a gridview and my gridview has a template feild for image button,for delete one row.
At the moment I use rowcommand and rowargument for this image button to recognize what row want to delete. but I need to implement below scenario:
I want when user click on imagebutton,no postback occured ,a modal box(bootstrap modal) open ,and only when user click yesI'm sure button in modal, postback occure and data deleted...
Is this possible with asp.net gridview and if yes,How I can determine what button click in "yesI'm sure button" ???
thank you

Yes this is possible. Please try the below code:
<script type="text/javascript">
function ShowModal(gridItemIndex)
{
$(document).ready(function ()
{
$('#mymodal').modal('show');
var row = gridItemIndex.parentNode.parentNode;
var rowIndex = row.rowIndex-1; //row index of that row.
document.getElementById("<%=hfID.ClientID %>").value =rowIndex;
});
}
</script>
<asp:gridview id="yourGridView" onrowcommand="GridView_RowCommand"
<asp:TemplateField>
<ItemTemplate>
<asp:ImageButton name="btnDelete" CommandName="Delete" OnClientClick="return ShowModal(this);" ImageUrl="/imagepath.pgn" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</asp:gridview>
Then in code behind use the following event of GridView.
protected void GridView_RowCommand(Object sender, GridViewCommandEventArgs e)
{
if (e.CommandName=="Delete")
{
// Write your delete code here...
}
}

Related

Get rowindex of gridview on click of a button outside gridview

In my asp.net application (v4.0), I have a grid view. I use a list object to bind data to the grid view.
In the grid view there is a cancel button. On click of the cancel button the application should pop a message to the user asking for confirmation to proceed with cancel. ie. are you sure you want to cancel the record yes/no. When the user selects yes then the particular record should be cancelled.
Now the issue is, when the user selects yes then i need to the get the index of the row for which the cancel button is clicked and i need to remove it from the list object that is used to bind the grid and rebind the gridview .
please let me know how to achieve this.
Thanks for all the reply.. im using custom pop up instead of built in 'confirm' method. The custom pop up will have 'OK' and 'Cancel' button controls. Only on click of 'OK' button i need to get the selected record index. Built in confirm method mentioned in some replies will not suit my scenario. please let me know how to achieve this.
Add a hiddenfield into your page
<asp:HiddenField ID="HiddenField1" runat="server" />
Use the Id(use corresponding column name instead of Id) of the records as the CommandArgument of Cancel button
<asp:Button ID="btncancel" runat="server" CommandArgument='<%#Eval("Id") %>' Text="Cancel" />
Then on clicking the cancel button it calls the gridviews rowcommand function. In that function keep the CommandArgument value in the hidden field as follows
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
HiddenField1.Value = e.CommandArgument.ToString();
}
Then on clicking the OK button, it calls the click event. In that function remove the Item from the List and then bind the list again to the gridview
protected void btnOK_Click(object sender, ButtonClickEventArgs e)
{
string id = HiddenField1.Value;
//use this id to remove the data from the List
// bind the gridview
}
Try this..
You can use javascript function..
<asp:Button ID="Button1" runat="server" onclientclick="Validate(this) />
Declare an HTML hidden field in your page...
<input id="Hidden1" type="hidden" runat="server" clientidmode="static"/>
function Validate(obj) {
var r = confirm("are you sure you want to cancel ?");
if (r == true) {
var id = obj.id.toString();
var index = id.split("_");
var RowNumber = index[2].toString();
document.getElementById('Hidden1').value=RowNumber ;
}
else {
return;
}
}
Here we get id of the button somewhat as ContentPlacedholde_Button1_0..Then we split it to get the index..
Use command name and command argument on cancel button like this:
<asp:Button ID="btncancel" runat="server" CommandArgument='<%#Eval("Id") %>' CommandName="Cancel" Text="Cancel" />
And then on gridviewRowcommand use this:
if (e.CommandName == "Cancel")
{
int count = GridViewName.Rows.Count;
for (int i = 0; i < count; i++)
{
int id = Convert.ToInt32(e.CommandArgument);
}
}
Have you tried adding a CommandArgument value to the cancel button that represents the item, for example an ID? Then onclick, display a popup, if the user selects yes then use the ID to remove the item from your collection, then simply rebind the grid. The item will then be gone.

How to call JavaScript function in GridView Command Field?

I have return one Javascript function which asks the confirm message to the user.
The JavaScript functions is
function ConfirmOnDelete() {
if (confirm("Are you sure to delete?"))
return true;
else
return false;
and GridView is like below:
<asp:CommandField HeaderText="Delete" ShowDeleteButton="True" />
Here I want to call the JavaScript function when user clicking the Delete in the GridView Command Field.
How to call this?
Assuming you want to keep using your CommandField, you could do this programmatically using your GridView's OnRowDataBound event.
Specify the event handler for the RowDataBound event in your GridView declaration:
<asp:GridView ID="gv" runat="server" OnRowDataBound="gv_RowDataBound"....
Then in your event handler (code-behind) find your button (here I'm assuming ImageButton, though this depends on your ButtonType property in your CommandField) and add JavaScript to its OnClientClick property.
protected void gv_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
((ImageButton)e.Row.Cells[cell].Controls[ctrl]).OnClientClick = "return confirm('Are you sure you want to delete?');"; // add any JS you want here
}
}
In the above example, cell refers to the column index of your CommandField and ctrl refers to the control index (Delete button) within the cell you're referencing.
You better avoid ask the confirmation for deletion on the server side, capture the user final decision using javascript then go to the server side to execute your logic. CommandField will not be the best solution here.
JS:
<script type="text/javascript">
function DeleteConfirm() {
if (confirm("Are you sure you want to delete this customer from excluded customer list ?")) {
return true;
}
return false;
}
</script>
HTML:
<asp:TemplateField HeaderText=" ">
<ItemTemplate>
<asp:LinkButton ID="lnk_RemoveFromlist" runat="server" Text="Delete"
CommandName="Delete" OnCommand="Delete_Command" CommandArgument='<%# Eval("ID").ToString()' OnClientClick='return DeleteConfirm()'></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
Code:
protected void Remove_Command(object sender, CommandEventArgs e)
{
//Implement your Delete Logic
}
for cancel button have command name as "cancel" and for delete button "delete" , check
if(e.CommandName == "delete")
{
//script to delete();
}
else if(e.commandName == "cancel")
{
//close with some script;
}
To call javascript function in codebehind,
Page.ClientScript.RegisterStartupScript(this.GetType(), "Call my function","loadPopupBox();", true);
In general you have to specify OnClientClick="return confirm('Are you sure you want to delete ?');" but that doesn't work with CommandField better use TemplateField, this explains better http://davesquared.net/2007/10/confirm-delete-for-gridview.html
you can use OnClientclick event of button to call the function.For example
<asp:button id="btndelete" runat="server" Text="delete" Onclientclick="if(!ConfirmOnDelete())return false;"/>
HTML:
<asp:GridView ID="GridView1" runat="server" OnRowDeleting="gv1_RowDeleting">
<Columns>
<asp:TemplateField HeaderText="Delete">
<ItemTemplate>
<asp:CommandField ShowDeleteButton="true" HeaderText="delete" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
CODE:
protected void gv1_RowDeleting (object sender, GridViewDeleteEventArgs e)
{
GridView1.Attributes.Add("OnClick", "return confirm('Really wanna delete?');");
// implement your delete logic
Response.Write("<script>alert("Delete Successful");</script>");
}
This will Call Javascript function when we will click on "Delete" Command Field in Gridview and Response.write function will give an alert that data has been deleted. You can add whwtever function you want to execute in this function.
use start up script
ScriptManager.RegisterStartupScript(Page, this.GetType(), "ConfirmOnDelete", "ConfirmOnDelete();", true);
or you can also use onclientclick as well

dynamically add a link button in gridview template field at run time together a label control

I have a gridview in my form. I am working with RowDataBound event to the grid. Now I have a template field inside columns of the gridview. A label has been taken inside template field. I want to add a link to this label on RowDataBound event at runtime, but .System.Web.UI.WebControls.LinkButton is showing instead of link button.
How do I add a link button with label text in the grid view?
Just add a linkbutton inside your templatefield
<asp:GridView runat="server" ID="gridView">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton runat="server" ID="lnkTest"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Then in your rowdatabound event you can find it and do whatever you want
void gridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
Entity entity = e.Row.DataItem as Entity;
LinkButton lnkTest = e.Row.FindControl("lnkTest") as LinkButton;
lnkTest.CommandArgument = entity.ID.ToString();
lnkTest.Text = entity.Name;
}
}
You can then subscribe to gridview Command event and correct CommandArgument will be passed when clicking by linkbutton.
Hope this helps.

Pass GridView Template Field <asp:LinkButton control data to javascript function in my .aspx page

I have a GridView Template field containing an ASP:Label field which has a unique reference number per Row. I also have an open Javascript function assigned to that control which opens a URL in a new window and displays the document of the same reference number.
I don;t know how to obtain the reference number when the user clicks the LinkButton on a particular row, and pass it to my Javascript function before the window opens.
Code:
enter code here
function openPreview()
{
var url = "quotereport.aspx?view=esq&&ref=REFNUMBER"; window.open(url);
}
<asp:TemplateField HeaderText="" ShowHeader="False">
<ItemTemplate>
<asp:LinkButton ID="lbNewWindow" runat="server" OnClientClick="openPreview ()">Window</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
Any help would be much appreciated.
You will have to add RowDataBound event to the grid. In RowDataBound event every row that is created is accessible with data. Bind javascript to link button instead of html as you did and pass Reference number to the javascript function from RowDataBound event.
protected void gvListing_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
System.Web.UI.WebControls.LinkButton lbNewWindow= new System.Web.UI.WebControls.LinkButton();
lbNewWindow = (System.Web.UI.WebControls.LinkButton)e.Row.FindControl("lbNewWindow");
if (lbNewWindow!= null)
{
string YourRefNumber = DataBinder.Eval("e.Row.DataItem", "ColumnNameInDataSource").ToString();
lbNewWindow.Attributes.Add("onclick","openPreview('"+ YourRefNumber + "')");
}
}
}

ASP:Imagebutton fail to post back in gridview

<asp:GridView ID="gv1" runat="server" Width="100%" DataSourceID="ods1" AutoGenerateColumns="false"
DataKeyNames="FileID" HeaderStyle-Height="20px">
<Columns>
<asp:TemplateField ItemStyle-Width="25px" ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:ImageButton ID="imgMimeType" runat="server" CommandName="download" />
</ItemTemplate>
...
I have defined my image button as above, but for some reason row command fails to fire off when I click the button.
Strangely, linkbutton in another column works just fine.
How do I make it so that image button will fire off post back?
Row bind
Image Button imb = e.Row.FindControl("imgMimeType") as ImageButton;
if (imb != null)
{
imb.CommandArgument = file.FileID.ToString();
imb.AlternateText = imb.ToolTip = file.MimeType;
if (file.MimeType.Contains("zip"))
{
imb.ImageUrl = "~/Images/mimetypes/zip-icon.png";
}
...
Row command code
public void gv1_RowCommand(object sender, GridViewCommandEventArgs e)
{
switch (e.CommandName.ToLower())
{
case "download":
...
Try changing the imagebutton to a linkbutton temporarily just to see if it works. It's been a little since I've worked with asp.net but I remember running into an issue where events were not working on ImageButtons missing their images on certain browsers only. Does your ImageButton have an image set?
Add CausesValidation="False" to the imagebutton.
That worked for me.

Categories