kar kar - 2 months ago 7
C# Question

Load my combobox with the column names of my database table

I am using the following method to load data from a database and fill into my combo box. For example if my database table is as follows:

Table Name: PERSONS

Person_Id Person_Name
1 Jason
2 Carl


The names Jason and Carl will be loaded into the combo box. This works fine. I am now looking to load my combo box only with the column names as in Person_ID, Person_Name. Is there a way I could modify my current method to do that? Please advice.

private void fillCombo(string query, string name, ComboBox c)
{
MySqlCommand cmdReader;
MySqlDataReader myReader;

try
{
cmdReader = new MySqlCommand(query, conn);
myReader = cmdReader.ExecuteReader();

while (myReader.Read())
{
string temp;
if (name != null)
{
temp = myReader.GetString(name);
if (!c.Items.Contains(temp))
{
c.Items.Add(temp);
}
}
}
myReader.Close();
}
catch (Exception e) { Console.WriteLine("Unable to load data from database"); }
}

public MainWindow()
{
InitializeComponent();
fillCombo("SELECT * FROM PERSONS;", "Person_Name", comboBox1);
}

Answer

You can get column names like this:

cmdReader = new MySqlCommand(query, conn);
myReader = cmdReader.ExecuteReader();

for(int index=0; index < reader.FieldCount; index++)
{
   c.Items.Add(myReader.GetName(index));
}
Comments