Home > Mobile >  Get Id of item from dropdownlist in ASP.NET using C#
Get Id of item from dropdownlist in ASP.NET using C#

Time:01-30

I have a dropdownlist in my project that get the value from SQL Server. Table in SQL Server has several columns and I select MemberId and MemberName from that. I want to show MemberName in the dropdown, but when I select an item, I want to get MemberId.

I do this like that:

string strsql1;
SqlConnection con1;
string strcon = "Data Source=ZAHRA\\SQLEXPRESS01;Initial Catalog=YekAye;Integrated Security=True";

con1 = new SqlConnection(strcon);

strsql1 = "SELECT MemberId,MemberName  FROM TbAye WHERE StatusMember = 1 ORDER BY MemberName";

SqlCommand cmd1 = new SqlCommand(strsql1, con1);

con1.Open();

DropDownListAye.DataSource = cmd1.ExecuteReader();
DropDownListAye.DataTextField = "MemberName";
DropDownListAye.DataValueField = "MemberId";
DropDownListAye.DataBind();

con1.Close();

But this:

int SelectedMember = Convert.ToInt32(DropDownListAye.SelectedValue);

gets me the index of the selected item, not MemberId of it.

What should I do?

CodePudding user response:

Try to use SelectedItem.Value, like:

int SelectedMember = Convert.ToInt32(DropDownListAye.SelectedItem.Value);

CodePudding user response:

I found What happened. I write this:

int SelectedMember = Convert.ToInt32(DropDownListAye.SelectedValue);

in the page_load but I should write it in :

protected void DropDownListAye_SelectedIndexChanged(object sender, EventArgs e)
        {
            int SelectedMember = Convert.ToInt32(DropDownListAye.SelectedValue);
        }
  • Related