简体   繁体   中英

ASP.net C# Error when passing text to Dropdownlist, which uses an Enum as its datasource list


(Asp.net/C# VS2008)
I have a datagrid populated by a database and when pressing Edit, a form opens and populates fields/controls from that datagrid line.
My issue lies when trying to populate a dropdownlist box, which has a datasource from an ENum List.
I Just cannot get the text from the datagrid cell to show up in the ddL, it should also equal one of the Enum Items and auto select it.
My Code
Pull from the datagrid cell gives me “Low”
ddl_reg.Text = e.Item.Cells[25].Text;

    public void Populate_regstatus_dropdownlist()
{
    //if (!IsPostBack)
    //{
    //    ddl_reg.DataSource = Enum.GetNames(typeof(regstatus));
    //    ddl_reg.DataBind();
    //}
    //if (!IsPostBack)
    //{
    //    foreach (int value in Enum.GetValues(typeof(regstatus)))
    //    {
    //        ddl_reg.Items.Add(new ListItem(Enum.GetName(typeof(regstatus), value), value.ToString()));
    //    }
    //}
    ddl_reg.DataSource = Enum.GetNames(typeof(regstatus ));
    //ddl_reg.DataValueField = regstatus;
    //ddl_reg.DataTextField = "Low";
    //ddl_reg .SelectedItem = Enum.GetName(typeof (regstatus ));
    ddl_reg.DataBind();
    //ddl_reg.SelectedIndex = ddl_reg.Items.IndexOf(ddl_reg.Items.FindByText("Low"));


}
public enum regstatus
{
    NotSelected,
    Low,
    Medium,
    High
}

Error received is;

ddl_reg' has a SelectedValue which is invalid because it does not exist in the list of items. Parameter name: value

I am new to C# but through searching your site i realise this means the value is not seen or has not been pulled and would really apreciate some help, or pointing in the right direction, cheers.

I believe the problem is that the drop down list doesn't contain the item you are passing. You may check it before changing the selected value. Other chances are that the value you are getting from e.Item.Cells[25].Text may contain spaces, so you may trim before setting it to the drop down.

 if (ddl_reg.Items.FindByText("Low") != null)
            {

                ddl_reg.Text = e.Item.Cells[25].Text;
            }
            else
            {
                //Not found
            }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM