Dean Lewis Dean Lewis - 8 months ago 36
SQL Question

Populating ComboBox with values from SQL Column

I am trying to populate a combobox that is disabled until a value in a previous combobox is selected, with all data within a specific column within a SQL Server table.

This is what I have tried so far:

private void cboManufacturor_SelectedIndexChanged(object sender, EventArgs e)
string manufacturor = this.cboManufacturor.SelectedItem.ToString();

if (!cboModel.Enabled)
cboModel.Enabled = true;

using (SqlConnection myConnection = new SqlConnection(Program.conString))
string queryString = "SELECT * FROM tblStock WHERE Manufacturor=@Manufacturor";

SqlCommand myCommand = new SqlCommand(queryString, myConnection);
myCommand.Parameters.AddWithValue("@Manufacturor", manufacturor);

SqlDataReader DR;

using (DR = myCommand.ExecuteReader())
while (DR.Read())

Thanks in advance for any and all help!


EDIT: Sorry, forgot to say what the problem i was encountering actually was! When a value in the original ComboBox (cboManufacturor) is selected, the second ComboBox (cboModel) is enabled, but no values are added.


the manufacturor variable is : "System.Data.DataRowView" because you use SelectedItem, SelectedItem is the data object that is bound to the ComboBox's data source, you can use :

string manufacturor = this.cboManufacturor.Text;

or cast SelectedItem to DataRowView, then retrieve the appropriate value from it like this :

DataRowView oDataRowView = this.cboManufacturor.SelectedItem as DataRowView;
string manufacturor = string.Empty;

if (oDataRowView != null) {
   manufacturor = oDataRowView.Row["YourFieldName"] as string;