Hello I have a searchbox and when I search for a record it is fine the records shows up however once I click edit on the gridview the page does a postback and all the records show back up with the first record selected for editing. How can I disable this post back or make it when I click edit all the records do not display again?
VB.CodeBehind
Protected Sub btnClear_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnClear.Click
txtSearch.text = ""
sourcegridview.DataBind()
End Sub
Protected Sub btnSearch_Click(sender As Object, e As System.EventArgs) Handles btnSearch.Click
SqlDataSource1.SelectCommand = "select * from Stg_Employee_All_Info where Name like '%" & txtSearch.Text & "%'"
SqlDataSource1.DataBind()
End Sub
Gridview Code
<asp:GridView ID="sourcegridview" runat="server" AllowPaging="True"
AutoGenerateColumns="False" BackColor="White" BorderColor="#3366CC"
BorderStyle="None" BorderWidth="1px" CellPadding="4"
DataSourceID="SqlDataSource1" Width="422px" AllowSorting="True"
DataKeyNames="Row">
<Columns>
<asp:BoundField DataField="Row" HeaderText="Row"
SortExpression="Row" ReadOnly="True" />
<asp:BoundField DataField="Name" HeaderText="Name" ReadOnly="True"
SortExpression="Name" />
<asp:BoundField DataField="Dept" HeaderText="Dept" ReadOnly="True"
SortExpression="Dept" />
<asp:TemplateField HeaderText="Hide_Bday">
<EditItemTemplate>
<asp:CheckBox ID="chkBday" runat="server" Checked='<%# Bind("Hide_Bday") %>' />
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblHideBday" runat="server" Text='<%# Eval("Hide_Bday") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Hide_Anniv">
<EditItemTemplate>
<asp:CheckBox ID="chkAnniv" runat="server"
Checked='<%# Bind("Hide_Anniv") %>' />
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblHideAnniv" runat="server" Text='<%# Eval("Hide_Anniv") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:CommandField ShowEditButton="True" />
</Columns>
<EmptyDataTemplate>
<asp:CheckBox ID="chkboxHideBday" runat="server"
Checked='<%# Eval("Hide_Bday") %>' Visible='<%# Eval("Hide_Bday") %>' />
</EmptyDataTemplate>
I populate and update the gridview with a sqldatasource which references a stored procedure
Gridview populate code
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:a_Kronos %>"
SelectCommand="SELECT [Row], [Name], [Dept], [Hide_Bday], [Hide_Anniv] FROM [Stg_Employee_All_Info]"
UpdateCommand="usp_insertoptout" UpdateCommandType="StoredProcedure">
<UpdateParameters>
<asp:Parameter Name="Hide_Bday" Type="Int32" />
<asp:Parameter Name="Hide_Anniv" Type="Int32" />
</UpdateParameters>
</asp:SqlDataSource>
The problem is when you click on search it sets the SelectCommand, but only for that single round-trip to the server. The SelectCommand is not persisted anywhere so when you are clicking "Edit", the grid goes right back to using SqlDataSource1's initial command.
Early versions of the ASP.NET GridView stored the SelectCommand text in ViewState, but that was removed for security reasons. As they put it:
For security purposes, the SqlDataSource control no longer stores commands in ViewState by default. Since it is technically possible to decode the contents of ViewState on the client, storing sensitive information about the database backend in this field could expose you to an information disclosure threat.
So instead, you will need to bind the Grid manually and find your way of persisting the SelectCommand across multiple post-backs. Here is an example using Session:
Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
SqlDataSource1.SelectCommand = If(Session("SearchSelectCommand"), "SELECT [Row], [Name], [Dept], [Hide_Bday] ...")
SqlDataSource1.DataBind()
End Sub
Protected Sub btnSearch_Click(sender As Object, e As System.EventArgs) Handles btnSearch.Click
Dim searchQuery As String = "select * from Stg_Employee_All_Info where ..."
Session("SearchSelectCommand") = searchQuery
SqlDataSource1.SelectCommand = searchQuery
SqlDataSource1.DataBind()
End Sub
Related
I have a Gridview on an ASP page bound to an SQL table. I've configured the Grid to allow Multiple updates by replacing the default Label Controls with TemplateFields using the approach described here:
Bulk Updates to Rows Bound to a GridView
Everything was working fine, until I made a change to bind the Gridview query programmatically on page load (With the aim of making the Gridview display different data depending on the user currently viewing the page) as described here:
Bind Gridview programmatically.
After making this change the page now throws the following error when the user makes changes and clicks the update button:
The GridView 'GridView1' fired event RowUpdating which wasn't handled.
Also when I try to do a single row update I get this error:
Exception Details: System.Web.HttpException: The GridView 'GridView1' fired event RowEditing which wasn't handled.
I have read many threads on similair problems but I can't seem to find a solution to my error. I don't know why dynamically binding the Gridview would cause an error in rowupdating. Appreciate any support to resolve this. Thanks.
Here's the Code:
Public Class Input
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
gvbind()
End If
End Sub
Public Sub gvbind()
Dim SqlDataSource1 As New SqlDataSource()
SqlDataSource1.ID = "SqlDataSource1"
Me.Page.Controls.Add(SqlDataSource1)
SqlDataSource1.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString
SqlDataSource1.SelectCommand = "SELECT [ID], [Project], [Description], [CAPEX], [Team] FROM [CAPEX]"
'Add Conditional Statements to change view for users/Teams
'SqlDataSource1.SelectCommand = "SELECT [ID], [Project], [Description], [CAPEX] FROM [CAPEX] where [Team] = 'Team1'"
GridView1.DataSource = SqlDataSource1
GridView1.DataBind()
End Sub
Private tableCopied As Boolean = False
Private originalDataTable As System.Data.DataTable
Protected Sub GridView1_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView1.RowDataBound
If e.Row.RowType = DataControlRowType.DataRow Then
If Not tableCopied Then
originalDataTable = CType(e.Row.DataItem, System.Data.DataRowView).Row.Table.Copy()
ViewState("originalValuesDataTable") = originalDataTable
tableCopied = True
End If
End If
End Sub
Protected Sub Up_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Up.Click
originalDataTable = CType(ViewState("originalValuesDataTable"), System.Data.DataTable)
For Each r As GridViewRow In GridView1.Rows
If IsRowModified(r) Then GridView1.UpdateRow(r.RowIndex, False)
Next
' Rebind the Grid to repopulate the original values table.
tableCopied = False
GridView1.DataBind()
End Sub
Protected Function IsRowModified(ByVal r As GridViewRow) As Boolean
Dim currentID As Integer
Dim currentProject As String
Dim currentDescription As String
Dim currentCAPEX As String
currentID = Convert.ToInt32(GridView1.DataKeys(r.RowIndex).Value)
currentProject = CType(r.FindControl("ProjectTextBox"), TextBox).Text
currentDescription = CType(r.FindControl("DescriptionTextBox"), TextBox).Text
currentCAPEX = CType(r.FindControl("CAPEXTextBox"), TextBox).Text
Dim row As System.Data.DataRow = _
originalDataTable.Select(String.Format("ID = {0}", currentID))(0)
If Not currentProject.Equals(row("Project").ToString()) Then Return True
If Not currentDescription.Equals(row("Description").ToString()) Then Return True
If Not currentCAPEX.Equals(row("CAPEX").ToString()) Then Return True
Return False
End Function
Here's the Markup:
<%# Page Title="Input" Language="vb" MasterPageFile="~/Site.Master" AutoEventWireup="false"
CodeBehind="Input.aspx.vb" Inherits="WebApplication5.Input" %>
<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<h2>
Data Entry
</h2>
<p>
Enter Inputs Here<asp:TextBox runat="server" Text='<%# Bind ("Project") %>'
id="TextBox4"></asp:TextBox>
<asp:Table ID="Entry" runat="server">
</asp:Table>
<asp:Button ID="TestButton" runat="server" Text="Test" />
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
AllowSorting="True" AllowPaging="True" datakeynames = "ID" Width="502px">
<Columns>
<asp:CommandField ShowEditButton="True" />
<asp:BoundField DataField="ID" readOnly = "true" HeaderText="ID" SortExpression="ID"/>
<asp:TemplateField HeaderText="Project" SortExpression="Project">
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("Project") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:TextBox ID="ProjectTextBox" runat="server" MaxLength="30"
Text='<%# Bind("Project") %>'></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Description" SortExpression="Description">
<EditItemTemplate>
<asp:TextBox ID="TextBox2" runat="server" Text='<%# Bind("Description") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:TextBox ID="DescriptionTextBox" runat="server" MaxLength="150"
Text='<%# Bind("Description") %>'></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="CAPEX" SortExpression="CAPEX">
<EditItemTemplate>
<asp:TextBox ID="TextBox3" runat="server" Text='<%# Bind("CAPEX") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:TextBox ID="CAPEXTextBox" runat="server" MaxLength="10"
Text='<%# Bind("CAPEX") %>'></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource2" runat="server"
ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
SelectCommand="SELECT [ID], [Project], [Description], [CAPEX] FROM [CAPEX]"
DeleteCommand="DELETE FROM [CAPEX] WHERE [ID] = #ID"
InsertCommand="INSERT INTO [CAPEX] ([ID], [Project], [Description], [CAPEX], [Team]) VALUES (#ID, #Project, #Description, #CAPEX, #Team)"
UpdateCommand="UPDATE [CAPEX] SET [Project] = #Project, [Description] = #Description, [CAPEX] = #CAPEX,[Team] = #Team WHERE [ID] = #ID">
<DeleteParameters>
<asp:Parameter Name="ID" Type="String" />
</DeleteParameters>
<InsertParameters>
<asp:Parameter Name="ID" Type="String" />
<asp:Parameter Name="Project" Type="String" />
<asp:Parameter Name="Description" Type="String" />
<asp:Parameter Name="CAPEX" Type="Decimal" />
</InsertParameters>
<UpdateParameters>
<asp:Parameter Name="Project" Type="String" />
<asp:Parameter Name="Description" Type="String" />
<asp:Parameter Name="CAPEX" Type="Decimal" />
<asp:Parameter Name="ID" Type="String" />
<asp:Parameter Name="Team" Type="String" />
</UpdateParameters>
</asp:SqlDataSource>
<asp:Button ID="Up" runat="server" Text="Up" />
<asp:SqlDataSource ID="SqlDataSource1" runat="server"></asp:SqlDataSource>
<asp:Table ID="Table1" runat="server" BorderWidth="1" BorderStyle="Solid">
</asp:Table>
</p>
You make a call in Up_Click to 'GridView1.UpdateRow()'
From the MSDN Docs:
Calling this method also raises the RowUpdated and RowUpdating events.
So all you should need to do is provide empty handlers
Adding to fnostro's answer about GridView1.UpdateRow() raising RowUpdated and RowUpdating, showing the edit button like you do:
<asp:CommandField ShowEditButton="True" />
will generate a button with CommandName="Edit". Clicking this button will raise the RowEditing event, which you also need to handle in your code.
And as a side note, since your "Update" button is outside your GridView, the CommandName property won't be responsible for automatically firing a GridView event. So not only will changing the ID from "Update" to "Up" not have any affect, but changing the CommandName wouldn't have either.
I see that SqlDataSource1 definition in codebehind lacks the UpdateCommand definition.
To be honest I always used the SqlDataSource2 approach, it'd be as easy as add DataSourceID="SqlDataSource2" and the markup would be:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
AllowSorting="True" AllowPaging="True" DataKeyNames = "ID"
DataSourceID="SqlDataSource2" Width="502px">
That way you can forget about if the gridview has to be bound in postbacks. Unless you place the gridview inside an UpdatePanel, I'd say it has to be bound, and then the If Not IsPostBack Then is incorrectly placed.
The code <asp:TextBox runat="server" Text='<%# Bind ("Project") %>' id="TextBox4"></asp:TextBox> looks placed outside of a databound control.
Within my ASP gridview, I have the following (updated to show full gridview):
<asp:GridView ID="TPAnnuity_GridView" AllowSorting="true" AllowPaging="true" Runat="server"
DataSourceID="TPAnnuity_SqlDataSource" DataKeyNames="AnnuityTotalPointsID"
AutoGenerateColumns="False" ShowFooter="true" PageSize="20">
<Columns>
<asp:TemplateField HeaderText="Company" SortExpression="CompanyName" HeaderStyle-VerticalAlign="Bottom">
<ItemTemplate>
<asp:Label ID="Label11" runat="server" Text='<%# Bind("CompanyName") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="EditACompanyID" runat="server" DataSource="<%# ddlCompanyDS %>" DataValueField="CompanyID" DataTextField="CompanyName" selectedValue='<%# Bind("CompanyID") %>'></asp:DropDownList>
</EditItemTemplate>
<FooterTemplate>
<asp:DropDownList ID="NewCompanyID" runat="server" DataSource="<%# ddlCompanyDS %>" DataValueField="CompanyID" DataTextField="CompanyName"></asp:DropDownList>
<asp:RequiredFieldValidator ID="RequiredFieldValidator11" runat="server" ControlToValidate="NewCompanyID" Display="Dynamic" ForeColor="" ErrorMessage="You must enter a value. *" Enabled="false"></asp:RequiredFieldValidator>
</FooterTemplate>
<FooterStyle Wrap="False" />
</asp:TemplateField>
</Columns>
<EmptyDataTemplate>
<br />
<i>No Commission Data to display.</i>
<br />
<br />
</EmptyDataTemplate>
</asp:GridView>
And within my back end, I have the following:
Sub TPAnnuity_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles TPAnnuity_GridView.RowCommand
If e.CommandName = "Cancel" Then
'Reset Footer Row input fields
CType(TPAnnuity_GridView.FooterRow.FindControl("NewCompanyID"), DropDownList).SelectedIndex = 0
ElseIf e.CommandName = "Insert" Then
TPAnnuity_SqlDataSource.InsertParameters.Clear()
Dim test1 As New Parameter("CompanyIDInt", TypeCode.Int32)
test1.DefaultValue = CType(TPAnnuity_GridView.FooterRow.FindControl("NewCompanyID"), DropDownList).SelectedValue
TPAnnuity_SqlDataSource.InsertParameters.Add(test1)
TPAnnuity_SqlDataSource.Insert()
ElseIf e.CommandName = "Update" Then
TPAnnuity_SqlDataSource.UpdateParameters.Clear()
Dim param1 As New Parameter("CompanyIDInt", TypeCode.Int32)
param1.DefaultValue = CType(TPAnnuity_GridView.FooterRow.FindControl("EditACompanyID"), DropDownList).SelectedValue ****THIS IS THE PROBLEM LINE****
TPAnnuity_SqlDataSource.UpdateParameters.Add(param1)
TPAnnuity_SqlDataSource.Update()
End If
End Sub
The Cancel and Insert functions work just fine, operating off of the footer. Every time hit the "Update" button, I get a NullReferenceException on the param1.Default Value = line.
Can anyone help me figure out what's going on here?
Your row should look like this:
param1.DefaultValue = CType(e.CommandSource.FindControl("EditACompanyID"), DropDownList).SelectedValue
Instead of utilizing the FooterRow, you have to use the source row. Since you passed that in with e, you can use this.
I am trying to execute an "INSERT INTO" in the HeaderRow.
The button in the HeaderRow does not trigger the RowCommand.
The gridview contains 5 columns: idt, datetime, col1, col2 and col3.
Protected Sub gvtest_RowCommand(ByVal sender As Object, ByVal e As GridViewCommandEventArgs) Handles gvtest.RowCommand
Dim txt1, txt2, txt3 as String
If e.CommandName = "insertinto" Then
Try
txt1 = DirectCast(gvtest.HeaderRow.FindControl("tbins1"), TextBox).Text
txt2 = DirectCast(gvtest.HeaderRow.FindControl("tbins2"), TextBox).Text
txt3 = DirectCast(gvtest.HeaderRow.FindControl("tbins3"), TextBox).Text
sqltest.InsertParameters("#datetime").DefaultValue = DateTime.Now()
sqltest.InsertParameters("#col1").DefaultValue = txt1
sqltest.InsertParameters("#col2").DefaultValue = txt2
sqltest.InsertParameters("#col3").DefaultValue = txt3
sqltest.Insert()
Catch ex As Exception
TextBox1.Text = "Insert: " & ex.Message
End Try
gvtest.DataBind()
End If
End Sub
default.aspx
<asp:GridView ID="gvtest"
runat="server"
DataSourceID="sqltest"
AutoGenerateColumns="False"
DataKeyNames="idt"
OnRowCommand="gvtest_RowCommand">
<Columns>
<asp:BoundField DataField="idt" HeaderText="idt" Readonly="true" SortExpression="idt" />
<asp:BoundField DataField="datetime" HeaderText="datetime" SortExpression="datetime" />
<asp:TemplateField SortExpression="col1">
<HeaderTemplate>
<asp:TextBox ID="tbins1" text="col1" runat="server" MaxLength="40" />
</HeaderTemplate>
</asp:TemplateField>
<asp:TemplateField SortExpression="col2">
<HeaderTemplate>
<asp:TextBox ID="tbins2" text="col2" runat="server" MaxLength="40" />
</HeaderTemplate>
</asp:TemplateField>
<asp:TemplateField SortExpression="col3">
<HeaderTemplate>
<asp:TextBox ID="tbins3" text="col3" runat="server" MaxLength="40" />
</HeaderTemplate>
</asp:TemplateField>
<asp:TemplateField>
<HeaderTemplate>
<asp:Button ID="btnins" CommandName="insertinto" runat="server" Text="Insert Into" OnClick="btnins_Click" />
</HeaderTemplate>
</asp:GridView>
<asp:SqlDataSource
id="sqltest"
ConnectionString="<%$ ConnectionStrings:connone %>"
SelectCommand="SELECT * FROM [test];
InsertCommand="INSERT INTO [test] datetime,col1,col2,col3 VALUES #datetime,#col1,#col2,#col3;">
</asp:SqlDataSource>
Note for brevity textboxes were omitted containing the gridview data.
You need to use a known command name, like Insert. It will not know your custom command name.
Read this:
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.buttonfield.commandname(v=vs.110).aspx
change:
<asp:Button ID="btnins" CommandName="insertinto" runat="server" Text="Insert Into" OnClick="btnins_Click" />
to:
<asp:Button ID="btnins" CommandName="Insert" runat="server" Text="Insert Into" OnClick="btnins_Click" />
GridView row command events come from the Command controls on the data rows.
You placed a button in the GridView header, you need to process the btnins.Command event
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 am trying to get a parameter for my update from the gridview but it is an ID column that I do not want displayed. If I display the data in a boundfield it works fine but if I set the visibility to false the parameter is no longer sent to the update stored procedure. There does not appear to be a hiddenfield column that I can put into the gridview.
I have tried to set the parameters through the code behind but I am not certain on how to access the data I want the following code does not work (It sets the parameter to nothing
Protected Sub grvFacilityDisciplineBillingRate_RowUpdating(ByVal sender As Object, ByVal e As GridViewUpdateEventArgs) Handles grvFacilityDisciplineBillingRate.RowUpdating
Dim row As GridViewRow = grvFacilityDisciplineBillingRate.Rows(e.RowIndex)
sqlDisciplineBillingRate.UpdateParameters("Facility_ID").DefaultValue = CInt(row.DataItem("Facility_ID"))
sqlDisciplineBillingRate.UpdateParameters("Discipline_ID").DefaultValue = CInt(row.DataItem("Discipline_ID"))
End Sub
And this is the front end with the two ID columns displayed, which is not what I want
<asp:SqlDataSource ID="sqlDisciplineBillingRate" runat="server" DataSourceMode="DataSet" SelectCommandType="StoredProcedure" SelectCommand="SP_Facility_DisciplineBillingRates" UpdateCommandType="StoredProcedure" UpdateCommand="SP_DiscplineBillingRate_Update" ConnectionString="<%$ ConnectionStrings:Trustaff_ESig2 %>">
<SelectParameters>
<asp:Parameter Name="Facility_ID" DbType="Int32" />
</SelectParameters>
<UpdateParameters>
<asp:Parameter Name="Facility_ID" DbType="Int32" />
<asp:Parameter Name="Discipline_ID" DbType="Int32" />
</UpdateParameters>
</asp:SqlDataSource>
<asp:GridView ID="grvFacilityDisciplineBillingRate" runat="server" DataSourceID="sqlDisciplineBillingRate" DataKeyNames="DisciplineBillingRate_ID" AutoGenerateColumns="false" AllowSorting="true" AllowPaging="false" AutoGenerateEditButton="true" CssClass="gridview">
<EmptyDataTemplate>
There were no discipline billing rates for this facility.
</EmptyDataTemplate>
<Columns>
<asp:BoundField DataField="Name" HeaderText="Discipline" SortExpression="Name" ReadOnly="true" />
<asp:BoundField DataField="BillingRate" HeaderText="Billing Rate" SortExpression="BillingRate" />
<asp:BoundField DataField="Facility_ID" HeaderText="Facility_ID" SortExpression="Facility_ID" InsertVisible="false" />
<asp:BoundField DataField="Discipline_ID" HeaderText="Discipline_ID" SortExpression="Discipline_ID" />
</Columns>
</asp:GridView>
You simply have to set the DataKeyNames e.g. DataKeyNames="Facility_ID,Discipline_ID" and the SqlDataSource will figure it out for you when using GV's Update and Delete feature.
Try using Template fields and use a label control and hide them by setting visible="false".
<asp:TemplateField HeaderText="College">
<ItemTemplate>
<asp:Label ID="lbl_Title" runat="server" text='<%# Bind("Title") %>' visible="false"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
And use below code to access values from codebehind.
If gvrow.RowType = DataControlRowType.DataRow Then
Dim label1 As Label = DirectCast(gvrow.FindControl("lbl_Title"), Label)
'Access text of label using label1.text and cast to int or string
End If
You can eliminate using templated fields if you don't wish for ID columns. And still access it using datakeynames property