How to initialize SelectCommand.Connection property in c#? - c#

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) {
}

Related

Code deleting from datagrid but not in database

My code works in deleting information from the datagrid but does not delete it from the actual database. I am not sure how to fix this. Can i have some assistance please.
MySqlConnection sqlConnection = new MySqlConnection();
MySqlCommand sqlCommand = new MySqlCommand();
DataTable sqlData = new DataTable();
MySqlDataAdapter SqlAdapter = new MySqlDataAdapter();
DataSet sqlSet = new DataSet();
MySqlDataReader sqlDataReader;
//int dmlInfo;
String queried;
String server = "localhost";
String username = "root";
String password = "";
String database = "premiercare";
sqlConnection.Open();
sqlCommand.Connection = sqlConnection;
//removes from database (work to be done)
sqlCommand.CommandText = "Delete from premiercare.addpatient where id = #id";
sqlCommand = new MySqlCommand(queried, sqlConnection);
sqlConnection.Close();
//removes from dataGrid
foreach (DataGridViewRow items in this.dgAddPat.SelectedRows)
{
dgAddPat.Rows.RemoveAt(items.Index);
}
foreach (Control con in gbAddPat.Controls)
{
if (con is TextBox)
((TextBox)con).Clear();
}
loadInfo();
}
You need to make sure the connection and the queryString are correct and then you could do it like this:
//todo: make sure the connectionString is right
using (SqlConnection connection = new SqlConnection(connectionString))
{
//todo: build the right queryString
SqlCommand command = new SqlCommand(queryString, connection);
command.Connection.Open();
command.ExecuteNonQuery();
}
//no need to close the connection because of "using"

Adding integer parameter to stored procedure in ASP.NET C#

While trying to pass an integer parameter #id to a stored procedure, I get an error da.Fill(ds):
Additional information: Conversion failed when converting the varchar value '#id' to data type int.
I have made sure that integer value is passed and stored procedure contain the correct datatype. What other possibilities are there to rectify this error?
SqlConnection conn = new SqlConnection(cs);
conn.Open();
SqlCommand cmd1 = new SqlCommand("asp_GetTrainingDetail", conn);
cmd1.CommandType = CommandType.StoredProcedure;
cmd1.Parameters.AddWithValue("#id", id);
SqlDataAdapter da = new SqlDataAdapter(cmd1);
DataSet ds = new DataSet();
da.Fill(ds);
If you know better, do not use AddWithValue() ... it has to "guess" what datatype you have in your DB based on what you put into the command. It is errorprone and causes unneeded conversions to take place.
Also: use using(..) around disposables, especially when using Database-access as it will close your connections even if exceptions arise - not using using might let some connection stay unclosed.
DataSet ds = new DataSet ();
using (var conn = new SqlConnection (cs))
{
using (var cmd1 = new SqlCommand ("asp_GetTrainingDetail", conn))
{
cmd1.CommandType = CommandType.StoredProcedure;
cmd1.Parameters.Add("#id", System.Data.SqlDbType.BigInt).Value = id;
using (var da = new SqlDataAdapter (cmd1))
{
da.Fill (ds);
}
}
}
Read the link in do not use AddWithValue() for more background infos.
Try this...
SqlConnection conn = new SqlConnection(cs);
conn.Open(); SqlCommand cmd1 = new
SqlCommand("asp_GetTrainingDetail", conn);
cmd1.CommandType = CommandType.StoredProcedure;
cmd1.Parameters.AddWithValue("#id", Int.Parse(id));
SqlDataAdapter da = new SqlDataAdapter(cmd1);
DataSet ds = new DataSet();
da.Fill(ds);

Fill DataTable from Oracle Database Table - C#

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

Is this the right order to clear SqlDataAdapter and Sql Command Parameters and close the connection?

