gpt4 book ai didi

asp.net - asp .net dropdownlist selectedindex 不起作用

转载 作者:行者123 更新时间:2023-12-02 17:15:31 25 4
gpt4 key购买 nike

我有以下代码:

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++;
}

标记如下所示:

<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>

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

我不知道为什么会发生这种情况。每次我从下拉列表中选择某些内容时,都会调用函数“DropDownList1_SelectedIndexChanged”。

谢谢

最佳答案

看起来您正在将下拉菜单绑定(bind)到 Page_Load...

请记住,当下拉列表更改时,它会进行回发(AutoPostBack='True'),并且由于您绑定(bind)在 Page_Load 上,因此每次索引更改时它都会重新绑定(bind)......这不是您想要的!

你应该这样做:

if (!IsPostBack)
{
BindDropDownList1();
}

关于asp.net - asp .net dropdownlist selectedindex 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7236591/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com