Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 833
  • Last Modified:

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

0
Ross-C
Asked:
Ross-C
1 Solution
 
xeonolCommented:
This line:
ExtensionUser = (string)UserDataReader[ExtensionUser].ToString();

should be updated to:
ExtensionUser = (string)UserDataReader["ExtensionUser"].ToString();

or it actually input a wrong/empty index value as you defined at the beginning in this function:
string ExtensionUser = "";

0
 
Ross-CAuthor Commented:
How did I not spot that, had been looking at it too long. Many thanks for that.
0

Featured Post

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now