将数据传回 Dropdownlist asp .net webform 时出错

Error on passing data back to Dropdownlist asp .net webform

我有一个无法用于编辑目的的下拉列表。当在存在数据的列表视图中单击按钮编辑时,数据应该传回下拉列表和表单位于列表视图外部的其他文本框。将数据传回文本框是可以的。问题是我要编辑的下拉列表数据已作为另一条记录添加到下拉列表中。请在图片上抢劫,我必须重新选择正确的一张。否则,所选数据(例如图片中的十二月)没有数据值字段,如果我没有选择底部十二月并单击更新按钮,它会停止 运行。这是我几个月的下拉列表代码。任何帮助表示赞赏。谢谢。

   public void BindMonth()
{
    ddlStartMonth.DataSource = objUIHelpers.GetAllMonths();
    ddlStartMonth.DataTextField = "StartMonthName";
    ddlStartMonth.DataValueField = "MonthId";
    ddlStartMonth.DataBind();
    ddlStartMonth.Items.Insert(0, "Select Start Month");}

然后,我把这个方法放在页面加载中这样。

 protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        BindMonth();
    }
}

这是列表视图数据项编辑

protected void lvEducation_ItemCommand(object sender, ListViewCommandEventArgs e)
{
    switch (e.CommandName)
    {
        //Delete Method will be fired when command name "Delete" inside Listview is clicked.
        case ("Delete"):

            int EducationId = Convert.ToInt32(e.CommandArgument);//pass Id of Experience to identify datarow to delete
           // DeleteEducationById(ExperienceId);//Call bind to delete method and pass ExperienceId as argument

            break;

        //Edit Method will fired when command name "Edit" inside Listview is clicked.
        case ("Edit"):
            EducationId = Convert.ToInt32(e.CommandArgument); //pass Id of Experience to identify datarow to edit
            BindEducationDataToEdit(EducationId);//Call bind to edit method and pass ExperienceId as argument
            break;
    }}

这是触发传回数据进行编辑的方法的一部分。

 public void BindEducationDataToEdit(int EducationId)
{
    Education edu = objJFUserBAL.GetEducationByIdToEdit(EducationId);

    txtAdditionalInfo.Text = edu.AdditionalInfo.ToString();
    ddlEndMonth.SelectedItem.Text = edu.mo.EndMonthName;
    }

When selected data is posted back for editing, I have extra data like this.

您必须手动填写列表,因为自动绑定不会让您放置 "select your month" 项目,除非您的数据库中有:

public void BindMonth()
{

    List<Month> listOfMonth = new List<Month>();
    Month fakeMonth = new Month();

      // you need to see your own 
      //code and try to make a fake month with these parameters you want

    fakeMonth.StartMonthName = "Select Start Month";
    fakeMonth.MonthId = 0;


    listOfmounth.Add(fakeMonth);

    foreach(Month m in objUIHelpers.GetAllMonths())
    {
       listOfMonth.Add(m)
    }

    ddlStartMonth.DataSource = listOfMonth;
    ddlStartMonth.DataTextField = "StartMonthName";
    ddlStartMonth.DataValueField = "MonthId";
    ddlStartMonth.DataBind();
    ddlStartMonth.Items.Insert(0, "Select Start Month");}
}

您不应该更新 SelectedItem.Text。这正在改变显示的文本。相反,您应该更新 selected 的项目。

如果您无权访问月份名称的值,您可以执行以下操作:

ddlEndMonth.Items.FindByText(edu.mo.EndMonthName).Selected = true;

这将 select 假设存在带有月份文本的项目。

如果可能有一个 edu.mo.EndMonthName 不存在于项目列表中,您将需要对 null 进行一些检查并进行相应处理。