Link to home
Start Free TrialLog in
Avatar of Ross-C
Ross-CFlag for United Kingdom of Great Britain and Northern Ireland

asked on

Index out of range datareader

I am having a problem with my function.  I have lots of similar functions that work fine but cannot seem to find what is wrong with the following.  I wondered if anyone looking at it fresh might spot the problem.

I get the error at
 ExtensionUser = (string)UserDataReader[ExtensionUser].ToString();

the fields ExtensionUser and ExtensionNo ar both varchars in a table called extensions.

If i set a breakpoint and copy the sqltext string vlaue and paste it into sql query analyser it returns the value i expect.

Many Thanks
public static string GetExtensionUserFromExt(string ExtensionNo)
        {


            string ExtensionUser = "";

            // declare datareader, connection and command name
            SqlDataReader UserDataReader;
            SqlConnection UserDataConnection;
            SqlCommand UserDataCommand;

            // start new command with command text 
            UserDataConnection = new SqlConnection(ConnString());

            // open connection
            UserDataConnection.Open();

            // declare sql text
            string sqltext = "select [ExtensionUser] from extensions where [ExtensionNo] = '" + ExtensionNo + "'";

            //prepare sql statements
            UserDataCommand = new SqlCommand(sqltext, UserDataConnection);
            UserDataReader = UserDataCommand.ExecuteReader();


            while (UserDataReader.Read())
            {

                ExtensionUser = (string)UserDataReader[ExtensionUser].ToString();
                
            }




            //cleanup objects
            UserDataReader.Close();
            UserDataConnection.Close();


            return ExtensionUser;



        }

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of xeonol
xeonol
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Ross-C

ASKER

How did I not spot that, had been looking at it too long. Many thanks for that.