【问题标题】:data binding for gridview网格视图的数据绑定
【发布时间】:2012-11-29 04:52:35
【问题描述】:

我正在尝试使用以下代码将我的 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>

【问题讨论】:

  • 设置断点并确定出错的行
  • web.config 中存在连接字符串“Gen_Lic”?使用 SQL Server 管理工作室检查它
  • 在第一行用这个“Gen_LicConnectionString”替换这个“Gen_Lic”
  • @Syrion 不客气。

标签: c# asp.net data-binding gridview


【解决方案1】:

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

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

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

string connectionString = ConfigurationManager.ConnectionStrings["Gen_LicConnectionString"].ConnectionString; 

【讨论】:

    【解决方案2】:

    您没有打开 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();
    

    【讨论】:

    • 如果您有任何问题,请告诉我。??
    【解决方案3】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多