我正在尝试搜索我的数据库以检索一些结果并将其填充到gridview中。
然而,我在标题中得到了上述错误,并且一些研究并没有真正帮助我解决为什么这种错误标记,并且想知道是否有更敏锐的人能够解释这个错误的原因。我的特定页面代码隐藏文件的代码如下所示:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
namespace StarksComics
{
public partial class search : System.Web.UI.Page
{
SqlConnection con = new SqlConnection();
string b = "";
protected void Page_Load(object sender, EventArgs e)
{
con.ConnectionString = ConfigurationManager.ConnectionStrings["DBVS"].ConnectionString; // the error occurs at this line. ---- nullreference exception was unhandled by code.
if (con.State == ConnectionState.Closed)
{
con.Open();
}
}
private void user_chk()
{
string a;
a = TextBox1.Text;
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "select * from tbCharacters where CharName like'" + a + "%'";
cmd.Connection = con;
SqlDataReader dr;
dr = cmd.ExecuteReader();
if (dr.HasRows)
{
dr.Read();
rep_bind();
GridView1.Visible = true;
TextBox1.Text = "";
}
else
{
GridView1.Visible = false;
b = TextBox1.Text + "is not available in list";
TextBox1.Text="";
}
}
private void rep_bind()
{
string a;
a = TextBox1.Text;
SqlDataAdapter adp = new SqlDataAdapter("select * from tbCharacters where CharName like'" + a + "%'",
ConfigurationManager.ConnectionStrings["DBVS"].ConnectionString);
DataSet ds = new DataSet();
adp.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
}
protected void Button1_Click(object sender, EventArgs e)
{
user_chk();
}
}
}
再一次,非常感谢您审核我的代码。 (我已经注释掉了这行,除非你在页面加载方法中拖动栏,否则它是不可见的。)
答案 0 :(得分:2)
显然它无法找到连接字符串DBVS
。
检查web.config
是否存在。
尝试使用此代码检查连接是否为null:
ConnectionString connStr = ConfigurationManager.ConnectionStrings["DBVS"];
if (connStr == null)
{
throw new Exception("Cannot find connection string DBVS in web.config");
}