在ASP.NET中用C#获取下拉列表项的ID

3npbholx  于 2023-02-01  发布在  .NET
关注(0)|答案(1)|浏览(241)

我的项目中有一个下拉列表,可以从SQL Server中获取值。SQL Server中的表有几列,我从中选择了MemberIdMemberName。我想在下拉列表中显示MemberName,但当我选择一个项目时,我想获取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
我该怎么办?

3ks5zfa0

3ks5zfa01#

我发现了发生了什么事。我这样写:

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

在page_load中,但我应该把它写在:

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

相关问题