簡體   English   中英

使用 C# 從 ASP.NET 的下拉列表中獲取項目的 ID

[英]Get Id of item from dropdownlist in ASP.NET using C#

我的項目中有一個下拉列表,它從 SQL 服務器獲取值。 SQL 服務器中的表有幾個列,我從 select MemberIdMemberName中獲取。 我想在下拉列表中顯示MemberName ,但是當我 select 一個項目時,我想得到MemberId

我這樣做是這樣的:

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();

但是這個:

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

獲取所選項目的索引,而不是它的MemberId

我應該怎么辦?

我發現發生了什么事。 我這樣寫:

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

在 page_load 但我應該把它寫在:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM