How to use GridView row's Key selected for Delete as select parameter for another datasource

I'm not sure if the subject title makes sense, but it wasn't too easy to describe what I'm trying to do in one sentence!

When a user clicks on the delete link in a GridView row, I want to run a stored proc, using the Key of the selected record as the parameter for the stored proc. I then want to programatically access the result of the stored proc (it'll be an integer value) for code-behind use.

I wrote out a few steps to help me figure out what I need to do:

1) Get the value of PersonnelID (the DataKey) from the selected row in the GridView
2) Set that PersonnelID value as the select parameter for the datasource dsPersonnelForSupervisorCheck"
3) Run the stored proc via the business logic class "PersonnelSystem"s function "GetListPersonnelForSupervisorCount" (all data handling is done through business logic classes)
4) Determine if the value from the stored proc is greater than 1
  a) If so, display message box & cancel delete operation
  b) If not, continue with delete operation

I'm assuming the best place to do this is in the GridView_RowDeleting event. My main sticking points are how to access the PersonnelID of the row selected for deletion, how to get that PersonnelID value set to the SelectParameter for the dsPersonnelForSupervisorCheck" datasource, and how to access the result of the stored proc. I think once I get those ironed out I can handle the business logic class handling and the value comparison/message box part.

Here's the VB code I've been "messing" around with. Hopefully my copious use of commenting will help clarify what exactly I'm trying to do:

1    Protected Sub gvPersonnel_RowDeleting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewDeleteEventArgs) Handles gvPersonnel.RowDeleting
3    	'Define a variable to hold the PersonnelID value
4    	Dim checkSelectParam As String
6    	'Get the value of PersonnelID from the selected row in the GridView
7    	checkSelectParam = dsPersonnel.DeleteParameters.ToString		'Mouseover at runtime shows checkSelectParam as "System.Web.UI.WebControls.ParameterCollection"
9    	'Set the retrieved PersonnelID value (stored in checkSelectParam) as the select parameter for the supervisor check datasource
10   	dsPersonnelForSupervisorCheck.SelectParameters(checkSelectParam).ToString()
11   	'Above code generates the following error at runtime
12   	'NullReferenceException was unhandled by user code
13   	'Object reference not set to an instance of an object
15   	'dsPersonnelForSupervisorCheck.SelectParameters("PersonnelID") = gvPersonnel.SelectedValue()
16   	'Above generates following error at runtime
17   	'ArgumentNullException was unhandled by user code
18   	'Value cannot be null.
19   	'Parameter(name) : value
21   	'Select parameter is retrieved, so run the stored proc via the business logic
22   	dsPersonnelForSupervisorCheck.DataBind()
24   	'Define a variable to hold the result of the stored proc's select statement
25   	Dim value As String
27   	'Set "value" to the result of the stored proc
28   	'value = 'No idea how to do this!
30   	If value > 0 Then
31   		'Above generates following error at runtime
32   		'InvalidCastException was unhandled by user code
33   		'Conversion from string "System.Web.UI.WebControls.Parame" to type 'Double' is not valid.
34   		MsgBox("The personnel you selected for deletion" & ControlChars.NewLine & "is assigned as a supervisor for at least one other personnel." _
35   		 & ControlChars.NewLine & "Personnel record cannot be deleted.", MsgBoxStyle.OkOnly, "Operation Canceled")
37   		'Selected personnel is assigned as super to other personnel, so cancel delete
38   		Exit Sub
39   	Else
40   		'Continue with row deletion
41   	End If
42   End Sub

 Here are the related datasources:

<asp:ObjectDataSource ID="dsPersonnelForSupervisorCheck" runat="server" SelectMethod="GetListPersonnelForSupervisorCount"
		<asp:Parameter Name="PersonnelID" Type="Int32" />

<asp:ObjectDataSource ID="dsPersonnel" runat="server" SelectMethod="GetListPersonnel"
	DeleteMethod="DeletePersonnel" UpdateMethod="UpdatePersonnel" InsertMethod="UpdatePersonnel"
		<asp:Parameter Name="PayrollCompanyID" Type="int32" />
		<asp:Parameter Name="PersonnelID" Type="Int32" />
		<asp:Parameter Name="FirstName" Type="String" />
		<asp:Parameter Name="LastName" Type="String" />
		<asp:Parameter Name="IsSupervisor" Type="Boolean" />
		<asp:Parameter Name="PersonnelID" Type="Int32" />

 Don't know if it'll help, but here's the stored proc that checks the table to see if the selected PersonnelID is found in the SupervisorID of other records in the table:

CREATE PROCEDURE dbo.sp_CheckSupervisorCount

@PersonnelID int

DECLARE @count int
SET @count = 0

SELECT @count = COUNT(SupervisorID)
FROM rsrc_Personnel
WHERE SupervisorID = @PersonnelID

 I'd appreciate it if someone could take a look at my code and help me figure out how to accomplish what I'm trying to do.


"f u cn rd ths, u cn gt a gd jb n cmptr prgmmng." - Anon
8/29/2007 2:06:54 PM 72751 articles. 3 followers. Follow

1 Replies

Similar Articles

[PageSpeed] 44

