Get database ID from a row in ListView in ASP.NET

2019-09-02 07:28发布

问题:

I have a ListView in ASP.NET where one column contains CheckBox. In order to get the database updated when the users change click them, I use OnCheckedChanged. But how do I know which record in the database each checkbox is related to?

回答1:

You should set the DataKeys property to the string which represents the individual record ID.

Once you are in the Item Data Bound event you can then reference the ID value using;

DataKey currentDataKey = myListView.DataKeys[e.Item.DataItemIndex];

You then simply lookup your database record using the currentDataKey value.



回答2:

The CheckBox control has a Parent property, which should translate to the ListViewItem; if it doesn't, you can try a series of .Parent.Parent.etc and one of the parents will be the list box item.

HTH.