(int)comboBox_CauseOfGame.SelectedItem
This throws the error "Specified type conversion is invalid what is mean the Specified cast is not valid." because the value is converted to an
integer
is not of that type, is a
string
display name from:
comboBox_CauseOfGame.Items.Add(reader["Name"].ToString());
You want the
SelectedIndex
which is an
integer
index of the
SelectedItem
. Read more here:
ComboBox.SelectedItem Property (System.Windows.Forms) | Microsoft Learn[
^]
UPDATED
This is fundamentals of a ComboBox, but I will make an example for you:
1. Create a new project
2. Add the following 4 controls:
private ComboBox comboBox1;
private TextBox txtSelectedItem;
private TextBox txtSelectedIndex;
private TextBox txtCollectionIndexOf;
3. Add the following to the code-behind:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
GenerateNames();
comboBox1.DataSource = Names;
}
public List<string> Names { get; set; } = new();
private void GenerateNames()
{
for (int i = 0; i < 100; i++)
{
Names.Add($"Name {i}");
}
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
txtSelectedIndex.Text = comboBox1.SelectedIndex.ToString();
txtSelectedItem.Text = comboBox1.SelectedItem.ToString();
txtCollectionIndexOf.Text = Names
.IndexOf(comboBox1.SelectedItem.ToString()
?? "no item selected")
.ToString();
}
}
When you select items in the ComboBox, you will see the results in the TextBoxes. This is exactly what has been discussed.