Here's what I would do (I'm sure there are plenty of other ways to do it though):

Set the CommandArgument of the Delete button or whatever button you are using to the row index - I usually do this in the RowDataBound

Use the RowCommand event rather than the RowDeleting event

Check e.CommandName to check which command raised the event

Dim rowindex as integer = cint(e.CommandArgument)

Rather than using an ObjectDataSource you can use a table adapter to retrieve the row count

e.g. Dim dta as new (whatever your table adater is here): Dim dt as datatable = dta.GetListPersonnelForSupervisorCount(Me.gvPersonnel.DataKeys(rowindex).Value))

You can get the number of rows or if you are just returning a count, value for the first row

If Value = 0  then Me.gvPersonnel.DeleteRow(rowindex)

Hope that helps, Tim

8/29/2007 5:31:16 PM

Similar Artilces:

First gridview's selected row doesn't update second gridview's objectdatasource
 HelloI got 2 gridviews on a page, each with its own ObjectDataSource. The first gridview fills itself just normally, no problem there. The second gridview needs to fill itself with other data, where the primary key is the primary key of the selected row of the first gridview.schematically:gridview1 row: IDfield, x, y, zrow: IDfield, x, y, z (-> this row is selected)row: IDfield, x, y, z gridview2 row:IDfield_of_selected_row_in_gridview1, a, b, c I tried to do this by configuring the ObjectDataSource behind gridview2 with a parameter pointing to gridview1.selectedValue. (by usin...

Problem in Using DropDownList Control to select a selected row of SqlDataSource that is under GridView Control
Hi all,In my SQL Server Management Studio Express, I have a database "ChemDatabase" that has a table "LabData"  formatted in the following way: SampleID int PRIMARY KEY, SampleName nvarchar(25), ChemicalName, nvarchar(25), Concentration decimal(6.2) with 5 rows of records in this .dbo table. In my Visual Web Developer Express, I created a website "RPD-TCE" for extracting a row of record from the LabData table by using a DropDownList, a GridView and a SqlDataSource.  I want to click DropDownList to list one number of S...

How To Populate A GridView From Another GridView's Selected Row Set
Hi, I am in a situation where i need to populate a gridview from another gridview's seleted rowset. The first gridview is showing some data from database . The data source table of the first gridview does not have any primary key because it has some aggregate results (i have used group by clause in the SQL query ). So the "DataKeyNames" property of the first gridview can not be set. The second gridview will be populated from the selected rows of the first gridview. As the first gridview does not have "DataKeyNames" property set, i can not f...

want to bind a gridview using the another gridview's selected item
 iam using a gridview1 which holds the feilds like (Cust_ID, date, ......). Now what i want to do is, when i click on any Cust_ID in the gridview1, it should bind the another gridview2 using the Cust_ID value, in the same page itself.... Here's a very simple example: <%@ page language="C#" masterpagefile="~/MasterPages/Default.master" autoeventwireup="true" codefile="1328980.aspx.cs" inherits="Posts_GeneralASPNET_DataPresentationControls_1328980" title="Untitled Page" %> <asp:content id="Content...

selecting row in gridview by clicking anywhere in row (not just on 'select' link)
Hi there- I would like my gridview to behave such that a click anywhere in the (whole length of the) row would act just like clicking the "select" column link. Anyone have any code or suggestions?   You could use: ( but you would also need to disable event validation ) <%@ Page Language="VB" EnableEventValidation="false"%> Protected Sub GridView1_RowCreated(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) If e.Row.RowType = DataControlRowType.DataRow Then e.Row.Attributes.Add("onclick", "javascript:__doPostBack('GridView1','select$" &...

Using a row selection in a gridview to create database rows for another gridview
Hi there, I have 2 gridviews on a form, the first displays some template rows from a database table.  The second displays some user specific rows (with additional data added to the template info) from the same table. They both work fine for displaying the info.  Now what I want to do, is allow users to 'select' a template row on the first gridview, and have that action automatically: create a new user-specific row, with added fields from profile data etc. insert it into the table then refresh the second gridview in order to show the new added row. C...

Selecting the multiple rows in GridView and inserting the selected rows to another Gridview & Performing some operations on it
 Dear All, I have become mad for solving this problem. Please Help me. I have a Gridview bound to a datasource. I inserted the CheckBox Control in Templet to select certain rows. Gridview1 contains some products id & name.I want to insert the selected rows in to second Gridview  and in the second Gridview I need to add two more colums AdvicedQty & AcceptedQty(TextBox Cotrol).The user will select few products in Gridview1 & clicks add which will be added another gridview then in second Gridview he enters the AdviceQty & AcceptedQty.After entering the data he cli...

How to make the DetailsView's edit button visible according to the state of one field of a GridView's selected row?
Hello everyone! Now I am working with a Master/Detail page that using a gridview and a detailsview. The detailsview is set to editable and the edit button is autogenerated. I want to make the DetailsView's edit button visible according to the state of one field of a GridView's selected row. I tried to access the selected row of the gridview in the detailsview's ItemCreated event or DataBound event,using the following code GridViewRow row = gvwMaster.SelectedRow But it goes wrong with this line of code. And then I tried to write some code in the gridview's SelectedIndexChanged eve...

Gridview paging enabled. Has checkbox to select the row . If user select the checkbox on one page and move to 2nd page to select the rows there also to export the selected rows to excel. But doing so
HiI am using Gridview and that has paging enabled. Using checkbox to select the particular row of the gridview to export the selected rows to the excel . Everything is working fine except for one case.Let user selected the "check" box for, five rows which user would like to export to excel (two of rows on page 1 of results and 3 of them on page 2 of results), however it only exports the 3 row details from page 2, because it seems to de-select the 2 rows from page 1 when I move to page 2 and vice versa. The code i am using is as :protected void BtnExcel_Click(object sender, EventArg...

Selecting another control in a custom control's properties
I have a custom control I'm creating and It is going to influence a gridview on the parent page.  What I would like is when the custom control is dropped onto the page in the designer, to be able to select the gridview in the custom control's properties (similar to the way when you drop a RequiredFieldValidator you can select other controls in the ControlToValidate property.  Is there a way to mimick the ControlToValidate property, except be able to select from any GridViews on the page?   Thanks! Hi, first you need to create a type converter. You can creat...

How to set DDL's selected value by datasource other than DDL's datasource
I have three TemplateFields in a Gridview. In each, the ItemTemplate has a label whose text value is bound to the GridView's DataSource. But in the EditItemTemplate the DropDownList is populated with a separate DataSource. This is a fairly common setup, so that wasn't too much to deal with. What I need to do is, when the GridView goes in to Edit mode and the DropDownList is populated and displayed I want the value that was in the bound label to be the default selected value in the DropDownList. As it currently is, the DropDownList renders with "Select..." as the defau...

Should FxOS's "select all" really be docshell's "select all" (which tries to select everything in the document)?
The specs on (specifically which of the two is the one that discusses "select all") don't directly address the issue of containment for non-editable areas. Our implementation, as I trace it, ends up invoking do_selectAll on the docshell which tries to select *everything* editable in the entire page. This came to my attention while looking at which is an email bug where select all was selecting both the selectable content on the current message rea...

Selecting a gridview row and keeping the last selected row in a gridview highlighted after mouse moves over a new row.
What is the best way to show a gridview row highlighted once selected and keep it highlighted once the mouse moves over a different row? Thanks, Steve hi,you can use <SelectedRowStyle BackColor="#008A8C" Font-Bold="True" ForeColor="#FFFFFF" /> plz let me know if i misunderstood you Thanks for your help. One problem; however, is that after the row has been selected and I check the "grid.SelectedIndex" it has a value of -1 and not the index of the row that was selected on the grid. What do you recommend? Thanks, Steve hi, sorry i din...

Using Gridview for delete, update and select using seperate sql statements and parameters
Hi everyone, I have a gridview which is bound to a sqldatasource which runs a stored procedure using userid as a parameter.  This then puts into a gridview all the surveys that that user has created. This all work fine, the problem is that when I put a delete button on the grid it expects the same parameter that the select statement uses which is the userid.  However the stored procedure which deletes from the database uses surveyID as the parameter as i need the user to be able to choose which survey they want to delete. My question is how do you have a delete button which ru...

Web resources about - How to use GridView row's Key selected for Delete as select parameter for another datasource -

Datasource - Wikipedia, the free encyclopedia
A DataSource object has properties that can be modified when necessary. For example, if the data source is moved to a different server, the property ...

Inverness Graham Acquires DataSource
Inverness Graham , a lower middle market private equity firm headquartered in suburban Philadelphia, has acquired DataSource , a print supply ...

SmartGlance for iPad for iPad on the iTunes App Store
Read reviews, get customer ratings, see screenshots, and learn more about SmartGlance for iPad on the App Store. Download SmartGlance for iPad ...

Chaitanya Pandit (@chaitanyapandit) on Twitter
Sign in Sign up To bring you Twitter, we and our partners use cookies on our and other websites. Cookies help personalize Twitter content, tailor ...

Data source - Wikipedia, the free encyclopedia
... Data source A data source is any of the following types of sources for (mostly) digitized data: a database in the Java software platform, datasource ...

2ndQuadrant - PostgreSQL expertise from specialists with a source code level understanding of RDBMS ...
PostgreSQL expertise from specialists with a source code level understanding of RDBMS PostgreSQL Planets Gabriele’s PlanetPostgreSQL Gianni’s ...

Tagged entries for CLOUD COMPUTING
Alan Williamson's output as a Java Champion, Blog-City Architect, BlueDragon Creator, Author, Speaker and Internet Guru

Private equity deals
... of biometric identity management systems, applications and services. Inverness Graham Investment has acquired DataSource ...

C# C Sharp and Tutorials on C#
Learn the c# langauge to build web applications using our online tutorials with live demos. Participate in our forums and learn from others. ...

JavaScript UI Library, Ajax Components & HTML5 Framework - DHTMLX
DHTMLX offers a rich JavaScript library, UI components & HTML5 mobile framework. Build impressive web apps for both desktop and mobile devices. ...

Resources last updated: 2/14/2016 3:59:32 AM