-1

我已经阅读了一些不同的例子,对于那些不完全了解asp.net页面生命周期的人来说,这似乎是一个明显的新手问题,抱歉还在学习。我的修复尝试都没有成功。

aspx:

...
<%
for( int j = 0; j < 11; j++)
{
  ChildWeightPounds.Items.Add( new ListItem(j.ToString(),j.ToString()));
}
%>
<asp:DropDownList ID="ChildWeightPounds" runat="server" OnSelectedIndexChanged="DropDownListSelected">
     <asp:ListItem Value="">-Select-</asp:ListItem>
</asp:DropDownList>
...
<asp:Button ID="InsertButton" runat="server" Text="Submit" OnClick="InsertButton_Click" />

aspx.cs:

protected void InsertButton_Click(object sender, EventArgs e)
{
   foreach (Control c in NewPatientForm.Controls)
    {
        ....
        if (c is TextBox)
        {
             TextBox tb = (TextBox)c;
             //Expected response:
             Response.Write( "field: " + tb.ID + " = " + tb.Text + "<br />");
        }
        if (c is DropDownList)
        {
            DropDownList ddl = (DropDownList)c;

            //Unexpected response: 
            //this is not giving me my selected value, but only the top item ("--select--")
            Response.Write("field: " + ddl.ID + ", selectedItem: " + ddl.SelectedItem.Value + "<br />");
         }
    }
 }

很明显,这是一个 IsPostBack,DataBind(),我对页面生命周期缺乏了解的问题。但是没有意义的是,我正在遍历所有控件,并且文本框、复选框、复选框列表都可以正常工作,并在字段中给我值,由于某种原因,下拉列表没有给我值。

我尝试过使用 OnSelectedIndexChanged 事件,也尝试过使用 DataBind() 函数,但是玩这些,仍然没有得到我的价值。

4

2 回答 2

2

The biggest issue with your example is you are using inline C# within your page with <% %>. This isn't advised for asp.net. That's more of a legacy/classic ASP approach which won't play well with .NET for many reasons.

Try moving your code that adds the items to the dropdownlist from the markup file into the .cs file, and be sure to hook into a page event that happens at or before OnPreRender. That is the last point you can alter the page controls and have viewstate/lifecycle work correctly.

protected void Page_Load(object sender, EventArgs e)
{
    for( int j = 0; j < 11; j++)
    {
        ChildWeightPounds.Items.Add( new ListItem(j.ToString(),j.ToString()));
    }
}

It's likely without running your example that the values are being inserted into the dropdownlist at the incorrect time in the lifecycle, and because of that when you try to access the selected value in the code behind it doesn't work.

Consider the following article on asp.net lifecycle which may assist you.

于 2012-10-09T18:52:53.817 回答
1

您可以AutoPostBack="true"在 DropDownList 上进行调整,并定义OnSelecIndexChanged event

    <asp:DropDownList ID="ChildWeightPounds" runat="server"
         OnSelectedIndexChanged="DropDownListSelected" AutoPostBack="true>
         <asp:ListItem Value="">-Select-</asp:ListItem>
    </asp:DropDownList>

代码背后

void DropDownListSelected(Object sender, EventArgs e)
{
 var value =  ChildWeightPounds.SelectedValue;
}
于 2012-10-09T18:52:15.477 回答