C# – If DataKeyNames is set to a field not defined as a primary key, then…

asp.netcdata-bindinggridview

1) I noticed that if I set GridView.DataKeyNames to a field that actually isn’t defined as primary key in data source, data source control ( or perhaps GridView?) will somehow know that field set in DataKeyNames isn’t really a primary key. I became aware of that fact when I opened Configure the Select Statement window ( via GridView’s Smart Tasks pop up –> Configure Data Source –> Configure the Select Statement window –> Advanced) and window had both radio buttons disabled.

a) So how did Asp.Net “figure it out” that field set in DataKeyNames is not actually a primary key?

b) Also, shouldn’t it be up to programmer to set DataKeyNames to whatever field she chooses to, even if that field is not defined as primary key in a data source?

thanx

Best Answer

Well, the purpose of the DataKeyNames property is to uniquely identify each and every data row in your data set. For that, ASP.NET needs to make 100% sure it's really truly a uniquely identifying column (or set of columns) that you provide, and the only one that can be truly checked is the primary key of a table - this will always be uniquely identifying a row (that's the very definition of a primary key).

I guess that's the reason that ASP.NET insists on the primary key for the DataKeyNames - any other column (or set of columns) can't really be checked for validity - so it's better to refuse them rather than running into the problems if it's not a uniquely identifying key.....

Marc