访问用于绑定GridView的数据或数据项 [英] Accessing the data or dataItem used to bind a gridview

查看:141
本文介绍了访问用于绑定GridView的数据或数据项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个gridview,我以编程方式设置数据源并将其绑定到一组对象。对于创建的每一行,我都会在字段中使用不同的方法来从对象中提取相关信息,如下所示:

  < asp:TemplateField HeaderText =别名> 
< ItemTemplate>
<%#((MyItem)Container.DataItem).Aliases.ToString()%>
< / ItemTemplate>
< / asp:TemplateField>

我的问题是,在OnRowDeleting方法中,我希望能够使用eg访问该DataItem MyGridView.Rows [e.RowIndex] .DataItem或以其他方式。但我找不到如何配置Gridview来保留DataItem。 是否可以访问使用的DataItem,以及如何配置它来完成它?如果这是不可能的,我可以访问通过方法绑定的值吗?或者我必须使用计划B并将数据源对象集合重写为数据表,然后使用datakeysnames?

解决方案

MyGridView.Rows [e.RowIndex] .DataItem 通常应该可以工作,但我想你可能依赖视图状态来保留网格数据。在这种情况下,您将获得 DataItem 属性为NULL。



解决方案可以始终在网页生命周期的早期每次回发中将网格与实际数据重新绑定(例如 page_load )。



然而,就你而言,你可以很好地使用 DataKeyNames 。与您的看法相反,您不需要DataTable就可以使用此属性。例如,如果你的类有一个名为 ItemId 的属性,表明你的对象的关键字,那么你可以使用 DataKeyNames =ItemId在标记中,并使用 OnRowDeleting 中引用它。 webcontrols.gridviewdeleteeventargs.keys.aspxrel =nofollow> Keys 属性的事件参数。

I have a gridview for which I programmatically set the datasource and databind it to a collection of objects. For each row that is created I then use different methods in the fields to extract the relevant information from the object like this one:

<asp:TemplateField HeaderText="Aliases">
<ItemTemplate>
<%# ( (MyItem)Container.DataItem).Aliases.ToString() %>
</ItemTemplate>
</asp:TemplateField>

My problem is that in the OnRowDeleting method I would preferably like to be able to access that DataItem using e g MyGridView.Rows[e.RowIndex].DataItem or in other way. But I can’t find how to configure the Gridview to retain the DataItem. Is this possible to access the DataItem used and how would I configure it to do it? If that’s not possible can I access the values that are bind by the methods? Or do I have to go with plan B and rewrite the datasource object collection to a datatable and then use datakeysnames?

解决方案

MyGridView.Rows[e.RowIndex].DataItem should generally work but I guess that you are probably relying the view-state for retaining grid data on post-backs. In such case, you will get the DataItem property as NULL.

Work-around can be to always re-bind the grid with actual data in each postback early in page life cycle (say page_load).

However, in your case, you can very well use DataKeyNames. Contrary to your belief, you don't need a DataTable for this property to work. For example, if your class has property named ItemId indicating the key for your object then you can use DataKeyNames="ItemId" in the markup and refer it in OnRowDeleting using Keys property of event arguments.

这篇关于访问用于绑定GridView的数据或数据项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