【问题标题】:DropDownList SelectIndexChanged not working?DropDownList SelectIndexChanged 不起作用?
【发布时间】:2016-12-03 15:41:26
【问题描述】:

这似乎是一个常见问题。我尝试了不同的解决方案,但仍然无法正常工作。这是我的代码。

HTML:

<div class="form-group">
  <label for="exampleInputEmail1">Artist *</label>
  <asp:DropDownList ID="artistDropdown" runat="server" CssClass="form-control" AutoPostBack="True" OnSelectedIndexChanged="artistDropdown_SelectedIndexChanged" ViewStateMode="Enabled"></asp:DropDownList>
  <asp:TextBox ID="mytest" runat="server"></asp:TextBox>
  <asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" ControlToValidate="artistDropdown" SetFocusOnError="true" ErrorMessage="Required Field" Font-Bold="True" Font-Names="Arial" Font-Size="X-Small" ForeColor="Red"></asp:RequiredFieldValidator>
  <asp:Label ID="lblMessage" runat="server" CssClass="help-block" Visible="False">Cant select Artist with no Manager</asp:Label>
</div>

功能:OnSelectedIndexChanged

protected void artistDropdown_SelectedIndexChanged(object sender, EventArgs e)
{

string selectedArtist = artistDropdown.SelectedValue;
mytest.Text = selectedArtist;
string query = "Select [Manager ID] from Artist Where ID = '" + selectedArtist + "'";

string myConnection = dbController.connectionString;
SqlConnection conn = new SqlConnection(myConnection);

SqlCommand cmd = new SqlCommand(query, conn);
conn.Open();
object obj = cmd.ExecuteScalar();
if (obj is System.DBNull)
{
    artistDropdown.SelectedValue = "";
    lblMessage.Visible = true;
}
else
{
    lblMessage.Visible = false;
}
conn.Close();
}

我正在Page_Load() 函数中加载 DropDownList,并且为 DropDownList 设置了AutoPostBack="True"

我还制作了一个 TextBox,它被设置为 DropDownList 中的 selectedValue,以检查 OnSelectedIndexChanged 是否正在触发。但是文本框仍然是空的。

我做错了什么?

【问题讨论】:

  • 如果将mytest.Text = selectedArtist; 更改为mytest.Text = selectedArtist + DateTime.Now.ToString(); 会发生什么?我怀疑artistDropdown 中的Values 是空的。

标签: asp.net


【解决方案1】:

您是否将下拉列表的绑定放在 if (!postback) {} 中?

如果您在每次回发后重新绑定列表,您将在到达 artistDropdown_SelectedIndexChanged 事件时获得第一个列表项的值。 如果此项为空字符串值...

【讨论】:

  • 是的,我在 if(!postback) 中绑定 DDL
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-22
相关资源
最近更新 更多