Subject: Membership / User question
Posted By: rsearing Post Date: 6/30/2008 12:15:41 AM
I'm not sure if Membership works differently in 3.5 or not.  I store a member's userID in a seperate table.  I have a member disabled upon the createuserwizard so that an admin can validate and enable this person.

SO---in my detailsview, I am trying to have a field that will show whether a person is enabled or disabled and then click to enable or disable (still not sure the easiest way to do this)..however, my problem is in getting the value of whether the user is enabled or not.

I do capture the userID in my table and it actually populates a field in the datalist - obviously, it's a string.  Is there a way to convert the userID into a parameter that will allow me to get to the user's entry in the asp_membership table?

I would sure appreciate any suggestions on how to tailor that particular field of the DataList...my thoughts were to have a button where the button's text would be dynamic - upon creation, it would evaluate whether user is enabled or disabled and then change text of button appropriately.  Then on Button_click also check enabled or disabled and then run the appropriate function.

I can't even begin to do that until I figure a way to use a text representation of a UserID to find  the user.

LAST question....I can get to the userID field in teh DataList by activeLabel = CType(e.Item.FindControl("ApprovedLabel"), Label) - but suppose I don't want to show the userID in the datalist--can I remove and get the value that is returned by the objectDataSource some other way - or do I have to create a hidden control and bind it and then do same as above (CType...)

Thanks, in advance,
Rob

Reply By: Imar Reply Date: 6/30/2008 1:50:14 AM
The User ID (the ProviderUserKey) is not a string; it's an Object.

Under the hood, the SqlServerMembershipProvider stores the ProviderUserKey as a Guid.

So, to get back the user you can do this:

Dim myId As Guid = new Guid(yourProviderUserKeyAsString)

Where yourProviderUserKeyAsString comes from depends; it could be the Query String, the SelectedValue of some control and so on.

WIth the ID you can get the user like this:

Dim myUser As MembershipUser = Membership.GetUser(myId)

You can make the ID part of the DataKeys collection of your data list control. Then it's available in the selected item.

Hope this helps,

Imar





---------------------------------------
Imar Spaanjaars
http://Imar.Spaanjaars.Com
Everyone is unique, except for me.
Author of Beginning ASP.NET 3.5 : in C# and VB, ASP.NET 2.0 Instant Results and Dreamweaver MX 2004
Want to be my colleague? Then check out this post.
Reply By: rsearing Reply Date: 6/30/2008 8:29:34 AM
Imar,

It most certainly does - I was trying to look at the overloads for the getuser method and was stuck on how to convert the string to something that would retrieve.

As to the DataKeys - this is probably more a beginner topic, but I have always used code behind methods to get the value of a database return by trying to tie into the value of the control that it is bound to.  What is the syntax on the control and the code behind to use DataKeys?  In other words, how to I initiate it in the control - and then in what code behind function do I use and how do I reference it?  How do I reference if I want more than one?

Thanks!!!
Rob

Reply By: Imar Reply Date: 6/30/2008 10:28:38 AM
You can assign the data key like this:
<asp:DataList ID="DataList1" runat="server" DataKeyField="Id" />
And then later retrieve it like this:
DataList1.SelectedValue
Hope this helps,

Imar


---------------------------------------
Imar Spaanjaars
http://Imar.Spaanjaars.Com
Everyone is unique, except for me.
Author of Beginning ASP.NET 3.5 : in C# and VB, ASP.NET 2.0 Instant Results and Dreamweaver MX 2004
Want to be my colleague? Then check out this post.
Reply By: rsearing Reply Date: 6/30/2008 10:34:49 AM
Imar - close.  Suppose, as is the case with me, the userID is not the primary key for the table (memberID is)...does that matter?  Suppose I wanted to capture more than one value - let's say I want to reference userID and email??  I am only wanting to get to userID so I can run that function to get access to that user's "isactive" field in the asp_membership table...but curious how I might work this if I wanted to get access to other fields that are returned from the objectdatasource.

Thanks!
Rob

Reply By: Imar Reply Date: 6/30/2008 11:01:12 AM
You can use the DataKeys property (which is a collection) to assign and retrieve multiple data keys...

http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.basedatalist.datakeys(VS.85).aspx

Imar


