编写一个 asp.net 文件管理器。
本质上,用户单击 TreeView 控件中的文件夹,该文件夹中的文件显示在 ListView 控件中。
ListView
<asp:listview id="lvFiles" runat="server" onitemdeleting="lvFiles_ItemDeleting"
onselectedindexchanging="lvFiles_SelectedIndexChanging">
<layouttemplate>
<table cellpadding="2" width="520px" border="1" id="tbl1" runat="server">
<tr id="Tr1" runat="server" style="background-color: #98FB98">
<th id="Th0" runat="server"></th>
<th id="Th1" runat="server">Filename</th>
<th id="Th2" runat="server">Uploaded</th>
<th id="Th3" runat="server">Last Accessed</th>
</tr>
<tr runat="server" id="itemPlaceholder" />
</table>
<asp:datapager id="DataPager1" runat="server" pagesize="25">
<fields>
<asp:nextpreviouspagerfield buttontype="Button" />
</fields>
</asp:datapager>
</layouttemplate>
<emptyitemtemplate>
<p>No items</p>
</emptyitemtemplate>
<itemtemplate>
<tr runat="server">
<td><asp:linkbutton id="itemSelected" runat="server" tooltip='<%# Eval("FullName") %>' autopostback="True" commandname="select" text="Select" />
</td>
<td><asp:label id="fNameLabel" runat="server" text='<%# Eval("Name") %>'></asp:label>
</td>
</tr>
</itemtemplate>
<selecteditemtemplate>
<tr id="Tr2" runat="server">
<td>Selected</td>
<td><asp:label id="fNameLabel" runat="server" text='<%# Eval("Name") %>'></asp:label>
</td>
<td><asp:button id="btnDelete" runat="server" text="Delete" commandname="Delete"></asp:button>
</td>
</tr>
</selecteditemtemplate>
</asp:listview>
绑定(bind)文件列表
所以目前发生的事情是在 TreeView_SelectedNodeChanged
事件中,应用程序获取由 TreeNode
表示的 DirectoryInfo
对象并获取一个数组FileInfo
对象,使用 DirectoryInfo.GetFiles()
方法。
FileInfo[]
被传递给下面的方法。
protected void AddFilesToViewPort(FileInfo[] Files)
{
List<FileInfo> fList = new List<FileInfo>();
for (int i = 0; i < Files.Length; i++)
{
fList.Add(Files[i]);
}
lvFiles.DataSource = fList;
lvFiles.DataBind();
upExistingFiles.Update();
}
它将 FileInfo[]
绑定(bind)到 ListView
对象 lvFiles
,这正是我想要的。
我想要做的是能够在 ListView 中选择一个项目(目前可以完成),然后当用户按下 Delete
按钮时,我希望应用程序可以使用有问题的文件。本质上,我想将文件移动到“已删除文件”目录并将操作记录在数据库中。
我遇到的问题是获取与我选择的列表项关联的实际 FileInfo
对象。
如果我将调试器附加到 并单步执行,lvFiles_ItemDeleting
事件将触发,并且我将获得所选 ListItem
的索引,但是当我在调试器中检查对象时,ListItem
所代表的对象的实际信息并不存在。
如您在上图中所见,ListView
的 DataKeys 属性包含有关其项目的一些信息,但当我深入研究该属性时,这些信息并不存在。
如何从选定的 ListViewItem
中获取 FileInfo
对象?
最佳答案
看看这是否回答了您的问题:
ListViewDataItem item = lvFiles.Items[e.ItemIndex];
FileInfo fInfo = (FileInfo)item.DataItem;
您还需要指定要传递到 ListView 中的 DataKeyNames。类似于:
<asp:listview DataKeyNames="FullName, Name" id="lvFiles" runat="server" onitemdeleting="lvFiles_ItemDeleting" onselectedindexchanging="lvFiles_SelectedIndexChanging">. read more about it [here][1]
关于c# - 使用 ListView 访问 Select 上的数据项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13046719/