-1

Below is my C# code

query = "Select german from words where polish='"+enteredword+"';";
command.CommandText = query;
datareader = command.ExecuteReader();
while (datareader.Read())
     {
        outword = datareader.GetString(1);
        MessageBox.Show(outword);
      }

I have a problem with this part of code. Im getting error "System.IndexOutOfRangeException" in this line

outword = datareader.GetString(1);

Where is the problem? I cant solve it

Finer
  • 95
  • 5
  • 4
    what are your results in datareader? I think you may need to put 0 not 1 – Brad Mar 01 '19 at 12:51
  • 2
    Arrays start at index 0. Everywhere. You retrieve just one field so there is only one index available in the reader buffer. The field is at index 0 – Steve Mar 01 '19 at 12:52
  • 1
    Possible duplicate of [What are good ways to prevent SQL injection?](https://stackoverflow.com/questions/14376473/what-are-good-ways-to-prevent-sql-injection) – mjwills Mar 01 '19 at 12:54

1 Answers1

2

You only select one field. As indexes are zero-based, this

outword = datareader.GetString(1);

needs to be:

outword = datareader.GetString(0);

This is probably test code, in your real code, please use using blocks and parameters in your queries instead of injection prone string formatting.

nvoigt
  • 75,013
  • 26
  • 93
  • 142