---------------------------------------
Imar Spaanjaars
http://Imar.Spaanjaars.Com
Everyone is unique, except for me.
Author of Beginning ASP.NET 3.5 : in C# and VB, ASP.NET 2.0 Instant Results and Dreamweaver MX 2004
Want to be my colleague? Then check out this post.
Reply By: rsearing Reply Date: 6/30/2008 4:55:59 PM
Imar .. or anyone..I need help, and I have tried researching this in both my Professional ASP.NET 2.0 & 3.5 (Wrox books) and online - and I think I am getting terms mixed up.

Can you *please* explain (or point out a source that explains this) the difference between:

DataKey
DataKeyField
DataKeysArray
DataKeyName

I always took DataKeyName to be that which is the field representing the Primary key of a table - I guess I didn't realize that I could use the DataKeys to store multiple "non-primary-key" fields--and am getting really confused on the different terms above--and it's driving me crazy.

Please.

-Rob

ADDED:

Here's an example of what I am finding.  In it, you can see how it is referred to as storing the "Primary Key".  What confuses me is that the field I am wanting to reference is not my primary key - so, how can I set my primary key to "MemberID" and yet have reference to another key called "UserID"?

The DataGrid control contains a DataKeyField property. This optional property can be used to specify the primary key field for the data being displayed in the DataGrid. If this property is set, a separate DataGrid property, DataKeys (a collection), is populated with the primary key values for each row in the DataGrid. Hence, we can access this collection programmatically in our DeleteCommand event handler. To get the proper item out of the DataKeys collection, we simply reference the index that is equal to the clicked DataGrid row's ItemIndex. This concept is illustrated below:

LAST ADD:  After some more research, please tell me if I have this correct.  If you want to use DataKeys at all, you set the DataKeyField to a value which will be the primary key(s).  Once you set that then a DataKey collection is created (here is my guess) that contains *all* the fields in the datasource - you the user, simply have to choose the correct one?  I guess what my hangup was/is is that The "DataKeyField" is set to something - how do you refer to a different field in the DataKey collection--AND--is only those fields you put in the DataKeyField in the DataKEy collection?

Reply By: Imar Reply Date: 7/1/2008 7:01:52 AM
Check out the MSDN documentation:

http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.basedatalist_properties.aspx

It's all in there....

Imar


---------------------------------------
Imar Spaanjaars
http://Imar.Spaanjaars.Com
Everyone is unique, except for me.
Author of Beginning ASP.NET 3.5 : in C# and VB, ASP.NET 2.0 Instant Results and Dreamweaver MX 2004
Want to be my colleague? Then check out this post.
Reply By: rsearing Reply Date: 7/1/2008 8:25:42 AM
I am really not trying to appear negative...but I have tried everything you are telling me to.  Right now, I just feel very stupid.  The link you provided, and the one prior (with MSDN) only shows "one" value in the DataKeyField example.  They do not show multiple DataKeys being used in any of their examples.  This is literally driving me buggy.  *everything* I read says that the DataKeyField is for the primary key - but I keep seeing that "DataKey"s can store more than one value--with no example.  What I don't understand is...

a)  How do you set, and then reference in code behind, multiple Data Keys?
b)  If you use multiple DataKeys - then how does the control know which one is the "primary key" in case you want to do updates/deletes, etc.

Really, I'm trying to simply be able to reference things like UserID, in addition to the primary key, memberID - without breaking the control's understanding that memberID is the primary key.


Reply By: Imar Reply Date: 7/1/2008 10:27:17 AM
Negative?

Anyway, I think you abusing the keys. The idea to use multiple keys is for a multi column key. There are a couple of solutions:

1. As I hinted earlier, simply store the UserId in a hidden column (on a Label for example) and retrieve it later.

2. Get the *key* Id from the database, make a call to the database to convert your own ID into the Membership ID and work from there.

3. Don't use your own ID, but make the Membership UserId the primary key of your table.

4. Just specify multiple keys; that shouldn't be a problem as .NET will do something like

Jadajadajadajada where Id = @id AND UserId = @userId

which should still result in the right record.

Personally, I prefer option 3, as it's the most natural thing to do: give your own table a proper key.....

And did you try Google:

http://www.google.com/search?hl=en&safe=off&q=DataList+%22DataKeys%22

results in:

