asp .net dropdownlist selectedindex无效

Var*_*rma 2 asp.net selectedindex drop-down-menu

我有以下代码:

DataRow CreateRow(DataTable dt, string name, string country)
    {
        DataRow dr = dt.NewRow();
        dr["Name"] = name;
        dr["Country"] = country;
        return dr;
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        // creating the data table
        DataTable dt = new DataTable("Student Details");

        // adding two columns Name and Country
        dt.Columns.Add("Name", typeof(String));
        dt.Columns.Add("Country", typeof(String));

        // create 3 rows        
        dt.Rows.Add(CreateRow(dt, "Varun", "India"));
        dt.Rows.Add(CreateRow(dt, "Li", "China"));
        dt.Rows.Add(CreateRow(dt, "Yishan", "China"));

        // create a data view 
        DataView dv = new DataView(dt);

        DropDownList1.DataSource = dv;
        DropDownList1.DataTextField = "Name";
        DropDownList1.DataValueField = "Country";
        DropDownList1.DataBind();
    }
    protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
    {
        int x = DropDownList1.SelectedIndex;
        int temp = 0;
        temp++;
    }
Run Code Online (Sandbox Code Playgroud)

并且标记看起来像这样:

<body>
    <form id="form1" runat="server">
    <div>

        <asp:Label ID="Label1" runat="server"></asp:Label>
        <br />
        <br />
        <asp:DropDownList ID="DropDownList1" runat="server" 
            onselectedindexchanged="DropDownList1_SelectedIndexChanged"
            AutoPostBack="true">
        </asp:DropDownList>

    </div>
    </form>
</body>
Run Code Online (Sandbox Code Playgroud)

问题是无论我选择什么,标签总是显示Varun.我调试了代码并发现"DropDownList1.SelectedIndex"总是因某种原因返回0.

我不知道为什么会这样.每次从下拉列表中选择某些内容时,都会调用函数"DropDownList1_SelectedIndexChanged".

谢谢

c0d*_*nja 6

看起来你绑定了Page_Load中的下拉列表...

请记住,当下拉列表更改时,它会回发(AutoPostBack ='True'),并且由于您绑定了Page_Load,它只会重新绑定索引更改的时间...而不是您想要的!

你应该做这样的事情:

if (!IsPostBack)
{  
    BindDropDownList1();      
}
Run Code Online (Sandbox Code Playgroud)