I have a GridView inside an UpdatePanel which fires the RowCommand event. While firing the RowCommand event i assign the e.CommandArgument value to a label but it does not show the effect. I set breakpoint over the event during execuation it set the label text property but after getting out of the event, The label lost its value and went to its previous text. I stored the value in ViewState and Session but still it did not work. Below is my code.
The GridView1_RowCommand event here want to assign value to lblValue which is the problem
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Delete")
{
lblValue.Text = e.CommandArgument.ToString();
}
}
Here i want to delete the record from the database through the label value
protected void Button2_Click(object sender, EventArgs e)
{
Int32 id = Convert.ToInt32(lblValue.Text);
conn.RegionalBusinessUnits.Remove(conn.RegionalBusinessUnits.Where(rbu => rbu.Id == id).FirstOrDefault());
conn.SaveChanges();
}
This is the markup
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<div class="BoxStyle" >
<div class="header"><asp:HyperLink ID="hlBack" runat="server"><img src="../images/back-icon.png" alt="Go Back" height="20" width="20" style="vertical-align: middle; text-align: center; cursor: pointer;" /></asp:HyperLink> Regional Department Unit List</div>
<div id="myModal" class="reveal-modal">
<h1>Delete</h1>
<p>This will guide you through the delete process</p>
<asp:Label ID="lblValue" runat="server" Text="Label"></asp:Label>
<p><asp:Button ID="Button2" runat="server" Text="Button" OnClick="Button2_Click" /></p>
<a class="close-reveal-modal">×</a>
</div>
<div class="contents">
<center>
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" />
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataSourceID="RBUEntityDataSource" CssClass="gridview" OnRowCommand="GridView1_RowCommand" EnableViewState="False">
<Columns>
<asp:BoundField DataField="Id" HeaderText="Id" ReadOnly="True" SortExpression="Id" />
<asp:BoundField DataField="Region" HeaderText="Region" ReadOnly="True" SortExpression="Region" />
<asp:TemplateField HeaderText="Update">
<ItemTemplate>
<asp:LinkButton ID="lbUpdate" runat="server" CommandName="Update" OnClick="lbUpdate_Click">Update</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Delete">
<ItemTemplate>
<asp:LinkButton ID="lbDelete" class="big-link" data-reveal-id="myModal" runat="server" CommandName="Delete" CommandArgument='<%# Eval("Id") %>' OnClick="lbDelete_Click">Delete</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:EntityDataSource ID="RBUEntityDataSource" runat="server" ConnectionString="name=ChemonicsDBEntities" DefaultContainerName="ChemonicsDBEntities" EnableFlattening="False" EntitySetName="RegionalBusinessUnits" Select="it.[Id], it.[Region]" OrderBy="it.[Id] asc" Where="it.[DeletedBy] = 0">
</asp:EntityDataSource>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="Button2" EventName="Click" />
</Triggers>
</asp:UpdatePanel>
</center>
</div>
<div class="bottom"></div>
</div>
lblValue isn't being updated as it is outside UpdatePanel1. If you move your UpdatePanel1 with ContentTemplate up to directly under the ScriptManager, it should work. Be sure to also put the
</ContentTemplate>
</asp:UpdatePanel>
at the very bottom.
You can then remove the Trigger and change the UpdatePanel "UpdateMode" to "Always"
<asp:GridView runat="server" ID="gvDocuments" AutoGenerateColumns="false"
AllowPaging="true" PageSize="10" DataKeyNames="DocumentID">
<Columns>
<asp:TemplateField HeaderText="Action">
<ItemTemplate>
<asp:Button ID="btnDocumentViewAttachmentInGrid" runat="server" Text="View Attachment" CommandName="ViewAttachment" CausesValidation="false" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
My button click I was trying to stream a file to the client, but got the error "Microsoft JScript runtime error: Sys.WebForms.PageRequestManagerParserErrorException: The message received from the server could not be parsed." since I was on an update panel. I tried registering the datagridview for postback, nothing worked. Finally, in the code, I tried this:
Protected Sub gvDocuments_RowCreated(sender As Object, e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles gvDocuments.RowCreated
Try
If (e.Row.RowType = DataControlRowType.DataRow) Then
Dim btnDocumentViewAttachmentInGrid As Button = e.Row.FindControl("btnDocumentViewAttachmentInGrid")
btnDocumentViewAttachmentInGrid.CommandArgument = e.Row.RowIndex.ToString()
ScriptManager1.RegisterPostBackControl(btnDocumentViewAttachmentInGrid)
End If
Catch ex As Exception
'handle error here
End Try
End Sub
...and then I could stream the file like this:
Protected Sub gvDocuments_RowCommand(sender As Object, e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles gvDocuments.RowCommand
Try
If e.CommandName = "Select" Then
gvDocuments.SelectedIndex = e.CommandArgument
ElseIf e.CommandName = "ViewAttachment" Then
Dim iDocumentID As Int64 = gvDocuments.DataKeys(e.CommandArgument).Value
Dim oRows() As DataRow = dtDocs.Select("DocumentID = " & iDocumentID.ToString())
If oRows.Length > 0 Then
Dim oRow As DataRow = oRows(0)
Dim strFileName As String = oRow("NetworkPath").ToString()
Dim strJustTheName As String = oRow("DocumentID").ToString() & "." & oRow("FileNameExtension").ToString()
strFileName &= strJustTheName
Response.Clear()
Response.ClearHeaders()
Response.ContentType = "application/octet-stream"
Response.AddHeader("Content-Disposition", String.Format("attachment;filename=""{0}""", strJustTheName))
Response.TransmitFile(strFileName)
Response.Flush()
Response.End()
End If
End If
Catch ex As Exception
'handle error
End Try
End Sub
...and BOOM goes the dynamite, totally works! :)
In this case not, but may be you add control to GridView with same ID, You must have unique ID.
I had this problem, and it worked
on Page_Load must be rebinding the gridview like this
If (!Page.IsPostBack)
{
bindhere()
}
Related
Hi all I have a simpe ASP button inside a grid. But the onclick event doesn't seem to fire. Where did I go wrong?
Here's the first line of my aspx page.
<%# Page Title="Trainer Data" Language="vb" AutoEventWireup="false" MasterPageFile="~/Site.Master" CodeFile="TrainerData.aspx.vb" Inherits="TrainerData"%>
And the button inside my gridview..
<asp:GridView ID ="gvExecSummary" runat="server" CssClass="gridview" AllowSorting="false" AllowPaging="false" AutoGenerateColumns="false" Width="98%" >
<RowStyle Height="22px" />
<AlternatingRowStyle Height="22px" CssClass="bg" BackColor="LightGray"/>
<HeaderStyle Height="22px" BackColor="#4b6c9e" Font-Bold="true"/>
<Columns>
<asp:TemplateField HeaderStyle-HorizontalAlign="Left" HeaderStyle-Width="5%" HeaderText="Action">
<ItemTemplate>
<asp:Button ID="btnExecutiveGenerate" runat="server" Text="Generate" OnClientClick="btnExecutiveGenerate_Click" />
</ItemTemplate>
</asp:TemplateField>
P.S. I tried even onclick but it doesn't work either.
EDIT: My code for server side.
Protected Sub btnExecutiveGenerate_Click(sender As Object, e As EventArgs)
Dim gvrow As GridViewRow = CType(CType(sender, Control).Parent.Parent, GridViewRow)
Dim lblSchoolId As System.Web.UI.WebControls.Label = gvrow.FindControl("lblSchoolMasterID")
Dim lblFacultyId As System.Web.UI.WebControls.Label = gvrow.FindControl("lblFacultyMasterID")
Dim btnExecutiveGenerate As System.Web.UI.WebControls.Button = gvrow.FindControl("btnExecutiveGenerate")
PDF_Creation_Executive(Val(lblSchoolId.Text), Val(lblFacultyId.Text))
End Sub
Use Command Argumnet,
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="AddButton" runat="server"
CommandName="AddToCart"
CommandArgument="<%# CType(Container,GridViewRow).RowIndex %>"
Text="Add to Cart" />
</ItemTemplate>
</asp:TemplateField>
add code page side
Protected Sub GridView1_RowCommand(ByVal sender As Object, _ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs)
If (e.CommandName = "AddToCart") Then
' Retrieve the row index stored in the CommandArgument property.
Dim index As Integer = Convert.ToInt32(e.CommandArgument)
' Retrieve the row that contains the button
' from the Rows collection.
Dim row As GridViewRow = GridView1.Rows(index)
' Add code here to add the item to the shopping cart.
End If
End Sub
You need to handle the button click event of Gridview in RowCommand event
NOTE: Please see the CommandName & CommandArgument properties added to the button.
<asp:GridView ID ="gvExecSummary" runat="server" CssClass="gridview" AllowSorting="false" AllowPaging="false" AutoGenerateColumns="false" Width="98%" >
<RowStyle Height="22px" OnRowCommand="gvExecSummary_RowCommand" />
<AlternatingRowStyle Height="22px" CssClass="bg" BackColor="LightGray"/>
<HeaderStyle Height="22px" BackColor="#4b6c9e" Font-Bold="true"/>
<Columns>
<asp:TemplateField HeaderStyle-HorizontalAlign="Left" HeaderStyle-Width="5%" HeaderText="Action">
<ItemTemplate>
<asp:Button ID="btnExecutiveGenerate" runat="server" Text="Generate" CommandName="GenerateExecutive" CommandArgument="<%#((GridViewRow)Container).RowIndex %>" />
</ItemTemplate>
</asp:TemplateField>
And and RowCommand event will be..
protected void gvExecSummary_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "GenerateExecutive")
{
// button click code goes here
}
}
change OnClientClick event to OnClick if btnExecutiveGenerate_Click is vb.net event handler
<asp:Button ID="btnExecutiveGenerate" runat="server" Text="Generate"
OnClick="btnExecutiveGenerate_Click"/>
OnClientClick event use to execute client-side script, if you have given OnClientClick event with OnClick event, then if OnClientClick return true only it will call OnClick event.
so make sure you are returning true or false from OnClientClick event if you using it.
note that if you are loading data in page laod, do as below
Sub Page_Load
If Not IsPostBack
LoadGridViewData()
End If
End Sub
This may help someone, but I was experiencing edit buttons not firing the event within rows (and not footer).
The cause was a gridview containing a label, which had the same ID as one elsewhere on the page.
Seemingly this did not cause problems for the footer row, which did not contain any such labels.
I hope this helps someone.
I'm trying to attach a Javascript function to confirm a delete of a record in a GridView. I know this can be done more easily using an asp:LinkButton in an ItemTemplate but I am trying to attach it to a CommandField - ShowDeleteButton button.
I've tried to follow this tutorial: display-confirmation-message-on-gridview-deleting
I am new to GridView and my implementation is in VB.Net not C#. Here is the code where I try to inject the Javascript function and I cannot figure out how/why my row.cell references are wrong:
Protected Sub GridView1_RowDataBound(ByVal sender As Object, ByVal e As GridViewRowEventArgs) _
Handles GridView1.RowDataBound
If e.Row.RowState <> DataControlRowState.Edit Then
If e.Row.RowType = DataControlRowType.DataRow Then 'check for RowType DataRow
Dim id As String = e.Row.Cells(0).Text 'get the position to be deleted
Try
'cast the ShowDeleteButton link to linkbutton
Dim lb As LinkButton
Dim i As Integer = 4 'cell we want in the row (relative to 0 not 1)
lb = DirectCast(e.Row.Cells(i).Controls(2), LinkButton)
If lb IsNot Nothing Then 'attach the JavaScript function with the ID as the parameter
lb.Attributes.Add("onclick", "return ConfirmOnDelete('" & id & "');")
End If
Catch ex As Exception
End Try
End If
End If
Here is my GridView markup snippet (a bit more busy than all bound columns; I count 3 TemplateField items after the first and only BoundField to arrive at the 5th column hence i = 4 above):
<Columns>
<asp:BoundField DataField="PositionID" HeaderText="ID" ReadOnly="true" />
<asp:TemplateField HeaderText="PositionTitle">
<ItemTemplate>
<%# Eval("PositionTitle")%>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox runat="server" ID="txtPositionTitle" Text='<%# Eval("PositionTitle")%>' />
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Incumbent">
<ItemTemplate>
<asp:Label ID="lblUser" runat="server" Text='<%# Eval("Incumbent")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:Label ID="lblUser" runat="server" Text='<%# Eval("Incumbent")%>' Visible = "false"></asp:Label>
<asp:DropDownList Width="100%" runat="server"
id="ddlUsers" AutoPostBack="true"
DataTextField="FullName" DataValueField="UserID"
OnSelectedIndexChanged="ddlUsers_SelectedIndexChanged">
</asp:DropDownList>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Backup">
<ItemTemplate>
<%#Eval("Backup")%>
</ItemTemplate>
<EditItemTemplate>
<asp:Label ID="lblBackup" runat="server" Text='<%# Eval("Backup")%>' Visible = "false"></asp:Label>
<asp:DropDownList Width="100%" runat="server"
id="ddlUsersBackup" AutoPostBack="true"
DataTextField="FullName" DataValueField="UserID"
OnSelectedIndexChanged="ddlUsersBackup_SelectedIndexChanged">
</asp:DropDownList>
</EditItemTemplate>
</asp:TemplateField>
<asp:CommandField ButtonType="Button" ControlStyle-CssClass="coolbutton"
ShowEditButton="true"
ShowDeleteButton="true"
ShowCancelButton="true" />
When I ignore the error, the Command buttons are indeed in the 5th column:
The error I get without the Try/Catch is:
If you haven't figured out yet, your problem is in ButtonType="Button" here:
<asp:CommandField ButtonType="Button" ControlStyle-CssClass="coolbutton"
ShowEditButton="true"
ShowDeleteButton="true"
ShowCancelButton="true" />
You can't cast a command button to link button. You have to define it as Link button (please refer to MSDN for details of CommandField class). This is working:
<asp:CommandField ButtonType="Link" ControlStyle-CssClass="coolbutton"
ShowEditButton="true"
ShowDeleteButton="true"
ShowCancelButton="true" />
Just call a javascript function on onclientclick event and ask for confirmation. If it returns true then you can call the server side code to delete.
Below is the code for explanation
<asp:LinkButton ID="lbDelete" runat="server" OnClick="lbDelete_Click" OnClientClick="return fnConfirm();"> Delete</asp:LinkButton>
And below is the javascript function:
<script type="text/javascript">
function fnConfirm() {
if (confirm("The item will be deleted. Are you sure want to continue?") == true)
return true;
else
return false;
}
You can check the detailed article with source code in the below link
http://www.dotnetpickles.com/2013/03/how-to-show-confirm-message-while.html
Thanks
I found lots of C# answers.
aspx page:
<asp:CommandField DeleteText="Delete" ShowDeleteButton="true"
ButtonType="Button" />
aspx.vb page:
Protected Sub GridView1_RowDataBound(sender As Object, _
e As GridViewRowEventArgs) _
Handles GridView1.RowDataBound
If e.Row.RowType = DataControlRowType.DataRow Then
If (e.Row.RowState <> DataControlRowState.Edit) Then
Dim oButton As Button
oButton = CType(e.Row.Cells(14).Controls(0), Button)
oButton.OnClientClick = _
"if (confirm(""Are you sure you wish to Delete?"") == false) return;"
End If
End If
End Sub
I would like to retrieve a row from the gridview by clicking on ImageButton (Booking):
here is the code of my grid view:
<asp:GridView ID="GridView1" runat="server" Height="150px" Width="284px"
CssClass="tb" AutoGenerateColumns="False" DataSourceID="SqlDataSource1">
<Columns>
<asp:TemplateField HeaderText=" Booking">
<ItemTemplate>
<asp:ImageButton ID="booking" runat="server" HeaderText="Booking" ImageUrl="booking_icon.ico" PostBackUrl="form.aspx"/>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Trade" HeaderText="Trade" SortExpression="Trade" />
<asp:BoundField DataField="CARRIER" HeaderText="CARRIER"
SortExpression="CARRIER" />
</Columns>
</asp:GridView>
The textbox of the form.aspx page that should be filed from the gridview row:
<asp:TextBox ID="trade" runat="server" CssClass="input , focus"></asp:TextBox>
<asp:TextBox ID="carrier" runat="server" CssClass="input , focus"></asp:TextBox>
Add GridView RowCommand event and command argument for image button where you can pass an id or something to determine the current row.
<asp:GridView onrowcommand="gvRowCommand" ID="GridView1" runat="server" Height="150px" Width="284px"
CssClass="tb" AutoGenerateColumns="False" DataSourceID="SqlDataSource1">
<ItemTemplate>
<asp:ImageButton CommandArgument='<%# Eval("SomeId") %>' ID="booking" runat="server" HeaderText="Booking" ImageUrl="booking_icon.ico" />
</ItemTemplate>
C#
protected void gvRowCommand(object sender, GridViewCommandEventArgs e)
{
var someId = e.CommandArgument;
}
VB.Net
Protected Sub gvRowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles gv.RowCommand
Dim someId As Integer = Convert.ToInt32(e.CommandArgument)
End Sub
You can refer msdn for more : http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.rowcommand.aspx
We have a GridView that contains 2 "Select" buttons for each row that is displayed in the GridView.
We would like to know if there is a way to find out which of the 2 buttons was clicked on by using the SelectedIndexChanged handler.
This coding shows the buttons we have:
<asp:UpdatePanel
ID="UpdatePanelParentsSummary"
runat="server"
UpdateMode="Conditional">
<ContentTemplate>
<p>Parent Search:
<asp:TextBox
ID="TextBoxSearch"
runat="server"
Width="207px"
Text="ALL"> </asp:TextBox>
<asp:Button
ID="ButtonSearch"
runat="server"
Text="Search" />
<asp:Button
ID="ButtonSearchAll"
runat="server"
Text="Show ALL Parents" />
<br />
</p>
<asp:GridView
ID="GridViewParentsSummary"
runat="server"
AllowPaging="True"
AllowSorting="True"
AutoGenerateColumns="False"
DataKeyNames="ID"
>
<Columns>
<asp:BoundField
DataField="ID"
HeaderText="ID"
SortExpression="ID" InsertVisible="False" ReadOnly="True" Visible="False" />
<asp:BoundField
DataField="FatherName"
HeaderText="FatherName"
SortExpression="FatherName" />
<asp:BoundField DataField="MotherName" HeaderText="MotherName"
SortExpression="MotherName" />
<asp:ButtonField
ButtonType="Button"
CommandName="Select"
Text="Select Details" />
<asp:ButtonField
ButtonType="Button"
CommandName="Select"
Text="New Person To Release Child" />
</Columns>
</asp:GridView>
</ContentTemplate>
</asp:UpdatePanel>
This is the code in the SelectedIndexChanged handler:
Protected Sub GridViewParentsSummary_SelectedIndexChanged(sender As Object, e As EventArgs) Handles GridViewParentsSummary.SelectedIndexChanged
IntParentsID = GridViewParentsSummary.DataKeys(GridViewParentsSummary.SelectedIndex).Value
Response.Redirect("AuthorizationForChildReleaseDetails.aspx")
End Sub
Ah, there is a simple solution to this problem. Your sender is the button clicked. Just try something like:
ButtonField buttonClicked = sender as ButtonField;
if (buttonClicked != null) {
String commandName = buttonClicked.CommandName;
if (commandName.equals("Command1") {
... do something awesome ...
} else if (commandName.equals("Command2")) {
... do something less awesome ...
}
}
I don't think you can differentiate between the source at the GridView event level because it is an event raised by the GridView at that point which is masking the lower level event. You can, however, implement a row level handler to identify which button was used to raise the event and set it up somewhere for use in the gridview event.
protected void GridView_RowCommand(object sender, CommandEventArgs e)
{
e.CommandArgument ....contains the argument name
....
}
I have a gridview with Template field. I add a checkbox in templatefield . Autopostback is true for checkbox .
I fill grid in Load-page and creted column dynamic .
if (!IsPostBack)
{
FillGrid();
}
I use update panel
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<SharePoint:SPGridView ID="grid" AllowSorting="true" AllowFiltering="true" CssClass="ms-listviewtable"
runat="server" AutoGenerateColumns="false">
<RowStyle CssClass="ms-alternating" Height="10px" />
<Columns>
<asp:TemplateField>
<ItemTemplate >
<asp:CheckBox ID="select" runat="server"
OnCheckedChanged="select_CheckedChanged" AutoPostBack="true" />
<input id="Display" type="hidden" runat="server" />
<input id="itemID" type="hidden" runat="server" />
<asp:Image ID="icon" runat="server" Height="10px" Visible="false" />
</ItemTemplate>
<ItemStyle Width="35px" />
</asp:TemplateField>
<asp:TemplateField >
</asp:TemplateField>
</Columns>
</SharePoint:SPGridView>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="select" EventName="OnCheckedChanged" />
</Triggers>
</asp:UpdatePanel>
but show error :A control with ID 'select' could not be found for the trigger in UpdatePanel 'UpdatePanel1'.
My problem is : When checkbox is change, page refresh
I don't want to refresh page after checkedchange!
you have to set autopostback="false" or remove autopostback property in checkbox. autopostback actully refresh the page.
So what happens if you set the autopostback property of the checkbox to false?
Also if you are actually looking to handle the onchange event of the checkbox you could wrap the grid with an UpdatePanel; the user wouldn't see a postback but you still get the flexibility of serverside event handling.
First of all you need changes templetecolumn as below
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="chkselect" runat="server" />
<input id="Display" type="hidden" runat="server" />
<input id="itemID" type="hidden" runat="server" />
<asp:Image ID="imgicon" runat="server" Height="10px" Style="display: none;" ImageUrl="~/images/arrow_left.jpg" />
</ItemTemplate>
<ItemStyle Width="35px" />
</asp:TemplateField>
Now handle itemdatabound event in server side code
Protected Sub SPGridView_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles gvBanner.RowDataBound
If e.Row.RowType = DataControlRowType.DataRow Then
Dim chkselect As CheckBox = e.Row.FindControl("chkselect")
Dim imgicon As Image = e.Row.FindControl("imgicon")
If chkselect IsNot Nothing Then
chkselect.Attributes.Add("onclick", "javascript:DoMyTask(this,'" + imgicon.ClientID + "')")
End If
End If
End Sub
Now specify JavaScript function in aspx page as below.
<script type="text/javascript" language="javascript">
function DoMyTask(obj, imgid) {
var objCheck = obj.checked;
var objimg = document.getElementById(imgid)
if (objCheck == true) {
objimg.style.display = "block";
//set more attributes over here
}
else {
objimg.style.display = "none";
//set more attributes over here
}
var count = $(":checkbox:checked").length;
alert('you have selected ' + count + ' Rows');
}
</script>
Hope this will help you...happy coding ..