CODE-how to fetch value from database in asp.net

Posted by Dn2010 under ASP.NET on 1/17/2011 | Points: 10 | Views : 4965 | Status : [Member] | Replies : 3
hi friends,
how to fetch value from database in asp.net

how to create it.


thanks in advance.




Responses

Posted by: Karthikanbarasan on: 1/17/2011 [Member] [Moderator] [Microsoft_MVP] [MVP] Silver | Points: 25

Up
0
Down
SqlDataReader rdr = null;

SqlConnection con = null;
SqlCommand cmd = null;

try
{
// Open connection to the database
string ConnectionString = "server=xeon;uid=sa;"+
"pwd=manager; database=northwind";
con = new SqlConnection(ConnectionString);
con.Open();

// Set up a command with the given query and associate
// this with the current connection.
string CommandText = "SELECT Value" +
" FROM Table" +
" WHERE (Value = 20)";
cmd = new SqlCommand(CommandText);
cmd.Connection = con;

// Execute the query
rdr = cmd.ExecuteReader();

while(rdr.Read())
{
label1.text = (rdr["Value"].ToString();
}
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
// Close data reader object and database connection
if (rdr != null)
rdr.Close();

if (con.State == ConnectionState.Open)
con.Close();
}


Thanks
Karthik
www.f5Debug.net

Dn2010, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: T.saravanan on: 1/18/2011 [Member] [MVP] Silver | Points: 25

Up
0
Down
Hi Dn2010,
Mr.Karthik code refers Connected architecture...
If you using disconnected architecture means refer the following code...
 

String strConn= "Data Source=test_server;Initial Catalog=test_Db;User ID=sa;Password=test;";
String strSQLQuery = "select Id, Name,Salary from Employee where Salary =20"
SqlDataAdapter daConn= new SqlDataAdapter(strSQLQuery , strConn);
DataSet dsData = new DataSet();
// No need to open or close the connection
// since the SqlDataAdapter will do this automatically.
daConn.Fill(dsData);
label1.Text = dsData.Tables[0].Row[0]["Salary"].ToString(); // If output have one record otherwise refer the following loop...
foreach (DataRow drRow in dsData.Tables[0].Rows)
{
lable1.Text += drRow[2].ToString();
}


To learn more about ADO.Net refer the following links....
http://www.csharp-station.com/Tutorials/AdoDotNet/Lesson01.aspx
http://www.codeproject.com/KB/database/DatabaseAcessWithAdoNet1.aspx

Cheers :)

Thanks,
T.Saravanan

Dn2010, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Dn2010 on: 1/18/2011 [Member] Starter | Points: 25

Up
0
Down
thanks to all

Dn2010, if this helps please login to Mark As Answer. | Alert Moderator

Login to post response