简体   繁体   中英

data binding for gridview

I'm trying to bind my sql table with the grid view using the following code:

 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();

But I don't know where I'm going wrong with this, but I'm getting an error:

Object reference not set to an instance of an object.

Any suggestions?

This is my web.config file:

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

Use this link to add connection string in web config.

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

you were using a different name in the call and webconfig.

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

You didn't open SqlConnection. you have to Open Connection before creating a command variable.

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();

Always check your connection string and set the connection to open. to make it safe, set always your connection to close.

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

connection.Open();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM