迭代 ListView 数据
我有一个绑定到 DataTable 的 ListView。我想迭代 DataTable 的行并访问它们的数据。我想,要做到这一点,我只需迭代 ListView 中的 ListViewDataItems 即可。为了测试我是否正确访问数据,我尝试了以下代码,该代码应该简单地打印每行第 0 列的字符串。
for (int i = 0; i < MyListView.Items.Count; i++)
{
ListViewDataItem item = MyListView.Items[i];
DataRow row = (DataRow) item.DataItem;
Response.Write(row[0]);
}
但是,没有打印任何内容。为了验证 ListView 不为空(它不应该为空,因为数据在我的 aspx 页面上正确呈现),我尝试了以下操作:
Response.Write(MyListView.Items.Count);
这会打印数字 16,这是正确的,因为我的 ListView 中有 16 行。我猜我只是没有正确访问数据。我希望对此有一些见解。
I have a ListView which is bound to a DataTable. I would like to iterate over the DataTable's rows and access their data. I figured, to do this, I would simply iterate over the ListViewDataItems in the ListView. To test that I am properly accessing the data, I tried the following code, which should simply print the string at column 0 for each row.
for (int i = 0; i < MyListView.Items.Count; i++)
{
ListViewDataItem item = MyListView.Items[i];
DataRow row = (DataRow) item.DataItem;
Response.Write(row[0]);
}
However, nothing is printed. To verify that the ListView is not empty (which it shouldn't be as the data is properly rendered on my aspx page), I tried this:
Response.Write(MyListView.Items.Count);
This prints the number 16, which is correct as there are 16 rows in my ListView. I'm guessing I'm just not accessing the data correctly. I'd appreciate some insight on this.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
最好的方法是在断点处停止(在 DataRow row = (DataRow) item.DataItem; 行)并简单地检查您拥有的内容。
例如像这里:http://msdn.microsoft.com/en-us/library/ms173083(v=VS.90).aspx
The best way is to stop on breakpoint (at line DataRow row = (DataRow) item.DataItem;) and simply to check what you have .
for example like here :http://msdn.microsoft.com/en-us/library/ms173083(v=VS.90).aspx
我认为最好的解决方案是直接迭代
DataTable
中的数据,而不是 ListViewDataItems。I decided the best solution was to just iterate over the data directly in the
DataTable
rather than the ListViewDataItems.对于任何仍在寻求此问题正确答案的人,以下代码将起作用 (VB.NET):
只需将
Response.Write
行替换为您想要对每个列表项执行的操作即可。该示例行正在查找名为“ExampleLabel”的控件,将其转换回标签,然后将文本值写入页面。对于任何精通 C# 的人来说(唉,不是我),都可以轻松适应 C#。
For anyone still seeking the correct answer to this question, the following code will work (VB.NET):
Just substitute the
Response.Write
line with whatever you wanted to do to each list item. The example line is looking for a control called 'ExampleLabel', casts it back to a label then writes the text value onto the page.Easily adapted to C# for anyone proficient (not I alas).