-2

i keep getting this error, but I don't know why, I get it here: Label1.Text = fgmail.ToString(); and here's the full code:

string st = this.pfun.Text;
string sqlstr2 = "select * from hsinfo WHERE rname='" + st + "'";
OleDbCommand cmd = new OleDbCommand(sqlstr2, DBFunction.GenerateConnection("DBS.accdb"));
OleDbDataReader reader = cmd.ExecuteReader();
string fgmail;

while (reader.Read())
{
    fgmail = reader[1].ToString();
}

Label1.Text = fgmail.ToString();
Stephen Kennedy
  • 20,585
  • 22
  • 95
  • 108
Raghad
  • 35
  • 1
  • 6
  • 2
    You have a SQL injection vulerability. – SLaks Jun 25 '19 at 17:12
  • what do you mean by "the last one"? does the "reader[1]" mean the last one? – Raghad Jun 25 '19 at 17:17
  • 3
    You're doing a SELECT and then reading all the results. You set `fgmail` equal to `reader[1]` for each result, which means that when you're done, `fgmail` will get its value from the last row. So in that case why loop through them all if you only want one value? Your query also has no ORDER BY, so if there are multiple results, there's no telling which one you'll get. If you only expect there to be one result, perhaps modify the query to select one column (not `SELECT *`) and use `ExecuteScalar` instead of a reader. – Scott Hannen Jun 25 '19 at 17:19
  • If you are expecting zero or one records from your query, it would be better to use `if (reader.Read())` instead of `while (reader.Read())`. – LarsTech Jun 25 '19 at 17:23
  • Check whether the reader[1] variable has value or not before assigning to a string variable. string.IsNullOrEmpty(reader[1].ToString()); – goofyui Jun 25 '19 at 17:57

2 Answers2

7

If the reader has no rows, the variable will never be assigned.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
  • can you simplify it? – Raghad Jun 25 '19 at 17:13
  • There are several problems in the logic. Look at the comment from @Scott-Hannen. You can initialize your string by string fgmail = String.Empty. This will initialize your string to an empty string – Anil Goel Jun 25 '19 at 17:23
1

The table you're reading might not have any records, if there is no value in the table the loop will not assign anything to your variable.

ipedrosa
  • 28
  • 4