I have a SQL Server database and I’m trying to query it. First I retrieve all names and id’s from a table called Firms, use that to populate a ListBox. When I click a an item in that list box I want to populate another ListBox with employees that work for said firm.
I use this query (tested in SQL Server 2008)
SELECT
employee.Name
From
employee, Firm
WHERE
Firm.Name = 'Some Firm' AND
Firm.F_Id = employee.F_Id
This is the code for clicking on a list box item:
private void Firm_ListBox_SelectedIndexChanged(object sender, EventArgs e)
{
String Name = "";
Int32 F_Id = -1;
// This for would be useful later on in the program
// For now it can be ignored
for (int i = 0; i < Firms.Count(); i++)
{
if (Firms.ElementAt(i).GetFirmName().Equals(Firm_ListBox.SelectedItem.ToString()))
{
Name = Firms.ElementAt(i).GetFirmName();
F_Id = Firms.ElementAt(i).GetF_Id();
}
}
MessageBox.Show(Name.ToString() + "\n\t" + F_Id.ToString()); // first message box
SqlCommand SqlCommand = new SqlCommand(
"SELECT employee.Name From employee, Firm WHERE Firm.Name = " + "'" +
Name + "'" + " AND Firm.F_Id = employee.F_Id", SqlConnection);
SqlDataReader SqlDataReader = SqlCommand.ExecuteReader();
MessageBox.Show("Test: " + SqlDataReader.GetString(1)); // second message box
Employee_ListBox.Items.Clear();
while (SqlDataReader.Read())
{
Employee_ListBox.Items.Add(SqlDataReader.GetString(1));
MessageBox.Show(SqlDataReader.GetString(1));
}
SqlDataReader.Close();
}
First MessageBox works, but the second one does not appear. I have no idea what is going on here (not to mention my ListBox doesn’t get populated).
EDIT While debugging I realized that after the read operation, when I attempt to get string I get a horrible exception (I added a try-catch block). I can’t even begin to read it, except this
Invalid attempt to read when no data is present.
caught my eye. Yet I can’t explain. The connection works, the query I’ve tested. And even if it didn’t return anything … shouldn’t it just print nothing and move one ?
EDIT2 It seems I get an invalid operation exception, not at reader, but at the message box.
In the second message box, you’ve got this as part of the message:
Because you haven’t yet read anything from the data reader, this command will throw the exception you are seeing.
The command
needs to appear prior to trying the GetString method. Additionally, you should verify that data was read before executing the GetString method.