Binding combobox from database

lional

Well-known member
Joined
Nov 29, 2018
Messages
55
Programming Experience
Beginner
Hi All
I am new to C# and used to do procedural programming so now I am doing my app in OOP.
I want to bind my combobox key and value from a database but I have numerous comboboxes to do so I am doing it as a method. I will first post the code I have done and then the exception that I am getting
C#:
public static class ComboBoxBinding
    {
        public static void BindKeyValueComboBox(ComboBox comboBoxName, string tableName, string comboBoxKey, string comboBoxValue)
        {
            string queryString = "Select " + comboBoxKey + ", " + comboBoxKey + " 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();

        }

    }

and my error is
System.NullReferenceException
HResult=0x80004003
Message=Object reference not set to an instance of an object.
Source=StudentSynergy
StackTrace:
at StudentSynergy.ComboBoxBinding.BindKeyValueComboBox(ComboBox comboBoxName, String tableName, String comboBoxKey, String comboBoxValue) in C:\Users\Lional\Documents\C#\C# Projects\StudentSynergy\ComboBoxBinding.cs:line 22

If I can be pointed in the right direction so that I can fix my code or understand where I am going wrong.

Thank you
 
"NullReferenceException at line 22" - which line is that in the code you posted?
 
I used the same column name,
C#:
string queryString = "Select " + comboBoxKey + ", " + comboBoxKey + " FROM " + tableName;
That seems unlikely. (EDIT: I see that you were referring to your mistake, not which was line 22 as asked)

I would think that it actually occurred here:
C#:
comboBoxName.DisplayMemberPath = comboBoxDataSet.Tables[0].Columns[comboBoxValue].ToString();
As you were retrieving the column specified by comboBoxKey twice, comboBoxDataSet.Tables[0].Columns[comboBoxValue] would have been null, hence the NullReferenceException. You presumably changed that to get the two different columns instead of the same column twice. I would also suggest two other small changes. Firstly, I'd suggesting using string interpolation if you need more than a single concatenation operator, for the sake of readability. Secondly, you probably ought to wrap your identifiers in brackets, just in case they are reserved words or contain special characters:
C#:
var queryString = $"SELECT [{comboBoxKey}], [{comboBoxValue}] FROM [{tableName}]";
 
Back
Top Bottom