Sibusiso Shongwe Sibusiso Shongwe - 2 months ago 15
ASP.NET (C#) Question

connecting to sql database from ASP.NET master page using c#

i Have this piece of code connecting to the database

SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["savingsConnectionString"].ConnectionString);
string c = "select VersionName ,updated from dbo.DBVersionControl where id = (select max(id) from DBVersionControl)";
SqlCommand cmd = new SqlCommand(c, conn);
conn.Open();
SqlDataReader read = cmd.ExecuteReader();
while(read.Read())
{
Label1.Text = Convert.ToString(read["VersionName"]);
Label2.Text = Convert.ToString(read["Updated"]);
}
conn.Close();
read.Close();


it works when its is located in a normal page but it doesnt work when placed on a master page, no errors are reported though. Is there a way to make this work??

Answer

Place this in your Web.config, with the correct configuration you can use your database in all your Controller's and classes. It is a much cleaner way and edible after you upload your ASP.NET application to a web-server. You can edit the Web.config every time you want. You can't change your connection this easy when you hard-code it in your programm.

<connectionStrings>
  <add name="NorthindConnectionString" 
   connectionString=" Server=MyDataServer;Integrated Security=SSPI;Database=Northwind;"
   providerName="System.Data.SqlClient" />
</connectionStrings>

See this webpage

See this video how you make the connection