View Single Post
  #2 (permalink)  
Old June 6th, 2011, 05:59 AM
MohamedHassanAli MohamedHassanAli is offline
Authorized User
 
Join Date: Mar 2011
Posts: 17
Thanks: 3
Thanked 0 Times in 0 Posts
Default

Hi Feng!
I know its a very long time you would have found the answer all by yourself but the point here is if someone comes looking for a similar scenario this post might be of use to them. Find the code below i have commented the statements too for you to understand. Lemme know if u have any problem.

Code:
string _StuName=string.Empty;
SqlConnectionStringBuilder _sqlCon = new SqlConnectionStringBuilder();
_sqlCon.DataSource=".";
_sqlCon.InitialCatalog="Test";
_sqlCon.IntegratedSecurity=true;

SqlConnection con = new SqlConnection(_sqlCon.ConnectionString);

//You need to open the connection to the database
con.Open();

SqlCommand command = new SqlCommand(@"select top 1 StudentName from StudentInfo",con); //You need to pass the Query and the connection or you can also use the SqlCommand.Connection to specify the Connection String

//then u can use the SqlCommand.ExecuteReader() method to execute you query
SqlDataReader sDataReader = command.ExecuteReader();

while(sDataReader.Read())
{
	Console.WriteLine(sDataReader[0].ToString()); //sDataReader[0] takes the First Column
}
sDataReader.Close();
con.Close();