繁体   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