Delete Row Method (getting the primarykey of row being deleted)

Hello friends,

I'd like to retrieve the primary key of the row being deleted so i can use it as a parameter in my stored procedure: Here's how far i have come with my code. I need help with line 6.

Thanks in advance :) 

 

1        Protected Sub DependentsObjectDataSource_Deleting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.ObjectDataSourceMethodEventArgs) Handles DependentsObjectDataSource.Deleting
2 3 'get value of deleting depednent id
4 'Delete (Unenroll) all benefits dependent enrolled in before attempting to delete dependent
5 Dim empIdString As String = GetEmpId()
6 Dim dependentIdString As String = me.DependentsGridView. 'Me.DependentsGridView.DeleteRow.SelectedValue.ToString() 'Me.DependentsGridView.SelectedRow.Cells(0).Text 'Me.DependentsGridView.SelectedValue.ToString() 'get dependentId from selected congtrol 7 8 If Not empIdString Is Nothing Then 9 'empIdString = querystring
10 '1 - Import sql types at top of code
11 '2 - declare variables
12 Dim conn As SqlConnection
13 Dim cmd As SqlCommand
14 15 '3 - create connection 16 conn = New SqlConnection
17 conn.ConnectionString = ConfigurationManager.ConnectionStrings("JMMConnectionString").ConnectionString
18 conn.Open()
19 20 '4 - create command 21 cmd = New SqlCommand
22 cmd.CommandType = CommandType.StoredProcedure
23 cmd.CommandText = "UnenrollDependentsFromBenefits" 24 '4.2 -Declare a parameter 25 Dim param As SqlParameter
26 param = New SqlParameter("@empId", SqlDbType.VarChar, 20)
27 param.Direction = ParameterDirection.Input
28 param.Value = empIdString
29 30 '5-Link command to connection 31 cmd.Connection = conn
32 cmd.Parameters.Add(param)
33 cmd.Parameters.Add(New SqlParameter("@dependentId", SqlDbType.VarChar, 20))
34 cmd.ExecuteNonQuery()
35 conn.Close()
36 End If 37 38 'Refresh benefits views to reflect deletions 39 Me.BenefitEnrollmentsGridView.DataBind()
40 Me.BenefitEnrollmentsDetailsView.DataBind()
41 42 End Sub
  
ASP.NET Newbie
0
undeclared
6/1/2007 2:49:45 PM
asp.net.presentation-controls 72751 articles. 3 followers. Follow

8 Replies
890 Views

Similar Articles

[PageSpeed] 31

DependentsGridView.SelectedValue.ToString() should work, so long as you have the DataKeyNames property set the the primary key field.

http://msdn2.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.selectedvalue(vs.80).aspx 


Regards Mike
[MVP - ASP/ASP.NET]
My site
0
Mikesdotnetting
6/1/2007 3:30:13 PM

Thanks Mike,

I get the error "Object reference not set to an instance of an object." When i use this in line 6: What do you think?

 

Dim dependentIdString As String = Me.DependentsGridView.SelectedValue.ToString
  
ASP.NET Newbie
0
undeclared
6/1/2007 4:09:14 PM

 I might be having problem with a null reference since i haven't selected any value in my gridview. I have simply clicked on a delete button to delete.

Please help me on how to retrieve my pk value on deleting....thanks :) 


ASP.NET Newbie
0
undeclared
6/1/2007 4:12:47 PM

 anybody? Sad


ASP.NET Newbie
0
undeclared
6/1/2007 6:42:36 PM
Can you show the code for your GridView?

Regards Mike
[MVP - ASP/ASP.NET]
My site
0
Mikesdotnetting
6/1/2007 6:56:04 PM

 Hi Mike, thanks for your patience.

I am just trying to tell the method to run a delete storedprocedure, while getting the parameter from the primary key of the current record being deleted. ie. i want it to delete child records before attempting to delete the child itself.

gridview code here: Hope to hear from you!

 

