0

我正在尝试使用以下代码将我的 sql 表与网格视图绑定:

 string connectionString = WebConfigurationManager.ConnectionStrings["Gen_Lic"].ConnectionString; //<-- error
 string selectSQL = "SELECT * FROM Gen_Lic";
 SqlConnection con = new SqlConnection(connectionString);
 SqlCommand cmd = new SqlCommand(selectSQL, con);
 SqlDataAdapter adapter = new SqlDataAdapter(cmd);
 DataSet ds = new DataSet();

 adapter.Fill(ds, "Gen_Lic");

 Gen_Lic_Grid.DataSource = ds;
 Gen_Lic_Grid.DataBind();

但我不知道我哪里出了问题,但我收到了一个错误:

Object reference not set to an instance of an object.

有什么建议么?

这是我的 web.config 文件:

<connectionStrings>
<add name="Gen_LicConnectionString" connectionString="Data Source=ESHA\SQLEXPRESS;Initial Catalog=Gen_Lic;User ID=sa;Password=sa@" providerName="System.Data.SqlClient" />
</connectionStrings>
4

3 回答 3

1

使用此链接在 Web 配置中添加连接字符串。

http://www.aspdotnet-suresh.com/2011/11/write-connection-strings-in-webconfig.html

您在通话和 webconfig 中使用了不同的名称。

string connectionString = ConfigurationManager.ConnectionStrings["Gen_LicConnectionString"].ConnectionString; 
于 2012-11-29T05:06:00.723 回答
0

您没有打开 SqlConnection。您必须在创建命令变量之前打开连接。

string connectionString = WebConfigurationManager.ConnectionStrings["Gen_Lic"].ConnectionString; //<-- error
 string selectSQL = "SELECT * FROM Gen_Lic";
 SqlConnection con = new SqlConnection(connectionString);
 con.Open();// Need to Open Connection before to Create SQL Comamnd
 SqlCommand cmd = new SqlCommand(selectSQL, con);
 SqlDataAdapter adapter = new SqlDataAdapter(cmd);
 DataSet ds = new DataSet();

 adapter.Fill(ds, "Gen_Lic");

 Gen_Lic_Grid.DataSource = ds;
 Gen_Lic_Grid.DataBind();
于 2012-11-29T06:59:25.783 回答
0

始终检查您的连接字符串并将连接设置为打开。为了安全起见,请始终将连接设置为关闭。

if(connection.State == ConnectionState.Open)
   connection.Close();

connection.Open();
于 2017-07-31T01:59:58.457 回答