Tuesday, February 22, 2011

How to: Read Connection Strings from the Web.config File

using System.Configuration;
using System.Data;

public static string GetUserName(string userid){
string fullname = "Unknown name";
string connString = ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString; string sqlString = "SELECT * FROM Users WHERE UserID=@UserID";
SqlDataSource sqldatasource = new SqlDataSource(connString, sqlString);
sqldatasource.SelectParameters.Add(new Parameter("UserID", System.Data.DbType.String, userid));

DataView dv = (DataView)sqldatasource.Select(DataSourceSelectArguments.Empty);
if (dv != null && dv.Table != null & dv.Table.Rows.Count > 0)
{
fullname = dv.Table.Rows[0]["FullName"].ToString();
}

return fullname;
}

How to: Read Connection Strings from the Web.config File: "ConnectionStrings.ConnectionStrings['NorthwindConnectionString'];"

No comments: