【发布时间】:2011-08-05 02:11:44
【问题描述】:
在网上做了很多研究之后,我仍然被这个问题难住了。我有一个页面,将类别的名称和计数加载到下拉列表中。我只在!(Page.IsPostBack) 时这样做。当AutoPostBack 触发SelectedIndex = 0。我尝试了几种不同的方法。这是我的代码:
页面
<form id="AddAssignmentForm" runat="server">
<asp:ScriptManager ID="ScriptManager1" EnablePartialRendering="true" runat="server" />
<asp:UpdatePanel ID="CommentUpdate" runat="server">
<ContentTemplate>
Add Comment
<asp:DropDownList ID="ddlCategory" runat="server" Width="206" OnSelectedIndexChanged="ddlCategory_SelectedIndexChanged" AutoPostBack="true" />
<asp:TextBox ID="txtName" runat="server" Width="200" />
<asp:TextBox ID="txtAbbrv" runat="server" Width="200" />
<asp:TextBox ID="txtDescription" runat="server" Width="200" Height="90" TextMode="MultiLine" />
</ContentTemplate>
</asp:UpdatePanel>
</form>
这是后端代码。
private void Page_Load(object sender, System.EventArgs e)
{
if (!Page.IsPostBack)
{
GetCategories();
}
}
public void GetCategories()
{
String strSql = @"SELECT Name, Total
FROM MyTable";
if (con.State == ConnectionState.Closed)
con.Open();
OleDbCommand cmdsql = new OleDbCommand(strSql, con);
OleDbDataReader cmdReader = cmdsql.ExecuteReader();
if (cmdReader.HasRows)
{
while (cmdReader.Read())
{
ddlCategory.Items.Add(new ListItem(cmdReader["Category_Name"].ToString(), cmdReader["Total"].ToString()));
}
ddlCategory.SelectedIndex = -1;
}
cmdReader.Close();
con.Close();
}
public void FillForm(int index)
{
ListItem item = ddlCategory.Items[index];
txtName.Text = item.Text + " " + (Convert.ToInt32(item.Value) + 1).ToString();
txtAbbrv.Text = item.Text.Substring(0, 1) + (Convert.ToInt32(item.Value) + 1).ToString();
}
public void ddlCategory_SelectedIndexChanged(Object sender, EventArgs e)
{
//When I break here SelectedIndex always = 1.
FillForm(ddlCategory.SelectedIndex);
}
我只是希望能够根据所选索引填充表单,但我似乎无法得到正确的答案。任何帮助表示赞赏。
【问题讨论】:
-
我假设您启用了视图状态?您是否检查了请求以查看为该控件返回的值是什么?下拉列表中有多少项?
-
我很确定我以前遇到过这个问题。您可以尝试使更新面板有条件并为您的 DropDownLists selectedindex 更改事件设置异步回发触发器吗?
-
现在下拉列表中有 4 个项目。我不确定您通过检查请求以查看返回的值是什么意思。我检查了 SelectedIndexChanged 中的 ddlCategory.SelectedIndex,它始终为 1。
-
我将更新面板更改为条件并添加了触发器。它没有改变任何东西。当我更改 DropDownList 选择时,它会自动跳回列表中的第一项。
-
GetCategories() 是从其他任何地方调用的吗?
标签: asp.net drop-down-menu autopostback