Gen*_*ume 8 asp.net autopostback drop-down-menu
在网上做了大量的研究后,我仍然对这个问题感到难过.我有一个页面,将名称和类别数加载到下拉列表中.我只会这样做!(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>
Run Code Online (Sandbox Code Playgroud)
这是后端代码.
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);
}
Run Code Online (Sandbox Code Playgroud)
我只是希望能够根据所选索引填充表单,但我似乎无法得到正确的答案.任何帮助表示赞赏.
use*_*214 12
为下拉列表添加AppendDataBoundItems ="true"
我发现了问题。从我的 SQL 语句填充的值包含重复的值。由于某种原因,这导致整个事情以奇怪的方式发生故障,这使得每次我选择一个 ListItem 时整个列表都会重置。通过确保没有重复的值,代码开始完美运行。感谢大家的帮助。
| 归档时间: |
|
| 查看次数: |
33913 次 |
| 最近记录: |