1                        <asp:GridView ID="DependentsGridView" runat="server" AutoGenerateColumns="False" DataKeyNames="dependentId"
2                            DataSourceID="DependentsObjectDataSource" OnDataBound="DependentsFormView_DataBound"  Width="70%" HorizontalAlign="Center">
3                            <Columns>
4                                <asp:TemplateField ShowHeader="False">
5                                    <EditItemTemplate>
6                                        <asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="True" CommandName="Update"
7                                            Text=""></asp:LinkButton>
8                                    </EditItemTemplate>
9                                    <ItemTemplate>
10                                       <asp:ImageButton ID="SelectImageButton" runat="server" CausesValidation="False" CommandName="Select"
11                                           ImageUrl="~/Images/selectbutton.gif" />
12                                   </ItemTemplate>
13                               </asp:TemplateField>
14                               <asp:BoundField DataField="dependentId" HeaderText="dependentId" InsertVisible="False"
15                                   ReadOnly="True" SortExpression="dependentId" Visible="False" />
16                               <asp:BoundField DataField="empId" HeaderText="empId" SortExpression="empId" Visible="False" />
17                               <asp:BoundField DataField="dFirstName" HeaderText="FirstName" SortExpression="dFirstName" />
18                               <asp:BoundField DataField="dLastName" HeaderText="LastName" SortExpression="dLastName" />
19                               <asp:BoundField DataField="dRelationship" HeaderText="Relationship" SortExpression="dRelationship" />
20                               <asp:TemplateField ShowHeader="False">
21                                   <EditItemTemplate>
22                                       <asp:LinkButton ID="UpdateLinkButton" runat="server" CausesValidation="True" CommandName="Update"
23                                           Text=""></asp:LinkButton>
24                                       <asp:LinkButton ID="CancelLinkButton" runat="server" CausesValidation="False" CommandName="Cancel"
25                                           Text=""></asp:LinkButton>
26                                   </EditItemTemplate>
27                                   <ItemTemplate>
28                                       <asp:ImageButton ID="DeleteImageButton" runat="server" CausesValidation="False"
29                                           CommandName="Delete" ImageUrl="~/Images/deleteperson.bmp" OnClientClick="return confirm('Are you certain you want to delete this dependant? \nThis action will unenroll(delete) dependent from all benefits!');"
30                                           ToolTip="Click to delete this dependant" />
31                                   </ItemTemplate>
32                               </asp:TemplateField>
33                           </Columns>
34                           <EmptyDataTemplate>
35                               <center> No dependants entered</center>
36                           </EmptyDataTemplate>
37                       </asp:GridView>
  
ASP.NET Newbie
0
undeclared
6/1/2007 7:02:47 PM

I thought, it would maybe better to do this from the OnRowDeleting event of the GridView?

In the handler, use  GridViewDeleteEventArgs, then you can get the SelectedValue of the key easily.

 

Then I thought, wait a minute, you don't have to do any of this stuff.

Just click delete,  ASP takes care of passing the key in the deleteparameter, and the deletemethod specified in the objectdatasource takes care of it all without a single line of code in your page.

Yeah OK, you have some code in the objectdatasource/business layer instead, but less, and it is tucked away separate from the presentation layer.

Unless I am missing something, of course.


If a post helps to solve your problem, please click the Answer button on that post.

I'm still confused, but now I'm confused on a higher plane.
0
LockH
6/2/2007 12:06:08 AM

Hi LockH,

Thanks for your input.
This code i found from the msdn site did the charm in helping me get the deleting key.

1            Dim paramsFromPage As IDictionary = e.InputParameters
2            Dim dependentIdString As String = paramsFromPage("dependentId").ToString()
3    
  Thanks all!

ASP.NET Newbie
0
undeclared
6/4/2007 3:59:34 PM
Reply:

Similar Artilces:

How to delete row from GridView control
Hello,  I am working on an ASP.NET 2.0 app, and I am trying to wire up a "Delete" button to a gridview control on a form. Here is the code for the ASP :  <asp:GridView ID="gvInConditions" runat="server" AutoGenerateColumns="true" OnRowDeleting="gvInConditions_RowDeleting" DataKeyNames="Condition_ID" >         <Columns>                <asp:CommandField ButtonType="Button" SelectText=&...

How to delete controls in GridView when the delete button in a row is clicked
Hi,   I am having issues with my gridview.....i added 2 dropdown and 2 compare validators....whenever i delete a row though......the dropdown and compare validators are becoming null........thus when i click a button, it is still validating.............anyway to delete this when i click the delete button or even handle?   Please help.  ...

