Ich lerne aus einem Textfeld mit einem Klick in eine Datenbank zu schreiben. Ich habe die Verbindungszeichenfolge zu meiner NorthWind-Datenbank in meiner web.config
-Datei angegeben. Ich kann jedoch nicht auf die Verbindungszeichenfolge in meinem Code dahinter zugreifen.
Das habe ich versucht.
protected void buttontb_click(object sender, EventArgs e)
{
System.Configuration.Configuration rootwebconfig = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("/Mohtisham");
System.Configuration.ConnectionStringSettings constring;
constring = rootwebconfig.ConnectionStrings.ConnectionStrings["northwindconnect"];
SqlConnection sql = new SqlConnection(constring);
sql.Open();
SqlCommand comm = new SqlCommand("Insert into categories (categoryName) values ('" + tb_database.Text + "')", sql);
comm.ExecuteNonQuery();
sql.Close();
}
Ich bekomme einen Tooltip-Fehler für
SqlConnection sql = new SqlConnection(constring);
wie
System.data.SqlClient.Sqlconnection.Sqlconnection (Zeichenfolge) enthält einige ungültige Argumente.
Ich möchte die Verbindungszeichenfolge aus dem web.config
in constring
laden
Dies liegt daran, dass die ConnectionStrings
collection eine Sammlung von ConnectionStringSettings
objects ist, der Konstruktor SqlConnection
jedoch einen string
-Parameter erwartet. Sie können also nicht einfach constring
alleine übergeben.
Versuchen Sie es stattdessen.
SqlConnection sql = new SqlConnection(constring.ConnectionString);
Sie können einfach eine Name
zu Ihrer ConnectionString
in der web.config
-Datei geben und dies tun:
web.config:
<add name="ConnectionStringName" connectionString=YourServer"; Initial Catalog=YourDB; Integrated Security=True"/>
Code hinter:
SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionStringName"].ToString());
versuche dies
readonly SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["northwindconnect"].ToString());
Ich werde Ihnen vorschlagen, eine Funktion zu erstellen, anstatt direkt auf die Datei web.config zuzugreifen
public static string GetConfigurationValue(string pstrKey)
{
var configurationValue = ConfigurationManager.AppSettings[pstrKey];
if (!string.IsNullOrWhiteSpace(configurationValue))
return configurationValue;
throw (new ApplicationException(
"Configuration Tag is missing web.config. It should contain <add key=\"" + pstrKey + "\" value=\"?\"/>"));
}
Und nutzen Sie diese Funktion in Ihrer Anwendung