I am new to SQL and C# , I am using windows forms C#.
As shown in the example code, is this the correct order of clearing SqlDataAdapter and clearing Sql Command Parameters and closing the connection?
Please guide me. Thank you
public partial class C1 : UserControl
{
SqlConnection MyConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString);
SqlCommand MyCommand = new SqlCommand();
DataTable DataTable = new DataTable();
SqlDataAdapter Sql_Data_Adapter = new SqlDataAdapter();
public C1()
{
InitializeComponent();
DataTable.Rows.Clear();
DataTable.Columns.Clear();
MyConnection.Open();
MyCommand.CommandText = "SELECT * FROM taqble1";
MyCommand.Connection = MyConnection;
Sql_Data_Adapter.SelectCommand = MyCommand;
Sql_Data_Adapter.Fill(DataTable);
buttonMD1_1.Text = Convert.ToString(DataTable.Rows[0]["Button_Text"]);
buttonMD1_2.Text = Convert.ToString(DataTable.Rows[1]["Button_Text"]);
buttonMD1_3.Text = Convert.ToString(DataTable.Rows[2]["Button_Text"]);
buttonMD1_4.Text = Convert.ToString(DataTable.Rows[3]["Button_Text"]);
// I did not clear DataTable because later I will use it
MyCommand.Parameters.Clear();
Sql_Data_Adapter.Dispose();
MyConnection.Close();
}
The order of distruction of your objects is not too important here, the important thing is to avoid global variables and be sure to always dispose the disposable objects
public C1()
{
InitializeComponent();
using(SqlConnection MyConnection = new SqlConnection(...))
using(SqlCommand MyCommand = new SqlCommand("SELECT * FROM taqble1", MyConnection))
using(SqlDataAdapter adapter = new SqlDataAdapter(MyCommand))
{
DataTable dt = new DataTable();
adapter.Fill(dt);
.... button code ....
}
}
The Using Statement closes and dispose the disposable objects also in case of Exceptions. The DataTable object is local, so when the code exits (and you don't need it anymore) it will be automatically disposed.
Avoid keeping a global object for the connection, there is a Connection Pooling infrastructure that allows to get good performance in using this kind of object. The SqlCommand is lightweight and it is easily rebuilt when you need it, the SqlDataAdapter instead is meant to be reused for updating when you bind the DataTable to a grid, so sometimes is necessary to keep it global.
In your context, I think you should simply use a SqlDataReader instead of an SqlDataAdapter
public C1()
{
InitializeComponent();
using(SqlConnection MyConnection = new SqlConnection(...))
using(SqlCommand MyCommand = new SqlCommand("SELECT * FROM taqble1", MyConnection))
{
DataTable dt = new DataTable();
using(SqlDataReader reader = MyCommand.ExecuteReader())
{
dt.Load(reader);
.... button code ....
}
}
}
I see a lot of time this kind of error, in particular around the connection object. People thinks to get better performances keeping it global. That's not true and both your local and remote resources are stressed with a global connection object.

Adding data to data row of database in c#

I am facing a little problem in my code to add data to sql database attached with my program in ASP.net/C#. Here's code:
string ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["sqlconnection"].ConnectionString;
SqlConnection cnn = new SqlConnection(ConnectionString);
cnn.Open();
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "select Id from TableName";
cmd.Connection = cnn;
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
DataSet ds = new DataSet();
da.Fill(ds, " TableName ");
SqlCommandBuilder cb = new SqlCommandBuilder(da);
DataRow drow = ds.Tables["TableName"].NewRow();
drow["Id"] = TextBox1.Text;
ds.Tables["TableName "].Rows.Add(drow);
da.Update(ds, " TableName ");
string script = #"<script language=""javascript"">
alert('Information have been Saved Successfully.......!!!!!.');
</script>;";
Page.ClientScript.RegisterStartupScript(this.GetType(), "myJScript1", script);
Even when I entered any integer value to the text box, it shows an error message that object is not set to an instance on code:
DataRow drow = ds.Tables["TableName"].NewRow();
Please guide.
Thanks.
This seems like a very bad way of inserting data. Have you looked at the Entity Framework or Linq2Sql? Alternatively you could just use a standard SqlCommand and set the CommandText yourself.
Any of these would provide a cleaner solution.
Eg: With ADO.NET (Connecting to SQLite):
var conn = new SQLiteConnection(string.Format(Constants.SQLiteConnectionString, "db.db3"));
conn.Open();
using (SQLiteTransaction trans = conn.BeginTransaction()) {
using (var cmd = conn.CreateCommand()) {
cmd.CommandText = "INSERT INTO TableName (Id) VALUES (#Id)";
cmd.Parameters.AddWithValue("#Id", someTextVariable);
cmd.ExecuteNonQuery();
}
}

Categories

Resources