选中asp.net列表框项

时间:2016-06-02 18:21:04

标签: asp.net listbox

在asp.net表单应用程序中,我想提供一个文档列表。该列表是手动填充的。我想点击一个项目(没有多选)并下载该项目。填充列表和下载工作正常。我的问题是使用什么控件。理想情况下我想使用Listview,但我无法弄清楚如何使用Click事件。如何将单击事件添加到Listview?或者是否有更好的控制使用?

1 个答案:

答案 0 :(得分:0)

这是一个完整的工作示例。只需按原样复制代码,并确保在解决方案中创建一个名为 FilesToDownload 的文件夹,并在其中删除一些示例文件以进行测试。

代码背后:

public partial class aaaaa_ListViewWIthDownload : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        var file1 = new MyFile { FileName="File 1", FilePath="~/FilesToDownload/File 1.txt" };
        var file2 = new MyFile { FileName = "File 2", FilePath = "~/FilesToDownload/File 2.txt" };
        var file3 = new MyFile { FileName = "File 3", FilePath = "~/FilesToDownload/File 3.txt" };

        var files = new List<MyFile>() { file1, file2, file3 };

        listViewFiles.DataSource = files;
        listViewFiles.DataBind();
    }

    protected void Unnamed_Click(object sender, EventArgs e)
    {
        LinkButton downloadButton = sender as LinkButton;
        if (downloadButton != null)
        {
            string filePath = downloadButton.CommandArgument;
            this.DownloadFile(filePath);
        }
    }

    private void DownloadFile(string filePath)
    {
        string fileName = new System.IO.DirectoryInfo(filePath).Name;

        System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
        response.ClearContent();
        response.Clear();
        response.ContentType = "text/plain";
        response.AddHeader("Content-Disposition","attachment; filename=" + fileName + ";");
        response.TransmitFile(Server.MapPath(filePath));
        response.Flush();
        response.End();
    }

}

public class MyFile
{
    public string FileName { get; set; }
    public string FilePath { get; set; }
}

<强> .ASPX:

<asp:ListView ID="listViewFiles" runat="server">
    <ItemTemplate>
        <table>
            <tr>
                <td>
                    <%# Eval("FileName")%>
                </td>
                <td>
                    <asp:LinkButton runat="server" Text="Download" OnClick="Unnamed_Click" CommandArgument='<%# Eval("FilePath")%>' />
                </td>
            </tr>
        </table>
    </ItemTemplate>
</asp:ListView>

<强>输出:

Downloading Files in ASP.NET web forms example