making combobox selection from a database

lional

Well-known member
Joined
Nov 29, 2018
Messages
55
Programming Experience
Beginner
Hi
I have an app where students are inputed and stored in a database table. Certain combobox selections are made and stored in the table. Is is possible when later editing the student that those selections are automatically selected in the combobox. I am using wpf which I am very new to along with binding. Can I be pointed in the right direction. I tried the following line but it does not seem to work. Must I use binding to accomplish this

string titleString = reader.GetString(1);
editStudentsTitleComboBox.SelectedValue = titleString;
 
If you are using binding to populate your combobox, you should also use binding to set the current selected item. You can use code behind if you wish, but you'll need to know the correct time to do that code behind call, as well as be aware be aware of your long term maintenance cost: now you have three places to look at when maintaining your code with regards to the combo box behavior: your XAML, your view model, and your view's code behind.
 
Thank you. I am not using binding. I am still new to this. A friend of mine runs a theological college and I am trying to give them a pro bono solution for now with my limited knowledge. I will take it on as a projects to learn from in the future. I did PHP development but took a liking to C# and am busy doing some self study. I am using wpf because I want to set a basic foundation to progress from as my knowledge improves.

I created a class to populate the various comboboxes from the database which is as follows:
C#:
string queryString = "Select " + comboBoxKey + ", " + comboBoxValue + " FROM " + tableName;
            SqlConnection comboBoxDatabaseConnection = DatabaseUtilities.GetDatabaseConnectionDetails();
            SqlDataAdapter comboBoxDataAdapter = new SqlDataAdapter(queryString, comboBoxDatabaseConnection);
            DataSet comboBoxDataSet = new DataSet();
            comboBoxDataAdapter.Fill(comboBoxDataSet, "\"" + tableName + "\"");
            comboBoxName.ItemsSource = comboBoxDataSet.Tables[0].DefaultView;
            comboBoxName.DisplayMemberPath = comboBoxDataSet.Tables[0].Columns[comboBoxValue].ToString();
            comboBoxName.SelectedValuePath = comboBoxDataSet.Tables[0].Columns[comboBoxKey].ToString();

It is maybe not the best approach but I will continue improving it as I get better
 
Get rid of this :
C#:
string queryString = "Select " + comboBoxKey + ", " + comboBoxValue + " FROM " + tableName;

And search these forums for sql parameters. It's bad practice to cut into a query string as it also leaves you open to sql injection attacks.
 
The best way is to use WPF the way it was meant to be used: Have your WPF View bind to a a Model View which is a facade for your Model -- the MVVM pattern.

But if you want to keep using WPF ala WinForms, then do it the WinForms way: wait for events and only populate on those events.
 
You have bigger fish to fry. First worry about changing your code to use parameters, and ensure you can actually query with your new code.

Once you can query with parameters, then worry about addressing the approach of populating controls. We will wait until you show us where you included parameters in the above code?

I'm a stickler for using parameters and since you are planning to give this to a collage, I'd prefer if you gave it after conducting the correct research before proposing it as an example to follow. Any example that demonstrated the use of concatenated query strings is a bad one.

Here is a tutorial for using parameters : The Right Way To Query A Database: Parameterizing Your SQL Queries. - C# Tutorials | Dream.In.Code
 
Thank you for your input. I will go through it. This is how we learn. we make corrections and post when completed
 
I have made some changes
I retrieve the student data from the database with the following code and then populate the drop down box from the database. As stated earlier I would like the combo box to default to the value that is stored in the database.

C#:
private void populateStudentData()
        {
            SqlConnection comboBoxDatabaseConnection = DatabaseUtilities.GetDatabaseConnectionDetails();
            string queryString = "select StudentNumber, Title, FirstName, MiddleName, LastName, NickName, GenderCode, EquityCode, HomeLanguageCode, NationalId, GroupId, PersonHomeAddress1, PersonHomeAddress2, PersonHomeAddress3, PersonalHomeAddressPostalCode, PersonPostalAddress1, PersonPostalAddress2, PersonalPostalAddress3, PersonalPostalAddressPostalCode, ProvinceCode, NationalityCode, PhoneNumber, WorkNumber, CellPhoneNumber, FaxNumber,EmailAddress, PersonAlternateId, AlternativeIdType, OldStudentNumber, OrganizationName, CitizenResidentStatusCode, SocioeconomicStatusCode, PersonBirthDate, Religion, Denomination, Supervisor, ProviderCode, ProviderId, PreviousLastName, PreviousProviderCode, PreviousEtqaId, SeeingRatingId, HearingRatingId, CommunicatingRatingId, WalkingRatingId, RememberingRatingId, SelfcareRatingId, Notes,PreviousAlternateId, PreviousAlternateIdType, ReferredBy, Archived from PersonalData where StudentNumber = @selectedStudentNumber";
            SqlCommand command = new SqlCommand(queryString, comboBoxDatabaseConnection);
            command.Parameters.AddWithValue("@selectedStudentNumber", selectedStudentNumber);
            comboBoxDatabaseConnection.Open();
               using (SqlDataReader reader = command.ExecuteReader())
                {
                    if (reader.HasRows)
                    {
                        reader.Read();
                        editStudentStudentNumberTextBox.Text = reader.GetString(0);
                        titleString = reader.GetString(1);
                        if (titleString != "")
                        {
                            editStudentsTitleComboBox.DisplayMemberPath = titleString;
                            editStudentsTitleComboBox.SelectedValuePath = titleString;
                        }
                        
                        editStudentsFirstNameTextBox.Text = reader.GetString(2);
                        MessageBox.Show(titleString);

                        reader.Close();
                    }
                }

                // Populate comboboxes

                try
            {
                SqlCommand cmd = new SqlCommand("select * from Title", comboBoxDatabaseConnection);
                comboBoxDatabaseConnection.Open();
                SqlDataAdapter adapter = new SqlDataAdapter(cmd);
                DataTable dt = new DataTable();
                adapter.Fill(dt);
                editStudentsTitleComboBox.ItemsSource = dt.DefaultView;
                editStudentsTitleComboBox.DisplayMemberPath = "Salutation";
                editStudentsTitleComboBox.SelectedValuePath = "Salutation";
                cmd.Dispose();
                comboBoxDatabaseConnection.Close();
                
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
}
 
Have you tried debugging your code?

What's it doing that it shouldn't?

What problem are you experiencing?

You are already setting the combox if your condition is not an empty string on line 15, but then overwrite it on line 37.

Please explain your problem with the above code.
 
Hi, I have made some changes. What I am trying to accomplish is the following:
I have a page that adds a student and certain values are selected via the combo boxes and that gets inserted into the database and that all works fine.
Then when the student is being edited then I want the combo box to default to the item that was selected when the student was added.

I found some errors in my code, namely the one that you mentioned. As I said I am new to C# and WPF. I have done PHP development but this is new to me.

If I can just be pointed in the right direction on how one defaults to a specific entry in the combo box then I can do some research and that way I learn

Thank you and have a great day!
 
Back
Top Bottom