http://msconline.maconstate.edu/tutorials/ASPNET1/ASPNET11/aspnet11-06.aspx
http://www.experts-exchange.com/Programming/Languages/.NET/ASP.NET/Q_23473159.html
http://www.pcreview.co.uk/forums/thread-1291942.php


Imar


---------------------------------------
Imar Spaanjaars
http://Imar.Spaanjaars.Com
Everyone is unique, except for me.
Author of Beginning ASP.NET 3.5 : in C# and VB, ASP.NET 2.0 Instant Results and Dreamweaver MX 2004
Want to be my colleague? Then check out this post.
Reply By: rsearing Reply Date: 7/1/2008 12:10:30 PM
Imar,

THANK YOU!!

Yes, I did try various Google searches and MSDN.  I guess the entire reason I was confused is because I always understood DataKeys to represent your primary key - it was your comment above about using it to get to the "non primary key" "userID" field that confused me - it made me think that you could use it for other purposes (such as simply wanting access to it without tying it to a control).

You are right - I originally thought about tying the memberID to the userID from the membership table - but ran into problems assimilating it into your 3-tier model because of it being a GUID (I'm sure I could find work-arounds - it just seemed easier to create my own key).

At the end of the day, I just wish there was an easier way to tie to fields rather than binding them to hidden fields - only to make it easier to work with them in code - behind pages so that ... for example, if I wanted to get access to the "IsApproved" Boolean in the MembershipTable--right now, it's bound to a hidden field and I have to reference it that way.

Again - was only thrown off because I misunderstood your suggestion above (using DataKeys) was a solution to getting to these fields.

I *really* appreciate your help!
Sincerely,
Rob

Reply By: planoie Reply Date: 7/1/2008 1:45:28 PM
Rob,

I would dissagree a bit with Imar about "abusing the keys".  The repeating controls that have the DataKeys field don't really care what the meaning of the data is.  The property is simply there so you can store needed data without having to put it into the control (i.e. in the form or a hidden column, hidden field, etc.).  I would say that it is perfectly OK to put multiple columns, possibly unrelated or non-key columns in there.  It won't break anything.  You just need to know how to use the data on the other side of a postback.  If you have one or more columns worth of data as the actual row key (simple or compound key) as well as other data, the control won't care.  You can use the key value(s) for database query filter criteria and use the others values for whatever.

What problems did you have "assimilating" the userID guid with the multi layer approach?  A Guid type isn't any less portable than any other "simple" row key type such as an int.  Was the problem simply with the way Guids can be treated as strings?

-Peter
compiledthoughts.com
Reply By: rsearing Reply Date: 7/1/2008 5:25:03 PM
Peter,

Wow--sorta confused now - but it's completely because I don't understand how DataKeys works--and, contrary to popular belief - I have done quite a bit of research - more than the several links Imar put - but none of them give examples of using more than one DataKeyField.

So---here's where my confusion stems from--really in not knowing how things work in the "black box"

a)  When you set a DataKeyField--"somehow" when you do updates or deletes, the control knows to pass the value you put in the DataKeyField in for the primary key.  So--my first question is--will that get screwed up if you have more than one datakeyfield.
b)  How do you reference the other datakey in the behind the scenes page..for example:

