在进行了大量在线研究之后,我仍然为这个问题感到困惑。我有一个页面可以将名称和类别计数加载到下拉列表中。我只在!(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);
}
我只希望能够根据选定的索引填充表单,但似乎无法获得正确的答案。任何帮助表示赞赏。
最佳答案
为下拉列表添加AppendDataBoundItems =“true”
关于在回发后,Asp.NET DropDownList重置选定的索引,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/5656058/