running a delete statement that matches multiple rows fails or partially fails to delete those rows.
I am having a very strange issue and looking for some ideas on next troubleshooting steps. Summary: running a delete statement that matches multiple rows fails or partially fails to delete those rows. Description: I am running Sybase ASE 15.0.0 and Solaris 10 with multiple zones. I BCP 1.5 million rows of data into a ProductStage table before running the following two statements - DELETE Product FROM Product, ProductStage (INDEX XPKProductStage) WHERE Product.BatchNumber LIKE @LikeArgument AND Product.BatchNumber = ProductStage.BatchNumber AN...

DataSet rows being deleted, but after the update , the sql database is not updated. The delete rows still in the database.
 Stepping thru the code with the debugger shows the dataset rows being deleted.   After executing the code, and getting to the page presentation. Then I stop the debug and start the page creation process again ( Page_Load ).    The database still has the original deleted dataset rows. Adding rows works, then updating works fine, but deleting rows, does not seem to work.   The dataset is configured to send the DataSet updates to the database. Use the standard wizard to create the dataSet.     cDependChildTA.Fill(cDependChildDs._ClientDependentC...

delete row or delete all in Gridview?
Hi there, I have a Gridview that bind the data from the .mdb  and I want to have 2 delete buttions, one is delete a row and the other one is delete all from the database.  How do I do it in code behind in c#?  thanks a lot row delete  (temp call rowDel) all delete (temp call allDel) with rowDel: i think you should bound one column in gridview  (or datagrid)<asp:ButtonColumn... and bout allDel: i think you should use a button distinct with gridview.Becoz your required is not complex , when allDel be push you don't care...

Delete row and delete from table
Hi I need, after delete a grid row, execute a delete statmentProtected Sub GridView1_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles GridView1.RowCommand Dim advogado As StringIf (e.CommandName = "Apagar") Thenadvogado = RTrim(e.CommandArgument.ToString)Apaga_Processos(advogado)End Ifend subPrivate Sub Apaga_Processos(ByVal advogado As String)Dim conn As SqlConnectionDim comm As SqlCommandDim connectionString As String = ConfigurationManager.ConnectionStrings("mssql2.tuganet.com").ConnectionStringconn = New Sql...

Delete row removes all rows
When datawindow row 1 is clicked and selected then a pfc_deleterow is issued all dw rows are deleted. dw_1 update spec is "update", not delete then insert. Only one key column on the table which is a serial column. ll_rtn = dw_1.event pfc_DeleteRow() ll_rtn count does indicate that all rows were deleted. If any other row is selected then only the selected row is deleted. When the window is 1st opened and row one is displayed but not selected, only row 1 is deleted. Is this the expected behavior? PB 7.02 8046, NT 4.0, and the corresponding version of SQLAnywhere (whate...

Insert/Delete/Delete all rows
Hi Neither in data window painter nor in data base painter I can Insert, Delete and Delete all Rows for a table. These Items are in both painters gray and can,t been selected. Is something wrong on my installation of PB? PB 7.02 (Build 8030) Can someone help me? Thanks Taghi Pouradjam Does your table have a primary key defined? -- <hopethishelps /> Roy Kiesler [TeamSybase] mySybase -- http://my.sybase.com "Taghi Pouradjam" <pouradjam@oasys.de> wrote in message news:OzIH97fiAHA.128@forums.sybase.com... > Hi > > Neither in data wi...

adding / deleting table rows, and accessing controls within added rows
Hi everyone,I would like to know what is a good and simple way to achieve this using asp.net.  Basically i would like the ability to add and delete rows, preferably table rows.  Against each row is its delete button, hitting it will delete the corresponding row.  There is only 1 Add button to add a new row.  In each row, there are say 2 textboxes.  When i hit, say a calculate button, i wish to be able to access all the available textboxes in all the available rows in the event handler, and say just output a sum.If GridView is suggested, could you please explain why i...

Trying to delete a row, I get "Row changed between retrieve and update."
Hi Trying to delete a row I get the following error message and can't figure out why. Please see error below and any suggestion will be appreciated. Thanks Error message and part of the script: Row changed between retrieve and update. No changes made to database. DELETE FROM q_code_cause WHERE code = 1 AND ... Ok I found the Problem! Thanks anyway "Wasap" <edgadon@medicalcardsystem.com> wrote in message news:3f96a7a5@forums-2-dub... > Hi > > Trying to delete a row I get the following error message and can't figure > out why. Ple...

is it possible to avoid getting fresh data when i delete a row in delete command of datagrid?
hi i ve wriiten code like this here i need to avoid getting fresh data from database inspite of that i want to delete the row in datagrid which i deleted in the database is this possible here is my code.Label rangeId = (Label)e.Item.FindControl("lblRangeId"); //deleting the rows near rangeid.DataSet dsDeleteRange = SqlHelper.ExecuteDataset(trans, CommandType.Text, "Delete tPrintServiceRange where RangeId=" + rangeId.Text);lblMessage.Text = "Data Deleted Sucessfully."; lblMessage.ForeColor = System.Drawing.Color.Green; Bindgrid();pavankumar I guess it wo...

Looping through rows of a DataGridView who's rows may be getting deleted within the loop?
Hi everyone, I have a DataGridView that is populated with data. In one of my procedures, I'm looping through each row of the DGV, and with each pass in the loop, there's a possibility that the row that is being worked on may be deleted.  The problem is that I've started the for loop using 0 to intRowCount (which represents the number of rows.  If I don't delete any rows, everything works fine.  If I delete a row, I'm guessing that the intRowCount is no longer accurate and in some situations points to a row that no longer exists, and I get an index out of ...

Select a Row in DataGrid and Delete this Row
My goal is to put the Rows from one (left) GridView into the secend (right) GridVIew.For this I would like to use Drag and Drop becauce this would do just that but I can find only D&D features in e.g. Dojo. Is it possible in ASP.NET, too?Because I didn't find the D&D solution for ASP.NET I created two GridViews with a SELECT Label for choosing a Row. Then I chosen the SelectedIndexChanged event but when I want to delete the selected row then an error occurs that this isn't possible. Does anyone knows how I can solve my problem? Thank you!  Hello!!Plz see following lin...

Deleted row information cannot be accessed through the row.
I'm getting an exception with the message "Deleted row information cannot be accessed through the row". I have processing the records through the data table. In some situation i have deleted the rows in the datatable and inserting the new rows. These situation i have get the above specified error. Regards, Vijay Hi Vijay, this error occours when u try to access the row which u have already deleted. So, try to check if the row exists or not and then retrieve the information. I hope this will help u..Please mark as Answer if it helps u. Thanks!Parth PatelTechsture Technol...

Web resources about - Delete Row Method (getting the primarykey of row being deleted) - asp.net.presentation-controls

Entity Framework & Resolving Team Migration Conflicts
... : DbMigration { public override void Up () { CreateTable ( "dbo.Books" , c new { ID = c . Int ( false , true ) }). PrimaryKey ( t t ...

Intelligent Versus Surrogate Keys
Should I use business columns as primary key fields for tables in thedatabase, or generate artificial primary key values? When business-related ...

Realm Database Complete Data Model
This is code from my upcoming app, with a working title of MileageTracker. It's a complete vehicle expense tracking app. This is not about my ...

MS Gooroo Career Development for Technology Professionals
[{"SkillId":730,"Label":".Net","Relevancy":10,"Jobs":27495,"WikipediaIntroduction":"\u003cp\u003e\u003cb\u003e.NET Framework\u003c/b\u003e (pronounced ...

Fully Editable Datagrid - Pale Musings
This is the text from an article I wrote back in April of 2003 and had published on the original DotNetJunkies site. After my recent change in ...

Russian internet Deal Book 2012-2013 Fastlane Ventures
New research by Fastlane Ventures covers 600 deals made in Russian internet in 2012-2013. This second edition of the Deal Book provides the most ...

Dove Search Guidelines
This search facility is based upon an extract from the database which underlies Dove. It includes rings of 3 bells and upwards (7135 rings in ...

Dove Search Guidelines
This search facility is based upon an extract from the database which underlies Dove. It includes rings of 3 bells and upwards (7136 rings in ...

Help for Bell Founders file
This file is NOT a comprehensive list of all known bell founders: it is simply another presentation of the data that appears in the 'drop-down' ...

Dove Search Guidelines
This search facility is based upon an extract from the database which underlies Dove. It includes rings of 3 bells and upwards (7135 rings in ...

Resources last updated: 1/4/2016 12:29:06 AM