Tuesday, December 2, 2008

How to connect SQL Server uisng Asp.net with C#-Easiest way to get the Connection String

In VS 2005, Drag and drop the SQL DataSource control from the Toolbox.
Configure the SQL DataSource as per the below diagram.If in the server name 'Localhost' doesn't exist, type 'localhost' manually and check the database name, if it shows the database name you can select the proper database, where you have created the tables. If it doesn't shows the database name select the proper server name from the server name dropdown list and try the same.
Once you are configured properly, click Test Connection button, it will show popup message like Test connection succeeded. And then click OK.

Once your connection succeeded, Take the connection string, and put it your code behind file like this, string conn = "Data Source=LOCALHOST;Initial Catalog=master;Integrated Security=True"; So it will be easy for you to use the conncetion string.

Here 'users' is the Table name which belongs to Master DataBase.

public partial class _Default : System.Web.UI.Page
string conn;
SqlConnection con;
SqlDataAdapter da;
DataSet ds;

protected void Page_Load(object sender, EventArgs e)
conn = "Data Source=LOCALHOST;Initial Catalog=master;Integrated Security=True";
con = new SqlConnection(conn );
da = new SqlDataAdapter("select * from users", con);
ds = new DataSet();
protected void Button1_Click(object sender, EventArgs e)
GridView1.DataSource = ds;


No comments: