0

when i run my code the labels stay the same but when i debug it i can see the text changes and then changes back when it is done runnning

public void getData(string a) 
{
    SqlConnection conn = new SqlConnection(@"Data Source=MASSI\FABERSERVER;Initial Catalog=Data.mdf;Integrated Security=True");
    conn.Open();
    SqlCommand command = new SqlCommand("Select UserID,UserName,Email FROM Login Where UserName= '" + a + "'", conn);
    SqlDataReader reader = command.ExecuteReader();

    while (reader.Read())
    {
        label1.Text = reader["UserID"].ToString();
        label2.Text = reader["UserName"].ToString();
        label3.Text = reader["Email"].ToString();
    }

    conn.Close();
}
Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
massi
  • 1
  • 1
    WebForms? WinForms? WPF? – Uwe Keim Jan 01 '15 at 21:25
  • 1
    You are probably after 1 row only. Your While loop should exit after that single row is found and also, you should add logic for when that row is not found using if (reader.HasRows). This link discusses a somewhat better way: http://stackoverflow.com/questions/7836517/enforce-only-single-row-returned-from-datareader but I guess it is a bit advanced. – NoChance Jan 01 '15 at 21:32
  • Your application is open to SQL injection. Use parameterized queries instead. – Daniel Mann Jan 01 '15 at 21:44
  • Are you reloading the form and then not calling getData() again? The changes will not persist automatically. – Steve Wellens Jan 01 '15 at 21:49

1 Answers1

0

Just in case, try this:

public void getData(string a) {
        SqlConnection conn = new SqlConnection(@"Data Source=MASSI\FABERSERVER;Initial Catalog=Data.mdf;Integrated Security=True");
        conn.Open();
        SqlCommand command = new SqlCommand("Select UserID,UserName,Email FROM Login Where UserName= '" + a + "'", conn);
        SqlDataReader reader = command.ExecuteReader();

        string id, name, email;

        while (reader.Read())
        {
            id = reader["UserID"].ToString();
            name = reader["UserName"].ToString();
            email = reader["Email"].ToString();

        }
        conn.Close();

        label1.Text = id;
        label2.Text = name;
        label3.Text = email;
    }
}

Hope, it helps.

Denis Yakovenko
  • 127
  • 2
  • 11