按钮单击ASP.NET后,在编程创建的DropDownList中保留选定的值

时间:2018-05-18 11:05:12

标签: c# asp.net webforms

我创建了一个表单,我根据PDF中的表单字段添加下拉列表。

namesMapping变量是Dictionary,其中旧值为键,新值为值。要保存值,我想将当前选择添加到Dictionary但是eventlistener没有开火。

我在这里读过许多帖子,说使用IsPostBack变量来更新页面重新加载时的下拉列表。但在这种情况下它似乎不起作用。

感觉从下拉列表中获取所选值会更容易。但无论如何,如何保存下拉列表中的选定值,以便在点击按钮后获取它们?

以下是代码:

    protected void Page_Load(object sender, EventArgs e)
    {
        ListItem[] listItems = new ListItem[4];
        listItems[0] = new ListItem("First Name", "first-name");
        listItems[1] = new ListItem("Last Name", "last-name");
        listItems[2] = new ListItem("Email", "email");
        listItems[3] = new ListItem("Company", "company");

        int counter = 0;
        foreach (PdfField field in fields)
        {
            if (field.GetType() == typeof(PdfTextField))
            {
                TableRow tr = new TableRow();
                TableCell name = new TableCell
                {
                    Text = field.Name
                };
                tr.Cells.Add(name);
                TableCell options = new TableCell();

                DropDownList dropdown = new DropDownList();
                dropdown.ID = field.Name;
                for (int i = 0; i < listItems.Length; i++)
                {
                    dropdown.Items.Add(listItems[i]);
                }
                dropdown.SelectedIndexChanged += Dropdown_SelectedIndexChanged;

                options.Controls.Add(dropdown);
                tr.Cells.Add(options);
                Table1.Rows.Add(tr);

                //If page loads for the first time, set the mapping to the default selected values
                if (!IsPostBack)
                {
                    namesMapping.Add(field.Name, dropdown.SelectedValue);
                }
            }
        }

    private void Dropdown_SelectedIndexChanged(object sender, EventArgs e)
    {
        DropDownList dropDown = (DropDownList) sender;
        namesMapping[dropDown.ID] = dropDown.SelectedValue;
    }

感谢您的回答。

修改

我将创建下拉列表的代码移动到if(!IsPostBack)以内,以便在重新加载页面时不会重新创建它们。我将所有下拉列表保存在Dictionary中,但在下拉列表中选择另一个时,它们仍会显示第一个值。

以下是代码:

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            doc = new PdfDocument(pdfFileName);

            namesMapping = new Dictionary<string, string>();
            ddlMappings = new Dictionary<string, DropDownList>();

            //Get all fields
            fields = doc.Fields;

            //Create the dropdown lists
            dropdownLists = new List<DropDownList>();

            ListItem[] listItems = new ListItem[4];
            listItems[0] = new ListItem("First Name", "first-name");
            listItems[1] = new ListItem("Last Name", "last-name");
            listItems[2] = new ListItem("Email", "email");
            listItems[3] = new ListItem("Company", "company");

            int counter = 0;
            foreach (PdfField field in fields)
            {
                //Only display the text fields
                if (field.GetType() == typeof(PdfTextField))
                {
                    TableRow tr = new TableRow();
                    //Add the field name
                    TableCell name = new TableCell
                    {
                        Text = field.Name
                    };
                    tr.Cells.Add(name);
                    //Add the options to select from
                    TableCell options = new TableCell();

                    DropDownList dropdown = new DropDownList();
                    dropdown.ID = field.Name;

                    //Populate the dropdown
                    for (int i = 0; i < listItems.Length; i++)
                    {
                        dropdown.Items.Add(listItems[i]);
                    }

                    dropdown.AutoPostBack = true;
                    dropdown.SelectedIndexChanged += Dropdown_SelectedIndexChanged;

                    options.Controls.Add(dropdown);
                    tr.Cells.Add(options);
                    //Add row to table
                    Table1.Rows.Add(tr);

                    //If page loads for the first time, set the mapping to the default selected values
                    namesMapping.Add(field.Name, dropdown.SelectedValue);
                    ddlMappings.Add(field.Name, dropdown);
                }
            }

        }
        else
        {
            foreach (PdfField field in fields)
            {
                //Only display the text fields
                if (field.GetType() == typeof(PdfTextField))
                {
                    TableRow tr = new TableRow();
                    //Add the field name
                    TableCell name = new TableCell
                    {
                        Text = field.Name
                    };
                    tr.Cells.Add(name);
                    //Add the options to select from
                    TableCell options = new TableCell();

                    DropDownList dropdown = ddlMappings[field.Name];
                    dropdown.SelectedIndexChanged += Dropdown_SelectedIndexChanged;

                    options.Controls.Add(dropdown);
                    tr.Cells.Add(options);
                    //Add row to table
                    Table1.Rows.Add(tr);

                }
            }

        }

        if (!IsPostBack)
        {
            foreach(var ddl in ddlMappings)
            {
                ddl.Value.SelectedValue = namesMapping[ddl.Key];
            }
        }
    }


    private void Dropdown_SelectedIndexChanged(object sender, EventArgs e)
    {
        DropDownList dropDown = (DropDownList) sender;
        namesMapping[dropDown.ID] = dropDown.SelectedValue;
    }

