从下拉 C# 中选择值而不是索引

selecting value not index from drop down c#

请原谅,C# 的新手一直都是 PHP 人。 有一个表单可以根据从下拉列表中选择的字符数为密码生成随机字符串。 从下拉列表中获取值时出现问题(将对象转换为 int)。 代码:

   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;
    }  
//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);
}

这里的默认值为0,所以任何时候都不会出现你的错误。我希望你的组合框数据源默认值有 ",这是导致这个错误的原因。

或者确保值部分不是 alphabets/other 字符而不是数据源中的数字。

试试这个

  private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
    {
        string endword = "";          
        int chrnumber = int.Parse(this.comboBox1.GetItemText(this.comboBox1.SelectedItem).ToString());// change line
        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;
    }