I write a solution in VS2010 that have some C# and asp.net project in it.
I have a configuration class in C# project to make connectionstring for connect to database and it worked well in C# projects, But when I want to use it in Asp web forms the class return a null connectionstring!!!
Please help me because I can't find anything about this problem in web.
Is that need to write another class and using web.config to make connectionstring for asp projects?? or I can reuse class of C# projects for asp projects??
protected void Button_Save_Click(object sender, EventArgs e)
{
try
{
this.intCreatedID = Aryana.Data.Contact.Create(int.Parse(Aryana.Data.FormPublicSetting.GetOption("DefaultGroup"));
}
///The Method to load data from db(the connectionstring in this method return null
public static string GetOption(string title)
{
using (SqlConnection connection = new SqlConnection(Aryana.Data.Configuration.ConnectionString))
{
using (SqlCommand command = new SqlCommand("SET NOCOUNT OFF SELECT Content FROM [dbo].[DefaultSetting] WHERE (Title = @Title)", connection))
{
command.CommandType = CommandType.Text;
command.Parameters.AddWithValue("@Title", title);
connection.Open();
using (SqlDataReader dr = command.ExecuteReader())
{
if (dr.Read())
{
string value = (string)dr["Content"];
return value;
}
else
throw new ObjectDisposedException("title");
}
}
}
}
/// The method to make connectionstring
public static class Configuration
{
static Configuration()
{
string ServerName = Properties.Settings.Default.Server;
string DataBaseName = Properties.Settings.Default.DataBaseName;
connectionString = "data source=" + ServerName + "; initial catalog=" + DataBaseName + ";user id=sa;";
You can get connection string from web.config file
web.config file:
<configuration>
<connectionStrings>
<add name="ConnectionStringName" connectionString="connection string goes here" />
</connectionStrings>
</configuration>
and you can then get the connection string in c# code with:
string connString=ConfigurationManager.ConnectionStrings["ConnectionStringName"].ConnectionString;
ConfigurationManager
class in is System.Configuration
namespace.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.