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();
Related
I have successfully built connection string and able to populate table data when the database is Access as:
DataTable results = new DataTable();
using (OleDbConnection thisConnection = new OleDbConnection(connectionname))
{
OleDbCommand cmd = new OleDbCommand("SELECT * from TABLE_A", thisConnection); //EDIT : change table name for Oracle
thisConnection.Open();
OleDbDataAdapter adapter = new OleDbDataAdapter(cmd);
adapter.Fill(results);
}
I am new to Oracle though. Can somebody mention what changes to make in above code for Oracle database?
You can try this;
OracleConnection conn = new OracleConnection("Your Connection string");
//Open the connection to the database
conn.Open();
DataSet dataSet = new DataSet();
OracleCommand cmd = new OracleCommand("your select query");
cmd.CommandType = CommandType.Text;
cmd.Connection = conn;
using (OracleDataAdapter dataAdapter = new OracleDataAdapter())
{
dataAdapter.SelectCommand = cmd;
dataAdapter.Fill(dataSet);
}
Basically I am trying to develop a software and I am new in programming. I am trying to insert the data of textbox into SQL Server 2008 R2 Standard and I am getting an error:
System.NullReferenceException was unhandled
Here is my code.
SqlConnection con = new SqlConnection();
con.ConnectionString = "Data Source=(local);Initial Catalog=songs_db;Persist Security Info=True;User ID=sa;Password=iloveyourb";
con.Open();
DataSet ds = new DataSet();
String sql = "Select * From tbl_songdb";
SqlDataAdapter da = new SqlDataAdapter(sql, con);
DataRow drow = ds.Tables["tbl_songdb"].NewRow(); // I am getting error message here.
drow[1] = txt_songName.Text;
drow[2] = txt_minute.Text;
drow[3] = txt_albumnName.Text;
drow[4] = txt_location.Text;
ds.Tables["tbl_songdb"].Rows.Add(drow);
con.Close();
actually my dataset was empty, thats why it was showing NULL error
da.Fill(ds, "tbl_studentData");
i used these lines to fill it and now everything is working fine.
thanks to all for giving their time.
Just do exactly what error said to you. Handle it with try catch like that:
try{
SqlConnection con = new SqlConnection();
con.ConnectionString = "Data Source=(local);Initial Catalog=songs_db;Persist Security Info=True;User ID=sa;Password=iloveyourb";
con.Open();
DataSet ds = new DataSet();
String sql = "Select * From tbl_songdb";
SqlDataAdapter da = new SqlDataAdapter(sql, con);
DataRow drow = ds.Tables["tbl_songdb"].NewRow(); // I am getting error message here.
drow[1] = txt_songName.Text;
drow[2] = txt_minute.Text;
drow[3] = txt_albumnName.Text;
drow[4] = txt_location.Text;
ds.Tables["tbl_songdb"].Rows.Add(drow);
da.Update(ds);
con.Close();
}
catch(Exception ex)
{
MessageBox.Show(ex.ToString());
}
SqlConnection con = new SqlConnection();
con.ConnectionString = "Data Source=(local);Initial Catalog=songs_db;Persist Security Info=True;User ID=sa;Password=iloveyourb";
con.Open();
DataSet ds = new DataSet();
String sql = "Select * From tbl_songdb";
SqlDataAdapter da = new SqlDataAdapter(sql, con);
da.Fill(ds);
DataRow drow = ds.Tables[0].NewRow(); // I am getting error message here.
drow[1] = txt_songName.Text;
drow[2] = txt_minute.Text;
drow[3] = txt_albumnName.Text;
drow[4] = txt_location.Text;
ds.Tables[0].Rows.Add(drow);
SQLiteCommandBuilder cmdbuilder = new SQLiteCommandBuilder(da);
da.InsertCommand = cmdbuilder.GetInsertCommand();
da.Update(ds);
ds.AcceptChanges();
con.Close();
Fill: SelectCommand.Connection property has not been initialized. I have done the coding in button click. Conn is my connection class's object. I have called this connection class in my button click class. Let me know why it shows error? I have already searched answer for this question in Stack overflow and I applied even though it shows the same error. The ddcode.selectedItem.Text is dropdown for select Employee name.
string strQuery = "SELECT MachID, EmpCode, FROM LeaveApply where MachID='" + ddcode.SelectedItem.Text + "'",conn;
SqlCommand cmd = new SqlCommand(strQuery);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);
See it is my connection class
public Connection()
{
conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString);
cmd = null;
}
And I have called this connection class in my button click function's class like
Connection conn = new Connection();
There's no point actually creating a SqlCommand object because the SqlDataAdapter will do it for you. In fact, it can even create the SqlConnection object for you. If you need to reuse the connection then do this:
using (var connection = new SqlConnection(connectionString))
using (var adapter = new SqlDataAdapter(query, connection))
{
adapter.SelectCommand.Parameters.AddWithValue(paramName, paramValue);
// ...
}
and, if you don't need to reuse the connection then do this:
using (var adapter = new SqlDataAdapter(query, connectionString))
{
adapter.SelectCommand.Parameters.AddWithValue(paramName, paramValue);
// ...
}
If you really want to create a separate SqlCommand then do this:
using (var connection = new SqlConnection(connectionString))
using (var command = new SqlCommand(query, connection))
using (var adapter = new SqlDataAdapter(command))
{
command.Parameters.AddWithValue(paramName, paramValue);
// ...
}
I would recommend using the CreateCommand factory method of the connection object to create your command, then your command object will correctly use the connection object.
SqlConnection conn = new SqlConnection("ConnectionString");
conn.Open(); // Make sure connection is open.
string strQuery = "SELECT MachID, EmpCode, FROM LeaveApply where MachID='" + selectedItem + "'";
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = strQuery;
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);
Alternatively you can manually tell the command to use the connection object
cmd.Connection = conn;
It sounds like jmcilhinney has a better answer for your purposes however.
You are missing the connection to your database. The connection will perform the following jobs.
Create a connection to database by using provided connection string.
Open up the connection bridge to transact the data.
Execute the provided query or Stored Procedure.
Fill the data in application's memory
Close the connection bridge to prevent the database.
Use the object of your own connection class.
Try it as follows:
using (Connection Con = new Connection()) {
SqlCommand cmd = new SqlCommand(strQuery);
cmd.Connection = Con;
SqlDataAdapter sda = new SqlDataAdapter(cmd);
try {
Con.Open();
sda.SelectCommand = cmd;
sda.Fill(dt);
Con.Close();
} catch (Exception ex) {
}
When retrieving a datatable from database using the following code in ASP.Net & C#:
The database is located in my local machine.
string connectionString = #"Data Source=CCS90; Initial Catalog=Ribo; Trusted_Connection=True;";
SqlConnection myConn = new SqlConnection(connectionString);
myConn.Open();
SqlCommand sqlCommand = new SqlCommand("SELECT * FROM PUR_POHEADER WHERE POID = #POID", myConn);
sqlCommand.Parameters.Add("#POID", SqlDbType.Int);
sqlCommand.Parameters["#POID"].Value = Convert.ToInt32(request.ReferenceNo);
DataSet DS = new DataSet();
SqlDataAdapter AD = new SqlDataAdapter(sqlCommand, myConn);
//AD.Fill(DS);
AD.Fill(DS, "POTABLE"); //Error arise at this place
DataTable DT = DS.Tables[0];
myConn.Close();
When compiler comes to the line AD.Fill(DS, "POTABLE");, error occurs at Incorrect syntax near '). What may be the reason?
You create a SqlCommand with a SELECT statement and then you don't use it. What is insertStatement? Surely you should be using sqlCommand.
You may try with
AD.Fill(DS);
instead of
AD.Fill(DS,"PORTABLE");
Also try:
SqlDataAdapter AD = new SqlDataAdapter(sqlCommand);
instead of
SqlDataAdapter AD = new SqlDataAdapter(insertStatement, myConn);
Problem is here:
SqlDataAdapter AD = new SqlDataAdapter(insertStatement, myConn);
replace it with:
SqlDataAdapter AD = new SqlDataAdapter(sqlCommand);
and also you are using this overload i think:
AD.Fill(DS, "NameOfDataTable");
then you can access it like this:
DataTable DT = DS.Tables["NameOfDataTable"];
insetad of using 0 index.
I'm using VS2012 and SQL Server Express 2008. I've boiled down my connection/query to try and find out why my DataSet is not being filled. The connection is completed successfully, and no exceptions are thrown, but the adapter does not fill the DataSet. The database that this is pulling from is on the same PC and using localhost\SQLEXPRESS does not change the result. Thanks for any input!
SqlConnection questionConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString);
questionConnection.Open();
String sql = "SELECT * FROM HRA.dbo.Questions";
SqlDataAdapter adapter = new SqlDataAdapter();
DataSet ds = new DataSet();
SqlCommand command = new SqlCommand(sql, questionConnection);
adapter.SelectCommand = command;
adapter.Fill(ds);
adapter.Dispose();
command.Dispose();
questionConnection.Close();
Connection String:
<add name="DefaultConnection" providerName="System.Data.SqlClient" connectionString="Data Source=CODING-PC\SQLEXPRESS;Initial Catalog=HRA;User ID=sa; Password= TEST" />
try this:
SqlConnection questionConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString);
questionConnection.Open();
DataSet ds = new DataSet();
String sql = "SELECT * FROM HRA.dbo.Questions";
SqlDataAdapter adapter = new SqlDataAdapter(sql, questionConnection);
adapter.Fill(ds);
adapter.Dispose();
command.Dispose();
questionConnection.Close();
It appears the answer has already been found, however, I am posting one anyway to advocate the use of using blocks, and also letting the .NET framework do the hardwork for you. Your 11 lines of code can be rewritten in 3:
DataSet ds = new DataSet();
using (var adapter = new SqlDataAdapter("SELECT * FROM HRA.dbo.Questions", ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString))
{
adapter.Fill(ds);
}
Is "HRA.dbo.Questions" an actual table?
Your connectionstring contains an Initial Catalog with value "HRA", and the SQL should only contain dbo.Questions as far as I know.
Check that you dont have the fill statement in another part of the code such as in the page load event.