Noman Nome Butt
Noman Nome Butt

Reputation: 1

How to find the value of selected index in dropdownlist in 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>

and C# code is

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;
}

Upvotes: 0

Views: 1125

Answers (1)

Nino
Nino

Reputation: 7095

You're missing AutoPostBack="true" in markup

Secondly, you're getting index of selected item which means that you're getting number 0 for first selected item, 1 for second etc. which probably doesn't match with your ID's.

Change your code behind like this:

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;
}

Upvotes: 2

Related Questions