Click here to Skip to main content
15,885,757 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
what is the c# code for connecting asp.net and sql
Posted

Try:
using (SqlConnection con = new SqlConnection(strConnect))
    {
    con.Open();
    using (SqlCommand com = new SqlCommand("SELECT iD, description FROM myTable", con))
        {
        using (SqlDataReader reader = com.ExecuteReader())
            {
            while (reader.Read())
                {
                int id = (int) reader["iD"];
                string desc = (string) reader["description"];
                Console.WriteLine("ID: {0}\n    {1}", iD, desc);
                }
            }
        }
    }
 
Share this answer
 
 
Share this answer
 
The simplest way of achieving this;

C#
using System.Data.SqlClient;
using System.Data

Page_Load()
{
    SQLConnection con = new SQLConnection();
    SQLCommand cmd;
    SQLDataAdapter adap = new SQLDataAdapter();
    DataTable ds = new DataTable();

    con.connectionstring = ""; //put whatever your connnection string to the db
    con.open();
    cmd = con.CreateCommand();

    //If the command type is purely select statement
    cmd.commandType = CommandType.Text;
    cmd.CommandText = "select * from....";

    //If the command type is a stored procedure
    cmd.CommandType = CommandType.StoredProcedure;
    cmd.CommandText = "sp_LoginDetailsProcess...."; //your stored procedure name

    //If the command type is a stored procedure and has parameters to pass
    cmd.Parameters.Clear();
    cmd.parameters.addwithvalue("ParameterName", "ParameterValue");

    adap.selectcommand = cmd;
    adap.fill(ds);
    con.Close();


}


I would recommend you to put this in to a separate class with different properties if using at many different places. This would be easy to maintain.

--Cheers
Nayan
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900