在网上做了很多研究后,我仍然对这个问题感到难过.我有一个页面,将名称和类别的数量加载到下拉列表中.我只会这样做!(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”