0

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

        }
halfer
  • 19,824
  • 17
  • 99
  • 186
Benedikt J Schlegel
  • 1,707
  • 1
  • 10
  • 23
  • I'm quite sure you have to loop through them manually and save the selected indices, then once you've added your new values, run through and reselect them. – Dave C Jan 30 '19 at 13:32
  • 1
    https://stackoverflow.com/questions/39407396/listbox-selected-items-are-reset-each-time-i-switch-tabs-in-may-tabcontrol – Dave C Jan 30 '19 at 13:34
  • That is a similar scenario except they are switching tabs and it's resetting instead of adding a new item. – Dave C Jan 30 '19 at 13:34
  • 1
    Possible duplicate of [WPF controls, disable changes to \`SelectedItem\` when bound property to \`ItemsSource\` changes](https://stackoverflow.com/questions/45368609/wpf-controls-disable-changes-to-selecteditem-when-bound-property-to-itemssou) – Rekshino Jan 30 '19 at 14:19

2 Answers2

0

Before you add the element store the selected index in a variable and set the selected index back to this variable after adding the item

Denis Schaf
  • 2,478
  • 1
  • 8
  • 17
  • Thanks for the answer. I've tried to do that now, but I havent been able to make it work. I edited the Post with the Code i have, maybe you could have a look. – Benedikt J Schlegel Jan 30 '19 at 15:31
0

So, it's hard for me to tell without seeing the rest of your code, but you declare y outside of your TxbSchüler_KeyDown method. Since this is outside of the scope of your method, this means other methods in your class will have access to this variable and are able to update its value before your method finishes executing (which might be your issue).

It is quite possible, given your code, that y is being updated outside of the TxbSchüler_KeyDown method. I would look in your ShowStudent and ShowClass methods to see if they are also using a variable called y OR if these methods are updating the listClasses.SelectedIndex, as they likely have access to update this value, and thus the opportunity to update y, since y is tied to the listClasses.SelectedIndex.

In general, it is good practice to keep these variables local to your methods, as to avoid any unwanted changes to this variable outside of the confines of your method. If you need to use this variable in another process, simply pass it as a parameter to another method or function.

In short, if you move the declaration of variable y inside of your method, this might fix your issue if you're updating y elsewhere in your code (either through an update in the listClasses.SelectedIndex or directly changing y). If not, it might be a more complex control issue. But, I doubt it.

However, the fact you are re-assigning your selected index as y, only after you call two methods that have access to change this variable just prior to this re-assignment, is a big red flag leads me to believe this might be a scope-related issue, that is providing unwanted variable re-assignment of y.

Link: Geeks For Geeks: C# Variable Scope

Hope your fix is that simple. Best Wishes.

P.S. - Also name it something better than y as it will stick out like a sore thumb in other places in your code. y is vague and non-descriptive. Name it something like int CurrentIndex

Scott Mallon
  • 136
  • 1
  • 9
  • Thank you very much. I have no idea why, but moving the y variable to the method fixed it. There was nothing in the rest of the code changing y, but for some reason it works now so i wont complain ;) thank you – Benedikt J Schlegel Jan 30 '19 at 16:00
  • To clarify, (and I will update my answer), if 'y' is outside of your method, but you assign it to 'SelectedIndex', this means ANY method that updates 'SelectedIndex' will update 'y' outside of your method, because these methods change 'SelectedIndex' and 'y' knows when it has changed because of the scope of 'y'. When you move 'y' inside of your method, that means unless you are changing the selected index within that method directly, 'y' will not update to some other value because 'y' doesn't even exist in the other method's scope when they change 'SelectedIndex'. Make sense? – Scott Mallon Jan 30 '19 at 16:44
  • And, no problem! Glad I could help. – Scott Mallon Jan 30 '19 at 16:50