i have made a form in c# to add data into my datatable, it works fine, all i want is to return a message when the data is inserted, and i am having an issue with that, the code is as follows:
conn.Open();
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = ("INSERT INTO datatable (Number_Plate,Registered_Keeper,Make,Model,Year_Of_Make,Colour,Engine_Size,Transmission,Fuel_Type) Values (#Number_Plate,#Registered_Keeper,#Make,#Model,#Year_Of_Make,#Colour,#Engine_Size,#Transmission,#Fuel_Type)");
cmd.Parameters.AddWithValue("#Number_Plate", Plate.Text);
cmd.Parameters.AddWithValue("#Registered_Keeper", Keeper.Text);
cmd.Parameters.AddWithValue("#Make", Make.Text);
cmd.Parameters.AddWithValue("#Model", Model.Text);
cmd.Parameters.AddWithValue("#Year_Of_Make", Year.Text);
cmd.Parameters.AddWithValue("#Colour", Colour.Text);
cmd.Parameters.AddWithValue("#Engine_Size", Engine.Text);
cmd.Parameters.AddWithValue("#Transmission", Transmission.Text);
cmd.Parameters.AddWithValue("#Fuel_Type", Fuel.Text);
SqlDataReader reader = cmd.ExecuteReader();
if (cmd.ExecuteNonQuery()==1)
{
button1.Visible = false;
label10.Visible = true;
}
else
{
button1.Visible = false;
label10.Text = "Data Not Added Please try Again!";
label10.Visible = true;
}
}
when i run the code, i get an issue with the If statement ane the error is:
There is already an open DataReader associated with this Command which must be closed first.
any help appreciated.
just remove this line (you don't need it)
SqlDataReader reader = cmd.ExecuteReader();
makes no sense because you are inserting a record and not fetching on the database.
snippet,
// other codes
cmd.Parameters.AddWithValue("#Engine_Size", Engine.Text);
cmd.Parameters.AddWithValue("#Transmission", Transmission.Text);
cmd.Parameters.AddWithValue("#Fuel_Type", Fuel.Text);
if (cmd.ExecuteNonQuery()==1)
{
button1.Visible = false;
// other codes
You have open Connection to Database previously. So you need to close that first to execute.
conn.close()
Related
I have a trouble with my coding. This is a source code what I coding for this program.
OracleConnection kon;
public Form2()
{
InitializeComponent();
FillCombo();
}
void FillCombo()
{
OracleConnection kon = Koneksi.getKoneksi();
OracleCommand cmd;
try
{
kon.Open();
cmd = new OracleCommand();
cmd.Connection = kon;
cmd.CommandText = "SELECT * FROM JOBS";
OracleDataReader reader = cmd.ExecuteReader();
comboBox1.Items.Add(reader.GetString(reader.GetOrdinal("JOB_ID")));
}
catch (Exception ex)
{
MessageBox.Show("Data has been failed to show: " + ex.Message);
}
finally
{
kon.Close();
kon.Dispose();
}
}
}
}
When I running this program, system will show dialog "operation is not valid due to the current state of the object".
When I running the Program
There's No Error
How to solve this error? I'll bind data to comboBox from database. I mean, I want to add JOB_ID to combo Box such as AD_VP, HR_REP, etc btw.
Btw, I'm sorry if my English is poor.
One obvious thing that's missing is that you didn't call reader.Read() before attempting to read from your data reader. When you call OracleDataReader reader = cmd.ExecuteReader();, at that moment, the data reader is positioned before the first record. You need to call reader.Read() to move it to the first record. This can easily explain the error you got.
OracleDataReader reader = cmd.ExecuteReader();
reader.Read(); // Add this. Check for a return value of false if necessary.
comboBox1.Items.Add(reader.GetString(reader.GetOrdinal("JOB_ID")));
Apart from that, it would also be a good idea to dispose of the data reader properly. You may want to use a using block for this.
So what youa re trying to do is Adding the ordial number of the JOB_ID column to a combobox. As you probably know GetOrdinal returns in int.
Why don't you just go like this:
...
comboBox1.Items.Add(Convert.ToString(reader.GetOrdinal("JOB_ID")));
...
I'm using Visual Studio 2010 to create a Win Form in c#. It has a handful of Comboboxes, and textboxes that the user can fill out and then submit to an Access DB. My issue comes in when I try to update existing entries. I load an existing entry, make my changes and click update. I do not get any system errors, my connection to the DB is successful, but no changes are actually made to the data. Am I completely missing something? Thanks in advance for any help or insight.
Here is the code for the update button:
private void updateButton_Click_1(object sender, EventArgs e)
{
{
OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\servicereq1.mdb";
OleDbCommand cmd = new OleDbCommand("UPDATE servicereq SET DateLogged = #datelogged, LoggedBy = #loggedby, Function = #function, [Other Impacts] = #summary, Account = #earningsaccount, [From] = #from, [To] = #to, Description = #description, Fixer = #fixer, [Time Estimate] = #timeestimate, [Actual Start] = #actualstart, [Actual Finish] = #actualfinish, [Actual Time] = #actualtime, [Programs/Forms] = #programsforms, Comments = #comments, [Retest Date] = #requestdate, Tester = #tester, Status = #status, [Problem In Environment] = #problemfoundin, [Code In Environment] = #codein WHERE (ServiceRequestNumber = #servreq)");
cmd.Connection = conn;
conn.Open();
if (conn.State == ConnectionState.Open)
{
cmd.Parameters.AddWithValue("#servreq", serviceRequestNumberTextBox.Text);
cmd.Parameters.AddWithValue("#datelogged", dateLoggedTextBox.Text);
cmd.Parameters.AddWithValue("#loggedby", loggedByComboBox.Text);
cmd.Parameters.AddWithValue("#problemfoundin", problem_In_EnvironmentComboBox.Text);
cmd.Parameters.AddWithValue("#function", functionTextBox.Text);
cmd.Parameters.AddWithValue("#summary", other_ImpactsTextBox.Text);
cmd.Parameters.AddWithValue("#earningsaccount", accountTextBox.Text);
cmd.Parameters.AddWithValue("#from", fromTextBox.Text);
cmd.Parameters.AddWithValue("#to", toTextBox.Text);
cmd.Parameters.AddWithValue("#status", statusComboBox.Text);
cmd.Parameters.AddWithValue("#description", descriptionTextBox.Text);
cmd.Parameters.AddWithValue("#fixer", fixerComboBox.Text);
cmd.Parameters.AddWithValue("#codein", code_In_EnvironmentComboBox.Text);
cmd.Parameters.AddWithValue("#programsforms", programs_FormsTextBox.Text);
cmd.Parameters.AddWithValue("#timeestimate", time_EstimateTextBox.Text);
cmd.Parameters.AddWithValue("#actualstart", actual_StartTextBox.Text);
cmd.Parameters.AddWithValue("#actualfinish", actual_FinishTextBox.Text);
cmd.Parameters.AddWithValue("#actualtime", actual_TimeTextBox.Text);
cmd.Parameters.AddWithValue("#requestdate", retest_DateTextBox.Text);
cmd.Parameters.AddWithValue("#tester", testerComboBox.Text);
cmd.Parameters.AddWithValue("#comments", commentsTextBox.Text);
try
{
cmd.ExecuteNonQuery();
MessageBox.Show("Form Updated Successfully");
conn.Close();
}
catch (OleDbException ex)
{
MessageBox.Show(ex.Message);
conn.Close();
}
}
else
{
MessageBox.Show("Connection Failed");
}
}
}
You shouldn't put your database parameters within quotes - they are evaluated as plain text instead of parameters if you do. There is no row where ServiceRequestNumber equals the literal string '#servreq', so nothing is updated.
Also, DataCommands don't pull in local variables as parameters - they must be explicitly added to the DataCommand object (cmd in this case). The reason you aren't getting any errors when you remove your parameter-adding code is because, as stated above, the query doesn't expect any parameters.
Also, the way parameters are being added in the code you removed is strange to say the least. This is much more normal, and significantly easier to read:
cmd.Paramaters.AddWithValue("#paramName", paramData);
//or
cmd.Parameters.Add(new OleDbParameter("#paramName", paramData));
After spending a little more time editing and moving code around, I stumbled on the fact that your parameters must be in the same order in the query as they are when you bind values to them. After making syntactical changes suggested by JoFlash Studios and putting my parameters in the correct order, I was able to make edits to existing data in my form.
I've ordered SQL Server from Somee. I want to use this SQL Server for my windows form. Somehow, i'm not sure, but whenever i execute the login query what i've found, it will have an unhandled exeption.
private void log_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = "workstation id=wbhandler.mssql.somee.com;packet size=4096;user id=acc;pwd=pw;data source=wbhandler.mssql.somee.com;persist security info=False;initial catalog=wbhandler";
con.Open();
string felh = username.Text;
string jelsz = password.Text;
string query = "SELECT * FROM accounts WHERE account=#felhasznalo AND password=#jelszó";
SqlCommand cmd = new SqlCommand(query, con);
cmd.Parameters.Add(new SqlParameter("#felhasznalo", felh));
cmd.Parameters.Add(new SqlParameter("#jelszó", jelsz));
SqlDataReader dr = cmd.ExecuteReader();
if (dr.HasRows == true )
{
MessageBox.Show("Succes");
}
else
{
MessageBox.Show("Failed");
}
}
I thought that the adress is wrong, but then i found on the website the connection string, and now i don't really know.
I'm thinking what's the problem is.
I have 3 schemes in the sql:
dbo, acc, guest.
I first created a table in dbo, then in acc. Now in both of it. But it doesn't execute the SqlDataReader dr = cmd.ExecuteReader();, sadly. Like i said, it has unhandled exeption. Any solution? Any ideas?
(the acc scheme is an example what i created in somee, so it doesn't exist, it's fake)
I also tried this way:
using (var dr = cmd.ExecuteReader())
{
if (dr.HasRows)
{
MessageBox.Show("Sikeres Login!");
}
else
{
MessageBox.Show("Sikertelen Login");
}
}
The problem is always the ExecuteReader()
Try the SqlParameterCollection.AddWithValue Method instead:
cmd.Parameters.AddWithValue("#felhasznalo", felh);
cmd.Parameters.AddWithValue("#jelszó", jelsz);
I will also recommend that you use using statements on your SQL objects to ensure that the unmanaged resources they consume are freed when they are no longer needed. You can read more on the using statement from here.
Another thing that I can suggest is adding Charset=utf8; to your connection string.
I'm trying to use a function via a SQL connection I've done everywhere else in my application (only here it give the error, not the rest of the application). When i searched for what that error code meant the responses i found say it's an error when one can't connect to SQL server? but it doesn't give a solution.
here is my c# code
SqlConnection connection = Database.GetConnection();
DataTable dt = new DataTable("CRC");
SqlCommand cmd = new SqlCommand("SELECT dbo.CalcRentalCharge(#RentalStartDateTime,#RentalEndDateTime,#CarTypeID)", connection);
try
{
connection.Open();
using (SqlDataReader dr = cmd.ExecuteReader())
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.Add("#RentalStartDateTimetext", SqlDbType.DateTime).Value = RentalStartDateTimeBox.Text;
cmd.Parameters.Add("#RentalEndDateTimetext", SqlDbType.DateTime).Value = RentalEndDateTimeBox.Text;
cmd.Parameters.Add("#CarTypeIDtext", SqlDbType.Int).Value = CarTypeID.Text;
connection.Open();
Decimal rentalChange = (Decimal)cmd.ExecuteScalar();
connection.Close();
MessageBox.Show("The rental change is: " + rentalChange.ToString());
if (dr.HasRows)
{
dt.Load(dr);
dataGridView1.DataSource = dt;
}
}
connection.Close();
Can you help me get this FUNCTION to work?
Don't use cmd.ExecuteReader() before adding parameter to command object.
It gives error,
add parameter to command and then cmd.execureReader()
You have a copy/paste error in your variable name:
In the line
cmd.Parameters.Add("#RentalStartDateTimetext", SqlDbType.DateTime).Value = RentalStartDateTimeBox.Text;
the string
RentalStartDateTimetext
needs to be
RentalStartDateTime
In addition to that, because it will pop up as your next error: Your opening and closing of the connection is wrong. Use a using block for the connection as well and open it directly after the start of the block. You don't need to close it manually, the using-block will do that for you.
I am trying to read from datareader but i am gettin the error "Invalid attempt to call Read when reader is closed." The stored procedure is working fine but when i try to read fom datareader it throws error.Plz help me
protected void CheckDatabase()
{
SqlConnection conn = new SqlConnection(GetConnectionString());
conn.Open();
SqlParameter[] param = new SqlParameter[2];
param[0]= new SqlParameter("#EmpID", SqlDbType.Int);
param[0].Value = txtEmpId.Text;
param[1]= new SqlParameter("#Date", SqlDbType.VarChar,50);
param[1].Value = txtDate.Text;
SqlDataReader reader = DNDatabase.ExecuteStoredProcedureReader("RetrieveDeatails", param);
while (reader.Read())
{
gridConfirm.DataSource = reader;
gridConfirm.Columns[0].Visible = false;
gridConfirm.DataBind();
Session["Task_List"] = reader;
}}
here is stored Procedure code
public static SqlDataReader ExecuteStoredProcedureReader(string procedureName, SqlParameter[] parameters)
{
SqlConnection _conn = new SqlConnection(DNDatabase.SQLConnectionString);
SqlCommand cmd = new SqlCommand(procedureName, _conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = procedureName;
cmd.CommandTimeout = 300;
try
{
foreach (SqlParameter param in parameters)
{
cmd.Parameters.Add(param);
}
_conn.Open();
return cmd.ExecuteReader(CommandBehavior.CloseConnection);
}
catch (Exception sqlExc)
{
throw new Exception("An error occured", sqlExc);
}
finally
{
if (_conn != null)
_conn.Close();
}
}
This looks like a bad idea to me:
Session["Task_List"] = reader;
You execute that and then call reader.Read() again, continuing until there's nothing left to read. Presumably you also close the reader at some point (I'd hope - ideally with a using statement). Fundamentally, a SqlDataReader is a connected resource - it's like a stream to the database. It's not something you should be holding onto for longer than you need to, and it's certainly not something you should be putting in a session, even if you didn't effectively invalidate it with the subsequent Read() call.
I assume that data binding works by fetching the data when you call DataBind(), but there's no indication of what you're trying to achieve by putting a reference to the reader itself into the session.
I suggest that:
You isolate whether this is actually to do with the session or the databinding
If it's the session, you pull all of the data you need out (e.g. into a DataTable or some other "disconnected" form)
If it's the databinding, you'll need to do something similar - but as I say, you can hope that that's not the problem, to start with - I assume you saw this sort of databinding elsewhere?
Additionally, you should consider why you want to loop - currently you're basically going to loop over all the results and only the last one is going to be displayed (because you're overwriting the databinding each time). Is that really what you want?
check DNDatabase.ExecuteStoredProcedureReader code may it close the reader after fetchdata
and another thing i should say is:
you can'nt use Session["Task_List"] = reader; because reader is forwardonly
and if you want to keep current value of reader in a seesion load in data table and keep data row of table
DataTable dt = new DataTanle();
dt.Load(dr);
and loop over data table rows
Your method ExecuteStoredProcedureReader has a finally statement which closes the connection. Hence you cannot read anything from the reader. Either close the reader in your method where you call ExecuteStoredProcedureReader or merge both the methods to have them in a single method.