I am very new to C# and coding in general. I have a question regarding my little project. I have Multiple Listboxes that are connected to my SQL Database. Under the Listboxes I have Textboxes to enter new values into the Database.
The problem I'm having is that whenever I enter something in a textbox (I made it so hitting enter would run the Keydown event to add the line) the selection from my Listboxes changes. That is annoying since what I have selected is important since I joined multiple Databases and the selection is what determines where the input goes.
So my question is, is there a way in WPF or C# to prevent the selected item from being unselected? I have searched for a while, but can't find anything except explanations that I just don't understand with the little knowledge I have.
Edit
Thanks for the responses. I've looked at the links people posted, but I couldn't figure out how they apply to my exact issue. I have been trying to save the SelectedIndex in a variable and then setting the SelectedIndex back to that variable after, but i must be making a mistake somewhere.
int y;
private void TxbSchüler_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Enter)
{
y = listClasses.SelectedIndex; // Here
try
{
string query = "insert into Schüler values (@Name, @KlassenId)";
SqlCommand sqlCommand = new SqlCommand(query, sqlConnection);
sqlConnection.Open();
sqlCommand.Parameters.AddWithValue("@Name", txbSchüler.Text.ToString());
sqlCommand.Parameters.AddWithValue("@KlassenId", listClasses.SelectedValue);
sqlCommand.ExecuteScalar();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
finally
{
sqlConnection.Close();
ShowStudent();
ShowClass();
}
}
listClasses.SelectedIndex = y; //here
}