Reputation:
I just seem to be losing it today. Can anyone help me find what I'm doing wrong here:
1. for (int y = 0; y < 5; y++)
2. {
3. IDataReader getLineInfo = DB.GetRS("Select LineText From TIF Where SCRID ='" + scRID + "' AND LineNum='" + y + "'");
4. if (getLineInfo.Read())
5. {
6. string[] lineText = new string[y];
7. lineText[y] = (string)getLineInfo["LineText"];
8.
9. ((Label)item.FindControl(string.Format("lbl{0}", y))).Text = "<a href='" + lineText[y] + "' target='_blank'> Link</a>";
10. }
11. getLineInfo.Dispose();
12. getLineInfo.Close();
13. }
I get the error on line 9. I originally had 'y' start at 1 because there is no lineNum == 0 .. but I thought since arrays start with 0 I was messing something up there. But that did not fix my problem. If someone can help me see what I'm not it would be greatly appreciated. Also there is no user input on this page cause I know The whole IDataReader using select statements can be bad.
If any additional info is needed I can write it in, and thanks to anyone who can help
Upvotes: 1
Views: 611
Reputation: 380
Why don't you use just a string instead of an array of strings?
string lineText = (string)getLineInfo["LineText"];
((Label)item.FindControl(string.Format("lbl{0}", y))).Text = "<a href='" lineText + "' target='_blank'> Link</a>";
Upvotes: 2
Reputation: 954
Is there a good reason why
string[] lineText = new string[y];
is inside the loop ? `
And also, if you allocate an array of 'y' elements, then accessing the element at index 'y' is bound to throw an exception. In an array of 'y' elements, the last element is at index 'y-1' (starting from 0).
Upvotes: 1
Reputation: 7934
You need to declare your array like this
string[] lineText = new string[y+1];
Upvotes: 0
Reputation: 273264
string[] lineText = new string[y]; // array 0 .. y-1
lineText[y] = ...; // y = 1 element too far
Also, lineText
is created locally inside the loop, you can simply replace string[] lineText
with string lineText
and forget about y
.
If you think you need y
then there is something else wrong/missing in this code.
Upvotes: 3