1
//Creating Data Reader Components
string str_ClientID;
string str_Occupation;
string strCompany;

public void Read_Out_Clients(string company)
{ 
    //Specify the parameter search criteria
    sqlComLoad.Parameters["@company"].Value = company;

    sqlCon.Open(); // open database connection

    // create database reader to read information from database
    SqlDataReader objReader = sqlComLoad.ExecuteReader();

    // retrieve 
    // information from database
    //<--This Errors saying there is not data in the data base 
    //Suppose to return the ClientID field data All field names are correct
    str_ClientID = Convert.ToString(objReader["ClientID"]);      

    //suppose to return the Occupation field data 
    str_Occupation = Convert.ToString(objReader["Occupation"]);

    objReader.Close(); // close data reader connection
    sqlCon.Close(); // close database connection
}

//This is the returning value to the method
private void cboCompany_SelectedIndexChanged(object sender, EventArgs e)
{
    strCompany = cboCompany.SelectedItem.ToString();
    if(strCompany != "")
    {
        //Read out companys selected related fields from clients
        Read_Out_Clients(strCompany);

        //Add those related fields to specifics
        cboClientID.Items.Add(str_ClientID); <--this is what the reader is supposed to return
        txtOccupation.Text = str_Occupation; 
    }
}

Any help on making this reader simple would be great! Thanks guys This code is suppose to read the data fields where the data field company matches the query search criteria It works with Access database but for some reason its not working with the SQL query. It should work I tested it in the SQL query executor, it returns the data but the error in the application level when I run the reader it says, "Invalid attempt to read when no data is present"; but there is data it returns the data in the SQL query Executor so I'm puzzled Please help Thanks again.

4

1 回答 1

2

在使用 SqlDataReader(或由 DbDataReder 派生的任何类实例)之前,您需要调用该方法

 if(objReader.Read())
 {
    ... read the fields
 }

并检查它是否返回 true。
只有在此之后,您才objReader位于查询检索到的第一条记录上。

于 2013-06-09T12:52:17.647 回答