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
Related
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...
}
}
I am making a web site in visual studio 2012, using asp.net, c#.
I created a grid view, which is taking data from my sql server, and created a button field which is bound to id_p, which is one of the collumns taken from a database. I am trying to get the data of the id_p for the row in which the button was clicked.
<asp:ButtonField ButtonType="Button" DataTextField="id_p"
DataTextFormatString="Stavi u košaricu" Text="Button1" />
What I need is not the selected row, only the id_p value, so how could I do that, please?
You need to handle the OnRowCommand Event on the gridview as so:
<asp:GridView ID="GridView1" runat="server" OnRowCommand="GridView_RowCommand"
And create a ItemTemplateField to display a regular <asp:button> instead of using the ButtonField column:
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="btn" runat="server"
CommandName="Something" CommandArgument='<%#Eval("id_p") %>'
Text="Stavi u košaricu" />
</ItemTemplate>
</asp:TemplateField>
Now you handle the RowCommand Event:
protected void GridView_RowCommand(Object sender, GridViewCommandEventArgs e)
{
string m_id = e.CommandArgument.ToString();
if (e.CommandName == "Something")
{
//do something with m_id
}
}
I have a GridView inside of a UpdatePanel. In a template field is a button I use for marking items. Functionally, this works fine, but the button always triggers a full page postback instead of a partial postback. How do I get the button to trigger a partial postback?
<asp:ScriptManager ID="ContentScriptManager" runat="server" />
<asp:UpdatePanel ID="ContentUpdatePanel" runat="server" ChildrenAsTriggers="true">
<ContentTemplate>
<asp:GridView ID="OrderGrid" runat="server" AllowPaging="false" AllowSorting="false"
AutoGenerateColumns="false">
<Columns>
<asp:TemplateField HeaderText="">
<ItemTemplate>
<asp:LinkButton ID="MarkAsCompleteButton" runat="server" Text="MarkAsComplete"
CommandName="MarkAsComplete" CommandArgument='<%# Eval("Id") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Name" HeaderText="Name" />
<asp:BoundField DataField="LoadDate" HeaderText="Load Date" />
<asp:BoundField DataField="EmployeeCutOffDate" HeaderText="Cut Off Date" />
<asp:BoundField DataField="IsComplete" HeaderText="Is Completed" />
</Columns>
</asp:GridView>
</ContentTemplate>
</asp:UpdatePanel>
You need to register each and every LinkButton as an AsyncPostBackTrigger. After each row is bound in your GridView, you'll need to search for the LinkButton and register it through code-behind as follows:
protected void OrderGrid_RowDataBound(object sender, GridViewRowEventArgs e)
{
LinkButton lb = e.Row.FindControl("MarkAsCompleteButton") as LinkButton;
ScriptManager.GetCurrent(this).RegisterAsyncPostBackControl(lb);
}
This also requires that ClientIDMode="AutoID" be set for the LinkButton, as mentioned here (thanks to Răzvan Panda for pointing this out).
It's probably not advised but you can make everything on the GridView work asynchronously by excluding the EventName on the AsyncPostBackTrigger so e.g.
<Triggers>
<asp:AsyncPostBackTrigger ControlID="OrderGrid" />
</Triggers>
This will make the RowCommand event and any other event on the GridView fire asynchronously. Note as well that when you make ClientIDMode="Static" on the GridView it will cause a full postback.
My grid view is in conditional mode.
protected void gvAgendamentoExclui_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow) {
LinkButton lnk = e.Row.FindControl("LinkButton2") as LinkButton;
AsyncPostBackTrigger trigger = new AsyncPostBackTrigger();
trigger.ControlID = lnk.UniqueID;
trigger.EventName = "Click";
UpdatePanel2.Triggers.Add(trigger);
}
}
And in the click event of the linkbutton I put:
protected void LinkButton2_Click(object sender, EventArgs e)
{
UpdatePanel2.Update();
}
Put the following element inside system.web element in web.config file
<xhtmlConformance mode="Transitional"/>
MSDN specifies that the UpdatePanel.ChildrenAsTriggers property "[g]ets or sets a value that indicates whether postbacks from immediate child controls of an UpdatePanel control update the panel's content" (see http://msdn.microsoft.com/en-us/library/system.web.ui.updatepanel.childrenastriggers.aspx).
Since your LinkButton does not appear to be an "immediate child control," then I would recommend configuring your LinkButton as an explicit AsyncPostBackTrigger.
Below your </ContentTemplate> tag, try adding this:
<Triggers>
<asp:AsyncPostBackTrigger ControlID="MarkAsCompleteButton" EventName="Click" />
</Triggers>
I had an issue where I had one form working fine (page1), another doing whole post backs (page2). Turned out when I made the 2nd page, I had done a bit too much cut/paste, and it still had a javascript call in the form definition.
< form id="form1" runat="server" onsubmit="return checkstuff();">
But checkstuff was not defined in page 2.
deleted the onsubmit, and the partial posts started working.
In the working page - page 1, checkstuff was defined, but was just a stub, which did nothing more than return true. Just for grins, I put an alert in checkstuff, and sure enough, it is called for all submits, partial or not. And, if I changed the stub to just return false, nothing happened at all.
Point in all this, the javascript is still exercised, as if a full page is being submitted. So double check your client side scripts.
this may be old but my solution was to put an update panel inside the itemTemplate and one outside the gridview as well.
the trigger should be the gridview and the outside trigger should be the gridview and PageIndexChanging. Try that.
You need to register each controls for each RowState.
1: Register your controls for RowState = Alternate and Normal)
2: Register your controls for RowState = Edit
3: ...
ASPX:
<asp:TemplateField HeaderText="">
<ItemTemplate>
<asp:LinkButton runat="server" ID="Btn1"
CommandName="Edit" CommandArgument='<%# Container.DataItemIndex + ";" + Eval("idinterlocuteur") %>'><i class="fa fa-pencil-square-o"></i></asp:LinkButton>
</ItemTemplate>
<EditItemTemplate>
<asp:LinkButton ID="Btn2" runat="server" CommandName="Update" CommandArgument='<%# Container.DataItemIndex + ";" + Eval("idinterlocuteur") %>'><i class="fa fa-check"></i></asp:LinkButton>
</EditItemTemplate>
</asp:TemplateField>
Code behind :
protected void GridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow
&& (e.Row.RowState == DataControlRowState.Normal
|| e.Row.RowState == DataControlRowState.Alternate))
{
LinkButton Btn1 = e.Row.FindControl("Btn1 ") as LinkButton;
ScriptManager.GetCurrent(this.Parent.Page).RegisterAsyncPostBackControl(Btn1 );
}
if (e.Row.RowType == DataControlRowType.DataRow
&& e.Row.RowState == DataControlRowState.Edit)
{
LinkButton Btn2 = e.Row.FindControl("Btn2 ") as LinkButton;
ScriptManager.GetCurrent(this.Parent.Page).RegisterAsyncPostBackControl(Btn2 );
}
}
I have a GridView :
<asp:GridView ID="GridView1" runat="server" AllowPaging="True" GridLines="None"
HorizontalAlign="Left" AutoGenerateColumns="False"
DataSourceID="SqlDataSource1" onrowcommand="GridView1_RowCommand1">
<HeaderStyle HorizontalAlign="Left" />
<Columns>
<asp:TemplateField HeaderStyle-Width="150">
<HeaderTemplate>
<b>Downloads</b>
</HeaderTemplate>
<ItemTemplate>
<!-- <asp:HyperLink ID="hyperlinkDownload" runat="server" NavigateUrl="" >Download
MP3</asp:HyperLink> -->
<asp:LinkButton CommandName="download"
CommandArgument='<%# Eval("Name") %>' runat="server">Download MP3</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</asp:GridView>
I want to query the value of a particular field in a DB and if it's true, display the LinkButton. if false, I want the linkButton not to be displayed.
is there a way to access the GridView programmatically and make visible certain of its columns or manipulate its items ?
help.
You can do this by adding a handler to the RowDataBound event. Add an event handler along this lines of this in your code behind:
protected void myGrid_RowDataBound(Object sender, GridViewRowEventArgs e)
{
var data = e.Row.DataItem as DataRowView;
if (data != null)
{
var lbtDownload = e.Row.FindControl("lbtDownload");
lbtDownload.Visible = (bool) data.Row["HasFileForDownload"];
}
}
In your markup, attach the event handler to the grid:
<asp:GridView OnRowDataBound="myGrid_RowDataBound" ...>
You will also need to assign an id to the LinkButton, matching the one that you are search for using the FindControl() method in the event handler.
Disclaimer: I am on currently a Linux machine with no chance of testing this. Please report any bugs in the code - feel free to correct them if you have editor rights.
Yes there is.
1) You need to subscribe the RowDataBound event.
2) Give the LinkButton an ID.
3) Insert in codebehind
protected void GridView1_RowDataBound(Object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow)
{
LinkButton _bt = e.Row.FindControl("ID") as LinkButton;
if(_bt != null)
{
// have a look at the e.row.DataItem and try to get the value of your desired visibility property
_bt.Visible = true;
}
}
}
4) If this does not work with accessing the DataItem, start thinking about a LinqDataSource.
I want to fetch the DataKey of the Selected Row of GridView on button click.
I would Personal do it in a Template Field Like so:
<asp:TemplateField>
<ItemTemplate>
//EDIT: after a comment it is suggested that you pass the RowIndex as the command argument which would provide access to the entire row
<asp:LinkButton ID="btnCopy" runat="server"CausesValidation="False"CommandName="MyCommandButton"CommandArgument='<%# Eval("MyDataKeyOrWhateverIWanteverIWantFromTheBindingSource")%>'>
</ItemTemplate>
</asp:TemplateField>
CodeBehind
protect void MyCommandButton(Object sender,CommandArgument e)
{
int DataKeyOrPK=int32.Parse(e.CommandArgument.ToString());
}
You other option would be:
<asp:gridview id="myGrid" runat="server"
width=100% datakeynames="Myid"
autogeneratecolumns=false
onSelectedIndexChanged="MyEvent">
<asp:templatefield headertext="Choose your dream home">
<itemtemplate>
<asp:linkbutton runat="server" commandname="select" text='<%# Eval ( "Whatever" ) %>' />
</itemtemplate>
</asp:templatefield>
Note the commandname="select" above.
Data-bound controls recognize certain command names and automatically raise and handle the appropriate events for the control. The following command names are recognized:
Cancel, Delete, Edit, Insert, New, Page, Select, Sort and Update. Reference
Codebehind
private void MyEvent(Object sender, EventArgs e)
{
string id = myGrid.SelectedDataKey.Value.ToString();
}
Use the SelectedDataKey property of the GridView:
DataKey currentKey = myGridView.SelectedDataKey;