2 个答案:

答案 0 :(得分:0)

如果你在Page_Load中进行数据绑定,那么你也会重置SelectedItem。

您应该在Page_Load块中添加if(!IsPostBack)中存在的绑定代码。

if(!Page.IsPostBack)
{

    // Your binding code here ...

}

以下是您进行绑定的代码示例...

 <form id="form1" runat="server">
<div>
    <asp:DropDownList ID="DropDownList1" runat="server" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged" AutoPostBack="true"></asp:DropDownList>
</div>
</form>
protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack) {
            Bind();
        }


    }


protected void Bind() {
        DataTable dt = new DataTable();
        DataColumn dc = new DataColumn("Name", typeof(string));
        DataColumn dc2 = new DataColumn("Path", typeof(string));


        dt.Columns.Add(dc);
        dt.Columns.Add(dc2);

        DataRow dr = dt.NewRow();
        dr["Name"] = "1";
        dr["Path"] = Server.MapPath("ProDinner1.pdf");

        DataRow dr2 = dt.NewRow();
        dr2["Name"] = "2";
        dr2["Path"] = Server.MapPath("ProDinner2.pdf");

        dt.Rows.Add(dr);
        dt.Rows.Add(dr2);

        DropDownList1.DataSource = dt;
        DropDownList1.DataTextField = "Name";
        DropDownList1.DataValueField = "Path";
        DropDownList1.DataBind();
    }

    protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
    {
        string path = DropDownList1.SelectedValue.ToString();
        Session["path"] = path;
        Response.Write("<script language=javascript>window.open('show.aspx')</script>");



    }

答案 1 :(得分:0)

阅读本文后,我找到了解决问题的方法:

Maintain The State Of Dynamic Added User Control On Each PostBack

我使用ViewState来保存下拉列表的ID,以便能够在Postback上重新创建它们。这是代码:

public Dictionary<Guid, string> DropdownLists
{
    get { return ViewState["MyDropdowns"] != null
            ? (Dictionary<Guid, string>)ViewState["MyDropdowns"] : new Dictionary<Guid, string>(); }
    set { ViewState["MyDropdowns"] = value; }
}

public Dictionary<Guid, string> DropdownNames
{
    get { return ViewState["DropdownNames"] != null
    ? (Dictionary<Guid, string>)ViewState["DropdownNames"] : new Dictionary<Guid, string>(); }
    set { ViewState["DropdownNames"] = value; }
}

首先,我添加了这两个类变量,将其值保存在ViewState中。然后第一次加载页面时调用方法CreateForm(),根据PDF文件中的字段创建所有下拉列表。在回发时加载页面时,将根据ViewState中存储的值创建下拉列表。代码如下:

protected void Page_Load()
{

    //Load the file
    doc = new PdfDocument(pdfFileName);

    //Get all fields
    fields = doc.Fields;

    if (!IsPostBack)
    {
        CreateForm();
    }
    else
    {
        RecreateForm();
    }
}

private void CreateForm()
{

    Dictionary<Guid, string> tempList = new Dictionary<Guid, string>();
    Dictionary<Guid, string> tempNames = new Dictionary<Guid, string>();

    foreach (PdfField field in fields)
    {
        //Only display the text fields
        if (field.GetType() == typeof(PdfTextField))
        {
            TableRow tr = new TableRow();
            TableCell name = new TableCell
            {
                Text = field.Name
            };
            tr.Cells.Add(name);
            TableCell options = new TableCell();

            DropdownList dropdown = (DropdownList)LoadControl("~/DropdownList.ascx");

            Guid nextKey = Guid.NewGuid();
            tempList[nextKey] = "dropdown" + nextKey.ToString().Replace('-', '_');
            dropdown.ID = tempList[nextKey];

            tempNames[nextKey] = field.Name;

            options.Controls.Add(dropdown);
            tr.Cells.Add(options);

            Table1.Rows.Add(tr);
        }
    }
    DropdownLists = tempList;
    DropdownNames = tempNames;
}

private void RecreateForm()
{
    foreach (var item in DropdownLists)
    {
        TableRow tr = new TableRow();
        TableCell name = new TableCell
        {
            Text = DropdownNames[item.Key]
        };
        tr.Cells.Add(name);
        TableCell options = new TableCell();

        DropdownList dropdown = (DropdownList)LoadControl("~/DropdownList.ascx");

        dropdown.ID = DropdownLists[item.Key];

        options.Controls.Add(dropdown);
        tr.Cells.Add(options);

        Table1.Rows.Add(tr);
    }
}

我希望这可以帮助那里的任何人。