Hello folks,
I am having a problem in my program that has apparently no reason to show itself but somehow it is. It actually comes when i run the program using F5 key, the program doesn't work properly while I execute it step by step using F11 key, it works perfectly fine.
Well, here is my problem.
frm_Login obj = new frm_Login();
username = obj.getUsername();
lbl_Welcome.Text = "Welcome "+username;
This given code is placed in another class but when i call it doesn't work.
The code of the function getUsername() is as given below
public string getUsername()
{
SqlConnection con = new SqlConnection(Properties.Settings.Default.ConnectionStr);
string getCurrentUsername = "select User_Name from tblSecUsers where User_ID = '"+tbx_UserID.Text+"'";
con.Open();
SqlCommand cmd = new SqlCommand(getCurrentUsername, con);
SqlDataReader reader = null;
reader = cmd.ExecuteReader();
while (reader.Read())
{
username = reader["User_Name"].ToString();
}
con.Close();
return username;
}
Urgent help required fellows.
Regards.
Loading
Jaish MathewsPosted Mar 21, 2010, 2:12 AM
But I am seeing one possible problem here. Nomally using any Reader object should be closed manually rather than waiting for CLR. Pleasae use the "using" block like below
using (SqlConnection con = new SqlConnection(<
{
//All code here.
}
NB: Publish the actual code here. The code you published may not compile.. :)
Sam HobbsPosted Mar 20, 2010, 10:09 PM
theLizardPosted Mar 20, 2010, 8:52 PM
Farrukh JaveidPosted Mar 20, 2010, 1:43 PM
what i meant was the function getUsername() wont return a value in the other class!
It does return when executing it through F11 key but wont do it when i hit the F5 key.
Sorry again!
Sam HobbsPosted Mar 20, 2010, 1:35 PM
Farrukh JaveidPosted Mar 20, 2010, 10:12 AM
Amit ChoudharyPosted Mar 20, 2010, 1:33 AM
SqlConnection con = new SqlConnection(Properties.Settings.Default.ConnectionStr);
string getCurrentUsername = "select User_Name from tblSecUsers where User_ID = '"+tbx_UserID.Text+"'";
con.Open();
SqlCommand cmd = new SqlCommand(getCurrentUsername, con);
username=cmd.ExecuteScalar().ToString();
con.Close();
return username;
The ExecuteScalar function return only one record. you can use it if only one record from the database is expected.
theLizardPosted Mar 20, 2010, 12:02 AM
SqlDataReader reader = cmd.ExecuteReader();
how many users to you expect out of the database!
using while is pointless, use if(reader.Read()) instead.
you have declared username before the function but you have not sent it to the function so how can you return username if it is not declared? you should not even be able to compile...
using tbx_UserID.Text directly is dangerouse, this is how sql injection attacks work, you need to use parameters.