Link to home
Start Free TrialLog in
Avatar of WhyDidntItWork
WhyDidntItWork

asked on

How can I determine which table record I'm viewing in a detailsview?

Hi,

I'm using entity framework to connect to database tables.

I have bound a table to a detailsview.  How can I write code to find the record within the table that is currently displayed on the webpage?

Thanks

W
Avatar of Carl Tawn
Carl Tawn
Flag of United Kingdom of Great Britain and Northern Ireland image

If you have bound to a record with a key field, then you can use the DataKey.Value property of the DetailsView control to get the key of the current record:
int currentID = int.Parse(DetailsView1.DataKey.Value.ToString());

Open in new window

DataKey returns the primary key and DataItem property returns the record itself.

Also, please note that DataKey class has different properties returning objects to get the primary keys.
Avatar of WhyDidntItWork
WhyDidntItWork

ASKER

Hi Experts,

When the page is loaded, I use a linq query to bind the database table to the detailsview.

Based on the above comments, for test purposes, I added a label on the webpage and tried to write to it the datakey value.  I didn't get the expected result.  Instead, I got an "Object reference not set to an instance of an object" error.

Here is the code:
protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
            HCLEntities4 Context = new HCLEntities4();
                                             
            var query = from q in Context.Pes
                        where q.Pending != null
                        where q.Approver == null
                        select q;

            DetailsView.DataSource = query.ToList();
            DetailsView.DataBind();

            Label1.Text = DetailsView.DataKey.Value.ToString();    
            }
        }

Not sure why I'm getting the error.  Suggestions?

W
Try

Label1.Text = (DetailsView.DataItem as Pes).RowIdProperty.ToString();
I used SQL Server Management Studio to create the database table first.  One field in the table has been assigned as the primary key.

The table was then replicated as a model in Visual Studio.  The primary key field in the database model has a "key" icon beside it.
ASKER CERTIFIED SOLUTION
Avatar of Ravi Vaddadi
Ravi Vaddadi
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Thanks for helping me get from Point A to B.