如何在asp.net的下拉列表中找到所选索引的值

时间:2017-05-25 12:55:49

标签: c# asp.net

<asp:DropDownList ID="DropDownList1" runat="server" DataSourceID="SqlDataSource1" DataTextField="Case_Id" DataValueField="Case_Id" Height="16px" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged" Width="184px">
</asp:DropDownList>

和C#代码是

protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{

    cmd.CommandText = "Select * from tb5 where Case_Id="+Convert.ToInt64(DropDownList1.SelectedIndex);
    SqlDataReader r = cmd.ExecuteReader();
    bool b = r.Read();
    TextBox2.Text = r["Case_Name"].ToString();
    TextBox2.ReadOnly = false;
}

1 个答案:

答案 0 :(得分:2)

您在标记中缺少AutoPostBack="true"

其次,您正在获取所选项目的索引,这意味着您将获得第一个选定项目的数字0,第二个数字等于1,这可能与您的ID不匹配。

像这样改变您的代码:

protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{

    cmd.CommandText = "Select * from tb5 where Case_Id= @CaseId";
    cmd.Parameters.Add(new SqlParameter("@CaseId", SqlDbType.BigInt)).Value = Convert.ToInt64(DropDownList1.SelectedValue);
    SqlDataReader r = cmd.ExecuteReader();
    bool b = r.Read();
    TextBox2.Text = r["Case_Name"].ToString();
    TextBox2.ReadOnly = false;
}