locked
How to make Dropdownlist in asp.net c# RRS feed

  • Question

  • User-218090889 posted

    Hello,

    I am having an issue with dropdownlist in asp.net

    i have my html markup and c# code for dropdownlist as below, but do get error message as
    ddlCountry' has a SelectedValue which is invalid because it does not exist in the list of items.
    Parameter name: value

    my HTML:

    <asp:DropDownList ID="ddlCountry" runat="server" Width="227px" OnSelectedIndexChanged="ddlCountry_SelectedIndexChanged" AutoPostBack="True">
                       

    my C# code:

    protected void Page_Load(object sender, EventArgs e)
            {
                //Fill only first time of page load
                if (!IsPostBack)
                {
                    DataSet oDs = CountryList();
    
                    if (oDs != null && oDs.Tables != null)
                    {
                        ddlCountry.DataValueField = "Country_ID";
                        ddlCountry.DataTextField = "Country_Name";
    
                        //Assign the dataset to dropdown list
                        ddlCountry.DataSource = oDs;
                        ddlCountry.DataBind();
                    }
                }
            }
    
    
    
      private DataSet CountryList()
            {
                //Create a new Dataset
                DataSet objDS = new DataSet();
                //Create a new datatable
                DataTable objTable = objDS.Tables.Add();
    
                //Add coloms
                objTable.Columns.Add("Country_ID", typeof(int));
                objTable.Columns.Add("Country_Name", typeof(string));
    
                //Add rows
                objTable.Rows.Add(1, "Algeria");
                objTable.Rows.Add(2, "Angola");
                objTable.Rows.Add(3, "Benin");
                objTable.Rows.Add(4, "Botswana");
                objTable.Rows.Add(5, "Burkina");
                objTable.Rows.Add(6, "Burundi");
                objTable.Rows.Add(7, "Cameroon");
    
                return objDS;
            }
    
    
     protected void Button1_Click(object sender, EventArgs e)
            {
                
                            
                            string Country = ddlCountry.SelectedItem.ToString();
                            
    
                            SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["dbConn"].ToString());
                            SqlCommand cmd = new SqlCommand("UpdateCountry", con);
    
                            cmd.CommandType = CommandType.StoredProcedure;
    
                            
                            cmd.Parameters.Add("@Country", SqlDbType.VarChar).Value = Country;
                           
    
    
                            try
                            {
                                cmd.Connection = con;
                                con.Open();
                                cmd.ExecuteNonQuery();
                            }
                            catch (Exception ex)
                            {
    
                            }
                            finally
                            {
    
                                con.Close();
    
    
                            }
    
    
                        }
                        catch (Exception ex)
                        {
    
                        }
                        lblUploadSuccess.Text = "Update country Successful";
                        
    
    
                    }

    Please how do I resolve the issue? Help


    Tuesday, June 18, 2019 6:59 AM

