我试图在asp.net页面中创建页面,但出现以下错误
错误:-System.NullReferenceException:对象引用未设置为对象的实例。在TestdateAssistor.user_info.Button1_Click1(对象发送方,EventArgs e)
在此行
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Data Source=LAPTOP-O9SI19I0\SQLEXPRESS;Integrated Security=True"].ConnectionString);
这是我完整的代码
try
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Data Source=LAPTOP-O9SI19I0\\SQLEXPRESS;Integrated Security=True"].ConnectionString);
conn.Open();
String insert = "insert into Table (NAME,ADDRESS,MOBILE NO,ADHAR NO,DOB) values (@name,@add,@mob,@adhar,@dob)";
SqlCommand com = new SqlCommand(insert,conn);
com.Parameters.AddWithValue("@name",TextBox1.Text);
com.Parameters.AddWithValue("@add",TextBox2.Text);
com.Parameters.AddWithValue("@mob",TextBox3.Text);
com.Parameters.AddWithValue("@adhar", TextBox4.Text);
com.Parameters.AddWithValue("@dob", TextBox5.Text);
com.ExecuteNonQuery();
Response.Write("Successful Registration!!");
conn.Close();
}
catch (Exception ex)
{
Response.Write("Error:-" + ex.ToString());
}
我应该对连接字符串进行哪些更改?
答案 0 :(得分:2)
您正在使用连接字符串作为Web.config中定义的连接字符串的键。因此,您需要在此处定义连接字符串并为其命名,然后在代码中按名称引用它:
Web.config:
<connectionStrings>
<add name="myConnectionString" connectionString="Data Source=LAPTOP-O9SI19I0\\SQLEXPRESS;Integrated Security=True" />
</connectionStrings>
代码:
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString);
答案 1 :(得分:2)
ConnectionStrings是框架自动为您构建的集合。它的内容是从web.config中检索的,您应该在相应的部分中对其进行定义。
然后,您通过方括号之间的Name
而不是整个连接字符串来获取其值。
string cnString = ConfigurationManager.ConnectionStrings["MyConnection"].ConnectionString;
SqlConnection conn = new SqlConnection(cnString);
,然后在web.config中为连接字符串添加正确的定义
<configuration>
<connectionStrings>
<add name="MyConnection" connectionString="Data Source=LAPTOP-O9SI19I0\\SQLEXPRESS;Integrated Security=True"/>
</connectionStrings>
.....
</configuration>
答案 2 :(得分:1)
错误:
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Data Source=LAPTOP-O9SI19I0\\SQLEXPRESS;Integrated Security=True"].ConnectionString);
解决方案1:
在主程序(.cs)中
SqlConnection conn = new SqlConnection("Data Source=LAPTOP-O9SI19I0\\SQLEXPRESS;Integrated Security=True");
解决方案2:
在web.config
<configuration>
<connectionStrings>
<add name="MyConnection" connectionString="Data Source=LAPTOP-O9SI19I0\\SQLEXPRESS;Integrated Security=True"/>
</connectionStrings>
</configuration>
在主程序(.cs)
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConnection"].ConnectionString;);
参考:https://msdn.microsoft.com/en-us/library/d7469at0(v=vs.110).aspx