Dim someVariable = DetailsView.datakey(e.itemindex)
(not at my development computer, so I know I butchered that--but if I have two datakeyfields, how do I reference one from the other in the code behind?  Again-I have been unable to find examples.

Really--at the end of the day--all I want to know how to do is reference fields that are returned from my object without having to bind them to a control (hidden or otherwise).  I'd like an example of how to do this - using more than one datakey.  Secondly, will having more than one datakeyfield mess with the fact that all websites - MSDN - google, etc - say that the datakeyfield is for the primary key-will the control's update/delete behavior be screwed up?


Sorry to belabor this point - but it's just one thing that I never did fully understand and all the research I have done online doesn't really attest to how it works--they simply give easy examples showing one datakeyfield and they *all* just reference one field.

Thanks Peter
Rob

Reply By: Imar Reply Date: 7/2/2008 12:55:44 PM
Hi Peter,

I agree with you, you can use the DataKeys for items that are not necessarily part of the primary key. My bad.

Rob: that is so easy to find out once you know where to look:

1. Add a GridView to your page

2. Hook it up to a SqlDataSource that supports editing

3. Hook into the GridView1_RowUpdating event.

4. Set a breakpoint in the (possibly) empty handler for GridView1_RowUpdating

5. Run the page, edit a record and choose Update.

6. The breakpoint will be hit.

7. Add the following to your Watch window:

GridView1.DataKeys[e.RowIndex]

8. Notice how that results in an object of type System.Web.UI.WebControls.DataKey

9. Change the code in the Watch window so it casts the DataKeys to a DataKey:

((System.Web.UI.WebControls.DataKey) GridView1.DataKeys[e.RowIndex])

10. Notice how this object now has a Values collection. Expand it and you'll see what it contains.

11. Manually add a Watch for:

((System.Web.UI.WebControls.DataKey) GridView1.DataKeys[e.RowIndex]).Values[0]
((System.Web.UI.WebControls.DataKey) GridView1.DataKeys[e.RowIndex]).Values[1]

Notice how [0] and [1] contain the values for your first and second DataKey fields.

Hope this helps,

Imar


---------------------------------------
Imar Spaanjaars
http://Imar.Spaanjaars.Com
Everyone is unique, except for me.
Author of Beginning ASP.NET 3.5 : in C# and VB, ASP.NET 2.0 Instant Results and Dreamweaver MX 2004
Want to be my colleague? Then check out this post.
Reply By: rsearing Reply Date: 7/2/2008 1:30:32 PM
Imar,

A couple things with this - and not sure if this matters, but I am using a DataList.

a)  When i try, in the control, putting DataKeyField="memberID,userID" as a property and then run the app, I get an error that says "Databinding:  "Namepace.Bo.Member" does not contain a property with the name 'memberID,userID'--so I'm getting stuck simply by trying to assign it in the control
b)  In the code behind, when I try typing (keep in mind I'm using VB-again, not sure if matters) : DataList1.DataKeys(e.item.itemindex) it doesn't give me intellisense to put another "." to reference another array.
c)  If I use multiple keys will the control still work--the reason I ask this is my experience in the past was that you set up the datakeyfield to that which is your primary key and then updates/deletes magically work (again, I don't understand what is happening in the black box).

I am genuinely trying everything you're telling me to do - just not getting the same results.

Reply By: Imar Reply Date: 7/2/2008 1:36:21 PM
Don't use DataKeyField, use DataKeys instead.

In VB, use CType like you normally would to do a proper cast like this:

(CType(GridView1.DataKeys(e.RowIndex), System.Web.UI.WebControls.DataKey)

and

(CType(GridView1.DataKeys(e.RowIndex), System.Web.UI.WebControls.DataKey).Values

You won't get IntelliSense with a proper cast; sometimes you need to think for yourself and not purely reply on IntelliSense.... ;-)

Do yourself a favor: try this with a simple SqlDataSource first (you weren;t doing exactly as I was telling you ;-0 ) so you understand the concepts. Then move on to an ObjectDataSurce.

Cheers,

Imar

---------------------------------------
Imar Spaanjaars
http://Imar.Spaanjaars.Com
Everyone is unique, except for me.
Author of Beginning ASP.NET 3.5 : in C# and VB, ASP.NET 2.0 Instant Results and Dreamweaver MX 2004
Want to be my colleague? Then check out this post.
Reply By: rsearing Reply Date: 7/2/2008 1:48:02 PM
Imar,

Man--I am certainly not trying to annoy - and I am feeling very stupid here..but, please keep in mind this is a DataList (not sure if that matters).  In the control itself (ie <asp:Datalist ID="DataList1.... /> "DataKeys" is not a property - only DataKeyField.  When I do:

<asp:DataList id="DataList1" runat="server" .... DataKeyField="memberID,userID">  I get the error I mentioned.  So I can't even get to the point of referring to it in code behind.



Reply By: Imar Reply Date: 7/2/2008 2:30:49 PM
Can you please stop apologizing for everything you say or do and stop feeling stupid? It's starting to look quite silly. If I thought for a split second you'd be annoying me on purpose, I'd simply stop answering your questions. So, as long as you keep getting replies you're pretty safe. And if you say sorry for apologizing, I am outta here.

Anyway, to understand the concepts, follow my steps. My steps say to use a GridView, not a DataList. Once you understand the concepts and the basics, move on.

One direction to move on is to use a ListView instead of a DataList as it supports multiple keys using DataKeyNames (sorry I didn't make that clearer earlier). The ListView not really replaces the DataList officially, but in many respects offers a lot more functionality.

You can use DataKeyNames for the comma separated list of fields. The rest of the code is pretty much the same:

<asp:ListView ID="ListView1" runat="server" DataKeyNames="Col1, Col2" DataSourceID="SqlDataSource1" ...>

Debugging in code behind for ItemEditing:

((System.Web.UI.WebControls.DataKey) ListView1.DataKeys[e.NewEditIndex]).Values[0]
((System.Web.UI.WebControls.DataKey) ListView1.DataKeys[e.NewEditIndex]).Values[1]

Hope this helps,

Imar

---------------------------------------
Imar Spaanjaars
http://Imar.Spaanjaars.Com
Everyone is unique, except for me.
Author of Beginning ASP.NET 3.5 : in C# and VB, ASP.NET 2.0 Instant Results and Dreamweaver MX 2004
Want to be my colleague? Then check out this post.
Reply By: rsearing Reply Date: 7/2/2008 6:56:19 PM
Imar,

Understand on the apology.

I just ran your example with a GridView - and I see it working - and it works fine.  In fact, all of the examples in MSDN and Google show Gridview.  My entire problem is/was that I am using a DataList - and the syntax isn't the same.  Datalist uses "DataKeyField" as a property of the control on the regular .aspx page.  Whenever I put a comma-seperated list (ex. "DataKeyField='memberID, userID'") I get the error "DataBinding: 'Searing.Sprint.CustomerAdvocacy.BO.Member' does not contain a property with the name 'memberID, userId'."  Consequently, when I leave it with one and simply try referring to it in the codebehind page in the DataList1_ItemCommand function, it doesn't appear as if multiple DataKeys are supported - all I can do is DataList1.DataKeys(e.item.itemindex) - and have played around with it to see if there is a way to support a multi-dimension array - you can't.

So - it appears - that DataList doesn't support multiple keys - which is what I was asking all along.

Added to that is my confusion (and I can't for the life of me remember what) as to the purpose of the DataKeyField (DataKeyName) when you leave it alone for use as a Primary Key - I think it was so that, if selected, it refered to the DataKey as the value?  I don't know - whatever the reason (as I'm confused right now) I didn't know if multiple keys in the DataKeyNames would mess up this relationship.

I'm just going to drop this and just use the HiddenField that's working - was simply trying to get away from binding to controls in a DataList - doesn't seem like I can do that with a DataList - must use GridView or ListView.

Thanks,
Rob

Reply By: rsearing Reply Date: 7/2/2008 9:24:43 PM
Ok, perhaps this might help me out.  I followed Imar's example - using  a GridView and a simple SQLDataSource to tie to my Member Table.  When I have the property in the GridView of DataKeyNames="memberID,userID" it works (updates) however, when I remove it - I get an error "Implicit conversion from data type sql_variant to uniqueidentifier is not allowed. Use the CONVERT function to run this query." (when attempting an update).  When attempting a Delete I get "Must declare the scalar variable "@memberID". "

(**Even more confusing is that when I put multiple values in the DataKeyNames field - it pulls out the right one for the SQL statement...thoroughly confused on how this is all working)

Below is my code.  

So my question then is:

a)  Why am I getting that error
b)  This is a *perfect* example of where messing with DataKeyNames messes with the simple update or delete - I guess I'm confused on how the 'black box' works to pass parameters--you have <asp:parameters> in the update that somehow find their values - except for the one being used for primary key?


<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
     DataSourceID="SqlDataSource1">
        <Columns>
            <asp:CommandField ShowEditButton="True" ShowSelectButton="True"
                ShowDeleteButton="True" />
            <asp:BoundField DataField="memberID" HeaderText="memberID"
                InsertVisible="False" ReadOnly="True" SortExpression="memberID" />
            <asp:BoundField DataField="userID" HeaderText="userID"
                SortExpression="userID" />
            <asp:BoundField DataField="fName" HeaderText="fName" SortExpression="fName" />
            <asp:BoundField DataField="lName" HeaderText="lName" SortExpression="lName" />
            <asp:BoundField DataField="phone" HeaderText="phone" SortExpression="phone" />
            <asp:BoundField DataField="mobPhone" HeaderText="mobPhone"
                SortExpression="mobPhone" />
            <asp:BoundField DataField="workLocationID" HeaderText="workLocationID"
                SortExpression="workLocationID" />
            <asp:BoundField DataField="positionID" HeaderText="positionID"
                SortExpression="positionID" />
        </Columns>
    </asp:GridView>
    <asp:SqlDataSource ID="SqlDataSource1" runat="server"
    ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
    
        SelectCommand="SELECT [memberID], [userID], [fName], [lName], [phone], [mobPhone], [workLocationID], [positionID] FROM [Members]"
        DeleteCommand="DELETE FROM [Members] WHERE [memberID] = @memberID"
        InsertCommand="INSERT INTO [Members] ([userID], [fName], [lName], [phone], [mobPhone], [workLocationID], [positionID]) VALUES (@userID, @fName, @lName, @phone, @mobPhone, @workLocationID, @positionID)"
        UpdateCommand="UPDATE [Members] SET [userID] = @userID, [fName] = @fName, [lName] = @lName, [phone] = @phone, [mobPhone] = @mobPhone, [workLocationID] = @workLocationID, [positionID] = @positionID WHERE [memberID] = @memberID">
        <DeleteParameters>
            <asp:Parameter Name="memberID" Type="Int32" />
        </DeleteParameters>
        <UpdateParameters>
            <asp:Parameter Name="userID" Type="Object" />
            <asp:Parameter Name="fName" Type="String" />
            <asp:Parameter Name="lName" Type="String" />
            <asp:Parameter Name="phone" Type="String" />
            <asp:Parameter Name="mobPhone" Type="String" />
            <asp:Parameter Name="workLocationID" Type="Int32" />
            <asp:Parameter Name="positionID" Type="Int32" />
            <asp:Parameter Name="memberID" Type="Int32" />
        </UpdateParameters>
        <InsertParameters>
            <asp:Parameter Name="userID" Type="Object" />
            <asp:Parameter Name="fName" Type="String" />
            <asp:Parameter Name="lName" Type="String" />
            <asp:Parameter Name="phone" Type="String" />
            <asp:Parameter Name="mobPhone" Type="String" />
            <asp:Parameter Name="workLocationID" Type="Int32" />
            <asp:Parameter Name="positionID" Type="Int32" />
        </InsertParameters>
    </asp:SqlDataSource>

Reply By: rsearing Reply Date: 7/2/2008 9:54:10 PM
I'm not the only one that gets confused with the relationship of DataKeyField/Names and the values:

http://forums.asp.net/p/1269097/2393266.aspx#2393266

What is confusing is on my Gridview (code above) I do have a memberID bound column - so why would I need to put "memberID" in the DataKeyNames field?  

<asp:BoundField DataField="memberID" HeaderText="memberID"
                InsertVisible="False" ReadOnly="True" SortExpression="memberID" />

This wouldn't be so bad if people didn't explain this so many different ways.  It's said that DataKeyNames is used for primary key - but then threads say you can use it for any field that you don't want bound - but then my control has the field bound and won't work without the DataKeyName....




Reply By: Imar Reply Date: 7/3/2008 4:31:17 AM
To reiterate my previous post: you are using a control that doesn't support this.

In .NET 1.x there was the DataGrid and the DataList, both supporting single keys. In .NET the GridView was introduced to replace the DataGrid. The GridView offers a much better technical design than the DataGrid.

Now with .NET 3.5 you have the ListView. Just as the GridView is a better alternative to the DataGrid, the ListView is better than the DataList. For example, it supports multiple keys using the DataKeyNames property and offers superior support for editing and displaying of data.

So, do yourself a favor: ditch the DataList and use a ListView instead. You'll find that the way it works is very similar to the DataList. I don't think you can do what you want to do with the DataList, unless you use other techniques described earlier.
quote:
This wouldn't be so bad if people didn't explain this so many different ways.
Ask someone for the road to Rome; you'll get as many different answers :-) That's part of the programming deal you need to get used to. There are many different controls, different properties, different ways to handle them, different versions of the .NET Framework, different views on the matter, different programming languages, different preferences, and many, many different ways to accomplish the same thing.

The cure is: Google till your fingers are sore, use the debugger, read, read, read and read some more, debug some more, and then choose something that works for you. Don't keep saying things like "I don't understand it because it's not in my book" There are a zillion things that are not in your book. However, they are available on Google, and right there, in your face, in the Debugger and Watch window. Learn to use these tools, learn how to use the MSDN documentation site, learn how to use Google, and you'll be a much better programmer .... ;-)

Cheers,

Imar


---------------------------------------
Imar Spaanjaars
http://Imar.Spaanjaars.Com
Everyone is unique, except for me.
Author of Beginning ASP.NET 3.5 : in C# and VB, ASP.NET 2.0 Instant Results and Dreamweaver MX 2004
Want to be my colleague? Then check out this post.
Reply By: rsearing Reply Date: 7/3/2008 10:20:35 AM
Imar,

I appreciate your comments.  Trust me, I have spent many hours on researching this - both Google, Metacrawler, MSDN - and actually finally realized that the DataList doesn't support multiple keys.

What I am failing to explain is that the question had a twist in really understanding "how" datakeys work-has nothing to do with the DataList vs GridView vs List--much broader.  *All* of the research I have done simply states "set the primary key as your DataKeyName/Field" - but doesn't explain what is going on behind the scenes.

The reason this confuses me is that in the simple example you had me do (with SQLDataSource and Gridview) - I made *no* changes.  It displays all the fields from my table and has "bound fields" for them - so, in the control, you have a boundfield for my primary key, "memberID".  At the same time, you have bound fields for all the remaining fields.

NOW - I also have the <asp:parameters> in the Delete, Update and Select Commands that has *all* the parameters - thus I have a "memberID" parameter.

So - how does DataKey work is really my question - and I can't seem to find an article that explains it.  What I have read is that you can use DataKey if you don't want to bind to a control within your List or GridView, etc.  So, having said that, why does the GridView fail when I remove the DataKeyName property--EVEN THOUGH I have a boundfield for memberID - and a Parameter for memberID.

Regardless of what control I use - I am having difficulty understanding simply - how DataKeys work--what they are doing.  All the stuff I have read simply states to set the datakey as the primary key - without explaining the "why" you are doing that.

I am trying to understand this to see if I could simply put all my table fields in the datakey without actually binding them to a control - and then refer to them in codebehind and set them all up myself - and what impact that would have.

Sincerely,
Rob

Reply By: rsearing Reply Date: 7/3/2008 11:14:31 AM
Ok...I **THINK** I might have my answer - and I also think my confusion was stemming from various things happening at one time tha weren't related.

If someone could please confirm / deny my statements, I'll be able to move on.

a)  If you simply use a SqlDataSource and a control (ListView, GridView, etc) then DataKeyName/Field has *NO* impact.  This is because the SqlDataSource has "update" commands and parameters that does all the transferring of fields to parameters.
b)  The DataKeyName/Field property really comes into play when you are wanting to tie to it in codebehind - for example, if you want to tie into a "Select" command and do something with the primary key - at which time you would reference the correct DataKey parameter and do with it as you will.
c)  DataKeyName is sorta like the "SelectedValue" of a dropdown.  You can store as many fields as the control will allow - and then simply refer to them as you will in the code behind.

Sincerely,
Rob

Reply By: Imar Reply Date: 7/4/2008 2:00:58 AM
1) Yes

2) Yes

3) No, not really. DataKeyName only contains the name of the key. .NET uses this to understand what columns to keep track of. The actual key values are stored in the DataKeys property.

If you really want to understand the *why*, download a tool called Reflector. It allows you to look into the ASP.NET assemblies, so you can dismantle the DataList control and look at its internal behavior.

Alternatively, you could choose to debug into the .NET Framework: http://weblogs.asp.net/scottgu/archive/2007/10/03/releasing-the-source-code-for-the-net-framework-libraries.aspx

Cheers,

Imar

---------------------------------------
Imar Spaanjaars
http://Imar.Spaanjaars.Com
Everyone is unique, except for me.
Author of Beginning ASP.NET 3.5 : in C# and VB, ASP.NET 2.0 Instant Results and Dreamweaver MX 2004
Want to be my colleague? Then check out this post.
Reply By: rsearing Reply Date: 7/4/2008 11:41:47 AM
*THANK YOU*  makes much more sense now!!


Go to topic 72483

Return to index page 1