Reputation: 83
I'm creating an outlook addin with MS Visual Studio. From the ribbon, the user clicks a button which opens a winform (called NewEntry) with some comboboxes which I would like to populate with data from an SQL database.
For populating a single combobox (named Companies) my code is:
public NewEntry()
{
InitializeComponent();
DataTable dt = new DataTable();
cnn.Open();
SqlCommand cmd = new SqlCommand("SELECT Name FROM PrivateContractors", cnn);
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
da.Fill(dt);
}
cmd.Dispose();
cnn.Close();
Companies.DataSource = dt;
try
{
foreach (DataRow dr in dt.Rows)
{
Companies.Items.Add(Convert.ToString(dr["name"])); //this is line 67
}
}
catch (Exception e)
{
MessageBox.Show(Convert.ToString(e));
}
}
This is the exception message:
When the form then opens, my ComboBox is populated with the expected amount of fields but they're all named System.Data.DataRowView
When I remove the foreach statement, I get no exceptions but the combobox values are all still System.Data.DataRowView
Anyone know where I'm going wrong and what I can do to rectify this error?
Upvotes: 0
Views: 110
Reputation: 83
Solution here:
cnn.Open();
SqlCommand cmd = new SqlCommand("SELECT Name FROM PrivateContractors", cnn);
SqlDataReader dataReader = cmd.ExecuteReader();
while (dataReader.Read())
{
Companies.Items.Add(Convert.ToString(dataReader["Name"]));
}
dataReader.Close();
cmd.Dispose();
cnn.Close();
}
Upvotes: 0