如何从DropDownList获取ID?

时间:2015-06-10 09:28:59

标签: c# asp.net database drop-down-menu selectedindexchanged

我正在尝试保存从DropDownList中选择不同值时所做的更改。但是我收到了这个错误

  

值不能为空。参数名称:String [ArgumentNullException:   值不能为空。参数名称:String]
  System.Number.StringToNumber(String str,NumberStyles选项,   NumberBuffer&安培; number,NumberFormatInfo info,Boolean parseDecimal)   +10722118 System.Number.ParseInt32(String s,NumberStyles style,NumberFormatInfo info)+145 System.Int32.Parse(String s)+23

我认为问题是它没有在DropDownList中找到值的ID,因此它会在更新语句Trailer.UpdateTrailer(int.Parse(TrailerID),中抓住这一行

  protected void ddlTrailerLoc_SelectedIndexChanged(object sender, EventArgs e)
        {
            DropDownList ddlTrailerLoc=sender as DropDownList;
            if (ddlTrailerLoc != null)
            {
                ddlTrailerLoc.SelectedValue.ToString();

                Trailer.UpdateTrailer(int.Parse(TrailerID), Company.Current.CompanyID,txtTrailerReg.Text,ddlTrailerLocation.Text);
            }
        }

如何获取我从DropDownList中选择的值的ID?

这里是填充DropDownList

的代码
protected void PopulateDDLs(DropDownList ddlTrailerLoc)
    {
        DataSet dsTrailerLocation = DataUtils.GetAllGenSmall(Company.Current.CompanyID, "Description", "", 1, false, "Description", false, "TrailerLocationNOCODE", 0);
        if (dsTrailerLocation.Tables[0].Rows.Count > 0)
        {
            ddlTrailerLoc.DataSource = dsTrailerLocation;
            ddlTrailerLoc.DataValueField = "Description";
            ddlTrailerLoc.DataTextField = "Description";
            ddlTrailerLoc.DataBind();
        }
        else
        {
            ddlTrailerLoc.Items.Insert(0, new ListItem("No Locations Entered", "0"));
        }
    }

我知道这个ddlTrailerLoc.DataValueField = "Description";应该设置为TrailerID或其他东西,但只有当它是描述时它才会起作用。更改此项会使DropDownList显示错误的值

2 个答案:

答案 0 :(得分:0)

只是猜测你提供的信息,但是应该这样:

ddlTrailerLoc.SelectedValue.ToString();

实际上是:

TrailerID = ddlTrailerLoc.SelectedValue.ToString();

否则无法确定设置了TrailerID的代码。

答案 1 :(得分:0)

  protected void ddlTrailerLoc_SelectedIndexChanged(object sender, EventArgs e)
        {
            DropDownList ddlTrailerLoc=sender as DropDownList;
string value = "".
            if (!String.IsNullOrEmpty(ddlTrailerLoc.SelectedValue.ToString())
            {
                value = ddlTrailerLoc.SelectedValue.ToString();

                Trailer.UpdateTrailer(int.Parse(TrailerID), Company.Current.CompanyID,txtTrailerReg.Text,ddlTrailerLocation.Text);
            }
        }

然后在需要使用它时分配值。喜欢TrailerID。我认为这是你想要实现的目标。如果是这样,您可以将TrailerID分配给ddlTrailerLoc.SelectedValue.ToString();然后声明字符串值是不必要的。在这种情况下:

protected void ddlTrailerLoc_SelectedIndexChanged(object sender, EventArgs e)
{
DropDownList ddlTrailerLoc=sender as DropDownList;
if (!String.IsNullOrEmpty(ddlTrailerLoc.SelectedValue.ToString())
{
TrailerID = ddlTrailerLoc.SelectedValue.ToString();
Trailer.UpdateTrailer(int.Parse(TrailerID), Company.Current.CompanyID,txtTrailerReg.Text,ddlTrailerLocation.Text);
}
}
相关问题