All replies

  • User665608656 posted

    Hi Enzyme,

    According to your description, what is the function of the Button1_Click method in code behind, is it related to your dropdownlist?

    And when the error occur in your page? I also cannot find the ddlCountry_SelectedIndexChanged method in your code behind.

    I test your code when page load, it run perfectly.

    I hope you could provided more detailed code and description about your issue.

    Best Regards,

    YongQing.

    Tuesday, June 18, 2019 7:25 AM
  • User-218090889 posted

    Yongqing Yu

    And when the error occur in your page? I also cannot find the ddlCountry_SelectedIndexChanged method in your code behind.

    my ddlCountry_SelectedIndexChanged is empty

    protected void ddlCountry_SelectedIndexChanged(object sender, EventArgs e)
    {

    }



    the function of Button1_Click method is to input the update in datadase.

    Tuesday, June 18, 2019 7:48 AM
  • User753101303 posted

    Hi,

    Usually this is because the current value for the drop down doesn't match any list item. What if you add ddlCountry.SelectedValue="1" for example to default to the first row (another common practice is to add an empty entry to force the user to select explicitely a value).

    Not related but you should likely avoid using empty catch blocks (hiding an exception from absolutely everybody is likzely one of the last thing you want).

    Tuesday, June 18, 2019 9:05 AM
  • User665608656 posted

    Hi Enzyme,

    According to your description,it seems you didn't have any sentence like ddlCountry.SelectedValue.

    Could you tell me when the error occur? And are there any other dropdownlist codes you haven't provided?

    Here is my example based on your code,you could refer to it:

    <!DOCTYPE html>
    
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title></title>
    </head>
    <body>
        <form id="form1" runat="server">
            <div>
                <asp:DropDownList ID="ddlCountry" runat="server" Width="227px" OnSelectedIndexChanged="ddlCountry_SelectedIndexChanged" AutoPostBack="True"></asp:DropDownList>
            </div>
        </form>
    </body>
    </html>
       protected void Page_Load(object sender, EventArgs e)
            {
                //Fill only first time of page load
                if (!IsPostBack)
                {
                    DataSet oDs = CountryList();
                    if (oDs != null && oDs.Tables != null)
                    {
                        ddlCountry.DataValueField = "Country_ID";
                        ddlCountry.DataTextField = "Country_Name";
    
                        //Assign the dataset to dropdown list
                        ddlCountry.DataSource = oDs;
                        ddlCountry.DataBind();
                    }
                }
            }
    
    
    
            private DataSet CountryList()
            {
                //Create a new Dataset
                DataSet objDS = new DataSet();
                //Create a new datatable
                DataTable objTable = objDS.Tables.Add();
    
                //Add coloms
                objTable.Columns.Add("Country_ID", typeof(int));
                objTable.Columns.Add("Country_Name", typeof(string));
    
                //Add rows
                objTable.Rows.Add(1, "Algeria");
                objTable.Rows.Add(2, "Angola");
                objTable.Rows.Add(3, "Benin");
                objTable.Rows.Add(4, "Botswana");
                objTable.Rows.Add(5, "Burkina");
                objTable.Rows.Add(6, "Burundi");
                objTable.Rows.Add(7, "Cameroon");
    
                return objDS;
            }
    
            protected void Button1_Click(object sender, EventArgs e)
            {
                //string Country = ddlCountry.SelectedItem.ToString();
                //SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["dbConn"].ToString());
                //SqlCommand cmd = new SqlCommand("UpdateCountry", con);
                //cmd.CommandType = CommandType.StoredProcedure;
    
                //cmd.Parameters.Add("@Country", SqlDbType.VarChar).Value = Country;
                //try
                //{
                //    cmd.Connection = con;
                //    con.Open();
                //    cmd.ExecuteNonQuery();
                //}
                //catch (Exception ex)
                //{
    
                //}
                //finally
                //{
    
                //    con.Close();
    
    
                //}
    
    
            }
    
            protected void ddlCountry_SelectedIndexChanged(object sender, EventArgs e)
            {
    
            }

    The result of my work demo:

    Best Regards,

    YongQing.

    Tuesday, June 18, 2019 9:25 AM
  • User-218090889 posted

    Could you tell me when the error occur?

    What I really want to achieve here is to select one item from the Dropdownlist and then use it to update Country column in my database.

    Please how do I go about that with my above code sample?

    Tuesday, June 18, 2019 2:31 PM
  • User665608656 posted

    Hi Enzyme,

    According to your description, I am not sure what is written in your stored procedure.

    If your goal is to update the table, there should be a conditional parameter besides the country parameter you brought in.

    In addition, in your Button1_Click event, did you write an extra catch? This is an incorrect grammar,you need to delete the last catch.

    I tried to realize the function according to your code, and it still had no error warning.

    I hope you could provide me with more detailed information. If you can, please provide a GIF that demonstrates your code flow.

    Here is my code:

            protected void Page_Load(object sender, EventArgs e)
            {
                //Fill only first time of page load
                if (!IsPostBack)
                {
                    DataSet oDs = CountryList();
    
                    if (oDs != null && oDs.Tables != null)
                    {
                        ddlCountry.DataValueField = "Country_ID";
                        ddlCountry.DataTextField = "Country_Name";
    
                        //Assign the dataset to dropdown list
                        ddlCountry.DataSource = oDs;
                        ddlCountry.DataBind();
                    }
                }
            }
    
            private DataSet CountryList()
            {
                //Create a new Dataset
                DataSet objDS = new DataSet();
                //Create a new datatable
                DataTable objTable = objDS.Tables.Add();
    
                //Add coloms
                objTable.Columns.Add("Country_ID", typeof(int));
                objTable.Columns.Add("Country_Name", typeof(string));
    
                //Add rows
                objTable.Rows.Add(1, "Algeria");
                objTable.Rows.Add(2, "Angola");
                objTable.Rows.Add(3, "Benin");
                objTable.Rows.Add(4, "Botswana");
                objTable.Rows.Add(5, "Burkina");
                objTable.Rows.Add(6, "Burundi");
                objTable.Rows.Add(7, "Cameroon");
    
                return objDS;
            }
    
            protected void Button1_Click(object sender, EventArgs e)
            {
                string Country = ddlCountry.SelectedItem.ToString();
                int id = ddlCountry.SelectedIndex + 1;
                SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["dbConn"].ToString());
                SqlCommand cmd = new SqlCommand("update Country set CountryName = @Country where Id =@Id", con);
                cmd.Parameters.Add("@Country", SqlDbType.VarChar).Value = Country;
                cmd.Parameters.Add("@Id", SqlDbType.Int).Value = id;
                try
                {
                    cmd.Connection = con;
                    con.Open();
                    cmd.ExecuteNonQuery();
                }
                catch (Exception ex)
                {
    
                }
                finally
                {
                    con.Close();
    
                }
                lblUploadSuccess.Text = "Update country Successful";
            }
    
            protected void ddlCountry_SelectedIndexChanged(object sender, EventArgs e)
            {
    
            }

    Here is my data sheet:

    Here is the result of my work demo:

    Best Regards,

    YongQing.

    Wednesday, June 19, 2019 1:30 AM