按所选项设置DropDownList值

时间:2013-07-24 19:11:57

标签: c# asp.net

我是asp.net和c#的新手。我正在尝试在下拉列表框中设置文本以显示当前页面标题,但我无法使其工作。有人可以根据下面的代码建议如何做到这一点吗?谢谢!

    if (!Page.IsPostBack)
    {
        string path = @"C:\Websites\TaxMapCS";
        DirectoryInfo di = new DirectoryInfo(path);
        FileSystemInfo[] fi = di.GetFiles("*.aspx");
        var result = string.Join(",", fi.OrderByDescending(f => f.CreationTime).Select(i => i.ToString()).ToArray());

        DropDownList1.DataSource = result.Replace(".aspx", "").Split(',');

        DropDownList1.DataBind();

        DropDownList1.Items.Insert(0, new ListItem("Select Edition", ""));

    }
}

protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
    Response.Redirect(DropDownList1.SelectedItem.Value + ".aspx");
}

4 个答案:

答案 0 :(得分:2)

试试这个

protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
    Response.Redirect(DropDownList1.SelectedItem.Text + ".aspx");
}

或者

protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
    Response.Redirect(DropDownList1.SelectedValue + ".aspx");
}

答案 1 :(得分:0)

我不确定ASP.NET,但在常规C#中,我认为你可以尝试这样的事情:

DropDownList1.Items.Add(this.Page.Title);

感谢Cubicle.Jockey帮助我修改代码。

答案 2 :(得分:0)

您不需要拆分和连接字符串。相反,您可以将单个ListItem添加到DropDownList。

<asp:DropDownList runat="server" ID="DropDownList1" AutoPostBack="True" 
    OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged" />

protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
    {
        string path = @"C:\DevelopmentArchive\TelerikDemo\TelerikDemo";
        DirectoryInfo di = new DirectoryInfo(path);
        FileInfo[] files = di.GetFiles("*.aspx");

        foreach (var file in files.OrderByDescending(f => f.CreationTime))
            DropDownList1.Items.Add(new ListItem(file.Name.Replace(".aspx", ""), file.Name));

        DropDownList1.Items.Insert(0, new ListItem("Select Edition", ""));
    }
}

protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
    Response.Redirect(DropDownList1.SelectedItem.Value);
}

答案 3 :(得分:0)

试试这个:

if (!Page.IsPostBack)
    {
        string path = @"C:\Websites\TaxMapCS";
        DirectoryInfo di = new DirectoryInfo(path);
        FileSystemInfo[] fi = di.GetFiles("*.aspx");
        var result = string.Join(",", fi.OrderByDescending(f => f.CreationTime).Select(i => i.ToString()).ToArray());

        DropDownList1.DataSource = result.Replace(".aspx", "").Split(',');

        DropDownList1.DataBind();

        DropDownList1.Items.Insert(0, new ListItem("Select Edition", ""));
        DropDownList1.Items.Insert(0, new ListItem(Page.Title, ""));

    }
}


    protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
    {
        if(DropDownList1.SelectedIndex > 0)//do not redirect if 'Selected Edition' is selected
        {
            Response.Redirect(DropDownList1.SelectedItem.Text + ".aspx");
        }
    }