Sunday, November 27, 2011

c# connect to SQL database through webconfig


1:  protected void Page_Load(object sender, EventArgs e)  
2:    {  
3:      String UserID, UserName, UserEmail, UserFullName;  
4:      //==== Value Assignment ================================================  
5:      //----USER ID  
6:      UserID = System.Security.Principal.WindowsIdentity.GetCurrent().Name.ToString();  
7:      txtUserName_Def.Text = UserID;  
8:      int backslashIndex = UserID.IndexOf("\\") + 1;  
9:      int userCharNum = UserID.Length;  
10:      UserID = UserID.Substring(backslashIndex, userCharNum - backslashIndex);  
11:      //----USER NAME & USER EMAIL  
12:      String strConnectionString = ConfigurationManager.ConnectionStrings["EmpSale2009ConnectionString"].ConnectionString;  
13:      SqlConnection myConnection = new SqlConnection(strConnectionString);  
14:      myConnection.Open();  
15:      SqlCommand command = new SqlCommand("SELECT userName, userEmail, FullName FROM users WHERE userName='" + UserID + "'", myConnection);  
16:      command.ExecuteNonQuery();  
17:      SqlDataReader myreader = command.ExecuteReader();  
18:      while (myreader.Read())  
19:      {  
20:        UserName = (string)myreader["userName"];  
21:        UserEmail = (string)myreader["userEmail"];  
22:        UserFullName = (string)myreader["FullName"];  
23:        txtUserName_Def.Text = UserFullName;  
24:      }  
25:      myreader.Close();  
26:      myConnection.Close();      
27:    }  

No comments: