Search code examples
c#dropdownboxselectedvalue

selecting value not index from drop down c#


Forgive, new to c# always been a PHP man. Have a form to generator random string for passwords based on the number of characters selected from drop down. Having a problem with obtaining the values from drop down (casting the object to an int). code:

   private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
    {
        string endword = "";
        int chrnumber = Convert.ToInt16(comboBox1.SelectedValue);
        string[] Nochars = { "q", "w", "e", "r", "t", "y", "u", "i", "o", "p", "[", "]", "a", "s", "d", "f", "g", "h", "j", "k", "l", ";", "'", "#", "z", "x", "c", "v", "b", "n", "m", "/", "Q", "W", "E", "R", "T", "Y", "U", "I", "O", "P", "{", "}", "A", "S", "D", "F", "G", "H", "J", "K", "L", ":", "@", "~", "Z", "X", "C", "V", "B", "N", "M", "<", ">", "?", "!", "£", "$", "%", "^", "&", ".*", "(", ")", "_", "+", "1", "2", "3", "4", "5", "6", "7", "8", "9", "0", "-", "=" };
        Random rndchar = new Random();
        for (int i = 0; i < chrnumber; i++)
        {
            int iSelect = rndchar.Next(0, Nochars.Length);
            string word1 = Nochars[iSelect];
            string word2 = word1;
            if (i == 0) { endword = word1; } else { endword += "." + word2; }
        }
        pwd.Text = endword;
    }  

Solution

  • //On form load
    public Form1(){
             List<Values> reasons = new List<Values> { 
                new Values("0", 0), 
                new Values("1", 1),
                new Values("2", 2), 
                new Values("3", 3), 
                new Values("4", 4), 
                new Values("5", 5) };
    comboBox1.DataSource = reasons;
    }
    
    private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
    {
    reason = Convert.ToInt32(comboBox1.SelectedValue);
    }
    

    here the default value is 0, so your error will not occur at any point. I hope your combox datasource default value has ", which is causing this error.

    or make sure the value part is not a alphabets/other characters instead of numbers in your datasource.