如何设置列表项的值属性,以正确的Id从数据库表'

本文关键字:Id 数据库 属性 设置 何设置 列表 | 更新日期: 2023-09-27 18:05:25

我使用实体框架连接到数据库并从表中检索一些信息。我需要在下拉列表中显示这些信息。我需要设置每个列表项目值等于Id设置在数据库。

public void EducationDropDownListViewer()
{
    EducationDropdown.Items.Add(new ListItem { Text = "--select--", Value = "0" });
    List<Education> educations = ModelLists.GetEducationList();
    for (int i = 0; i < educations.Count; i++)
    {
        ListItem educationListItem = new ListItem();
        Education education = educations[i];
        educationListItem.Text = education.EducationName;
        educationListItem.Value = education.Id.ToString(CultureInfo.InvariantCulture);
        EducationDropdown.Items.Add(educationListItem);
    }
}

我期望Id集对应于每一行的Id从DB,但它将设置连续从1开始。如何将此属性设置为正确的值?我需要使用这个值,它选择通过这段代码在数据库表中做一些更新。

protected void EducationDropdown_SelectedIndexChanged(object sender, EventArgs e)
{
    ViewState["educationid"] = Convert.ToInt32(EducationDropdown.SelectedIndex);
}

如何设置列表项的值属性,以正确的Id从数据库表'

SelectedIndex属性返回当前选择项在整个DropDownList中的累进索引。
您正在寻找返回SelectedItem

ValueSelectedValue属性。
protected void EducationDropdown_SelectedIndexChanged(object sender, EventArgs e)
{
    // If you accept also the item at index zero (the prompt to select) then change
    // the test below to >=
    if(EducationDropDown.SelectedIndex > 0)
        ViewState["educationid"] = Convert.ToInt32(EducationDropdown.SelectedValue);
}