如何从 ASP.NET 2 中的 ItemTemplate 中的 gridview 获取数据
我有一个网格视图,其中每列都有两个模板字段。一个是 ItemTemplate,另一个是 EditItemTemplate。现在在 EditItemTemplate 中它将显示一些文本框,我可以在其中执行必要的编辑。我可以使用以下代码轻松地从每个单元格获取数据 -
Dim gvRow As GridViewRow = gvView.Rows(e.RowIndex)
CType(gvRow.FindControl("controlID"), TextBox).Text
但是当网格视图未处于 ItemTemplate 中的编辑模式时,如何获取数据。我已尝试以下操作 -
Dim rowView As DataRowView = CType(gvRow.DataItem, DataRowView)
Dim something As String = rowView("data_field").ToString()
但其获取异常对象引用未设置为对象的实例。发生这种情况可能是因为当实例化一行时,上面的代码应该在像 RowDataBound 这样的方法中使用。但我必须从其他方法获取数据。知道如何做到这一点。
再次澄清一下,我想在 gridview 列处于 ItemTemplate 模式时获取数据。
I have a gridview where each columns have two template fields. One is ItemTemplate and another is EditItemTemplate. Now in EditItemTemplate it will show some textboxes where i can perform necessary editing. I can easily fetch data from each cell by using the following code-
Dim gvRow As GridViewRow = gvView.Rows(e.RowIndex)
CType(gvRow.FindControl("controlID"), TextBox).Text
But how can i fetch data when the grid view is not in editing mode that is in ItemTemplate. I have tried the following-
Dim rowView As DataRowView = CType(gvRow.DataItem, DataRowView)
Dim something As String = rowView("data_field").ToString()
But its getting the exception object reference is not set to an instance of object. This is probably happening because the above code should be used in a method like RowDataBound when a row is instantiated. But I have to fetch data from some other method. Any idea how to do this.
Again for clarification I want to fetch data when the gridview columns are in ItemTemplate Mode.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我想您想在某些命令中读取网格视图列的值。如果您有
gvRow
这是 gridview 的行,那么您可以使用.Cell(index).Text
来获取列的值。如果您使用模板字段并使用某些控件来显示列数据,则必须执行
gvRow.findControl("controlId")
,然后将其转换为适当的控件对象以从中读取数据。快乐编码
I guess you want to read value of grid view column in some command. If you have
gvRow
which is your gridview's row then you can use.Cell(index).Text
in order to get value of the column.If you are using template field and using some controls to show column data, you have to do
gvRow.findControl("controlId")
and then cast it to appropriate control object to read data from it.Happy coding
您可以考虑直接访问gridview数据源。如果您允许在网格上排序/分页,则执行此操作时要小心,因为数据源的索引会有所不同。
You may consider accessing the gridview datasource directly. Be careful when doing this if you allow sorting / paging on the grid as the index into your datasource will differ.
两个答案效果很好,非常感谢。
我花了更多时间尝试获取 GridView 单元格值,但毫无用处,我不知道问题是什么。当我阅读您的答案时,我发现我的 GridView 有模板字段,这就是问题所在。
Two answers worked fine thank you very much.
I spent more time trying to get the GridView Cell value but useless I could not Know what is the problem. When I read your answer I found that my GridView has template fields so that was the problem.