[英]data binding for gridview
我正在尝试使用以下代码将我的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配置中添加连接字符串。
http://www.aspdotnet-suresh.com/2011/11/write-connection-strings-in-webconfig.html
您在通话和webconfig中使用了其他名称。
string connectionString = ConfigurationManager.ConnectionStrings["Gen_LicConnectionString"].ConnectionString;
您没有打开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();
始终检查您的连接字符串并将连接设置为打开。 为了安全起见,请始终将您的连接设置为关闭。
if(connection.State == ConnectionState.Open)
connection.Close();
connection.Open();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.