I am creating a sql project. I used a SqlDatareader and textbox, but when I run it I got an error
InvalidOperationException
My code is this, thanks for your help.
protected void DropDownList2_SelectedIndexChanged(object sender, EventArgs e)
{
if (DropDownList1.SelectedIndex == 0)
{
string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
con.Open();
SqlCommand cmd = new SqlCommand
("USE [PRODUCTS] SELECT QUALITIES FROM dbo.COMPUTERS WHERE ID = 0", con);
SqlDataReader reader;
reader = cmd.ExecuteReader();
TextBox1.Text = reader["QUALITIES"].ToString();
}
}
}
You are not accounting for the case where your data reader has no rows.
Try this:
while(reader.Read())
{
TextBox1.Text = reader["QUALITIES"].ToString();
}
Also note that the "Qualities" field in your database could potentially be null. You will want to protect against this as well.
You should do a couple of error-checking tasks to better understand what is causing the problem. Use a try/catch to analyze the exception more closely. Also add a Finally block to close the reader. And check if the reader has rows:
reader = cmd.ExecuteReader();
try
{
if (reader.HasRows)
{
reader.Read();
if (!reader.IsDBNull(0))
TextBox1.Text = reader.GetString(0);
}
}
catch (Exception ex)
{
// Do something
}
finally
{
reader.Close();
}
Related
I want to pass the information I get from a database to a label. How can I pass the information into a variable.
How can I do this?
private void button1_Click(object sender, EventArgs e)
{
var numero = textBox1.Text;
string connection_string = "datasource=xxx;port=111;username=xxx;password=xxx";
string Query = "select * from xxx.lojass where nome =" + numero;
MySqlConnection conDate = new MySqlConnection(connection_string);
MySqlCommand cmdDate = new MySqlCommand(Query, conDate);
MySqlDataReader myReader;
try
{
conDate.Open();
myReader = cmdDate.ExecuteReader();
MessageBox.Show("Conected");
while (myReader.Read())
{
label1.Text
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Proper coding. Explanation in code comments below
private void button1_Click(object sender, EventArgs e)
{
try
{
const connStr = "datasource=xxx;port=111;username=xxx;password=xxx"; // constant
// Instead of "select *" select particular column(s), it will help with reader columns later
var sql = "select column1 from xxx.lojass where nome = #1"; // you need to parameterize. Never push text box value directly into sql
// important to use "using" to release resources
using (var conn = new MySqlConnection(connStr))
{
using (var cmd = new MySqlCommand(sql, conn))
{
// assuming "nome" is string. If the value is other datatype - convert it
// Better yet - create parameter where you explicitly specify mySql data type
cmd.Parameters.AddWithValue("#1", textBox1.Text);
conn.Open();
using (var reader = cmd.ExecuteReader()) // Since single value expected another way doing it - ExecuteScalar
{
// you only fill one single value, so makes sense to use IF, not WHILE
if (reader.Read())
label1.Text = reader["column1"].ToString();
}
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Query with parameters works perfectly in ms access database. But when I supply the same parameters from C# winforms application it returns no records.
If the parameter is passed to the query then it will use that parameter in where clause, otherwise it will retrieve all records.
bus table sample data:
Ms-Access Query:
PARAMETERS parPlateNo Text ( 255 );
SELECT bus.*
FROM bus
WHERE (((bus.plateNo) Like IIf(IsNull([parPlateNo]), True ,"%" & [parPlateNo] & "%")));
C# Code:
using (OleDbConnection conn = new OleDbConnection(myGlobals.connString))
{
using (OleDbDataAdapter adapter = new OleDbDataAdapter())
{
using (OleDbCommand cmd = conn.CreateCommand())
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "qryBus";
if(plateNo == "")
cmd.Parameters.AddWithValue("?", DBNull.Value);
else
cmd.Parameters.AddWithValue("?", plateNo);
adapter.SelectCommand = cmd;
dsDetails = new DataSet();
adapter.Fill(dsDetails, "details");
}
}
}
PlateNo is a text column.
Remarks: If I remove the like statement in ms access query and run the same code in C#, it will run perfectly and retrieve all the records in table.
After that, I display the data in datagridview using bindingsource.
Why this is happening?
You using oleDB. You have to change that query and use % as wild cards. DAO, and native Access you use *, but for ADO, or oleDB, you have to use % as the wild cards.
Here are a couple of examples that should help you get this up and running.
private void button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("Server=Your_Server_Name;Database=AdventureWorksLT2012;Trusted_Connection=True");
try
{
cmd = new SqlCommand("insert into [dbo].[Student] values(#a,#b,#c)", con);
cmd.Parameters.AddWithValue("#a", int.Parse(textBox1.Text));
cmd.Parameters.AddWithValue("#b", textBox2.Text);
cmd.Parameters.AddWithValue("#c", textBox3.Text);
con.Open();
a = cmd.ExecuteNonQuery();
if (a > 0)
{
MessageBox.Show("Data Submited");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
con.Close();
}
}
AND
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("Server=Your_Server_Name;Database=AdventureWorksLT2012;Trusted_Connection=True");
try
{
cmd = new SqlCommand("select * from student where sid=#a", con);
cmd.Parameters.AddWithValue("#a",int.Parse(comboBox1.SelectedItem.ToString()));
con.Open();
dr = cmd.ExecuteReader();
if (dr.HasRows)
{
if (dr.Read())
{
textBox1.Text = dr["sid"].ToString();
textBox2.Text = dr["fname"].ToString();
textBox3.Text = dr["lname"].ToString();
//label1.Text = dr["cdate"].ToString();
}
}
dr.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
con.Close();
}
}
I'm newbie in C#
I have 2 methods
In the first method, I want to get the result of the execution sql query - this number (for example 123456) and insert the number (123456) into the text field (second method)
but I do not get the result of running sql query
I use System.Data.SqlClient;
Correct my code please.
//Method for retrieving data from a sql query
private void Form_Load(object sender, EventArgs e)
{
string Qry;
Qry = "select number from TableTest ";
try
{
using (SqlConnection sqlConn = new SqlConnection("Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=Database1.mdf;Integrated Security=True"))
using (SqlCommand cmd = new SqlCommand(Qry, sqlConn))
{
sqlConn.Open();
cmd.CommandTimeout = 300;
SqlDataReader reader = cmd.ExecuteReader();
GetNumber(reader.GetString(2));
}
Application.Exit();
}
catch (Exception ex)
{
MessageBox.Show("Error.Form_Clicker_1_Load" + ex.Message);
}
}
You have to call Read() method. Try like:
..
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
GetNumber(reader[2].ToString());
}
..
I have the following code in C#-
private void sendnotificationmail(string enqid)
{
try
{
connection.Open();
List<string> maillist = new List<string>();
string sql = "SELECT TrussLog.repmail, TrussLog.branchemail, TrussEnquiry.DesignerEmail FROM TrussLog FULL OUTER JOIN TrussEnquiry ON TrussLog.enquirynum = TrussEnquiry.Enquiry_ID where TrussEnquiry.Enquiry_ID = '" + enqid + "'";
SqlCommand cmd = new SqlCommand(sql);
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
if (!string.IsNullOrEmpty(reader[0].ToString()))
{
maillist.Add(reader[0].ToString());
}
if (!string.IsNullOrEmpty(reader[1].ToString()))
{
maillist.Add(reader[1].ToString());
}
if (!string.IsNullOrEmpty(reader[2].ToString()))
{
maillist.Add(reader[2].ToString());
}
}
connection.Close();
if (result != DialogResult.Cancel)
{
processmail(maillist);
}
}
catch (Exception)
{
}
}
I am getting the value of the variable enqid from a combobox on my Windows form.The contents of the combobox are retrieved from the database. On form load, the combobox displays the first enquiryID retrieved from the database. When I run my program the data reader skips the loop. However if I select a different enquiry in the combobox, the data reader works properly
It seems that you've forgot to associate Command with the Connection:
// SendNotificationMail is more readable then sendnotificationmail
private void sendnotificationmail(string enqid) {
// put IDisposable into using...
using (SqlConnection con = new SqlConnection("ConnectionStringHere")) {
con.Open();
using (SqlCommand cmd = new SqlCommand()) {
cmd.Connection = con; // <- You've omitted this
// have SQL readable
cmd.CommandText =
#"SELECT TrussLog.repmail,
TrussLog.branchemail,
TrussEnquiry.DesignerEmail
FROM TrussLog FULL OUTER JOIN
TrussEnquiry ON TrussLog.enquirynum = TrussEnquiry.Enquiry_ID
WHERE TrussEnquiry.Enquiry_ID = #prm_Id";
// use parametrized queries
cmd.Parameters.AddWithValue("#prm_Id", enqid);
using (SqlDataReader reader = cmd.ExecuteReader()) {
while (reader.Read()) {
...
}
}
}
}
}
And never, never after write code alike
catch (Exception)
{
}
which means "just ignore all the errors and continue".
I am trying to use a SqlDataReader to run a query and then display the results in a messagebox, but I keep getting the error
Invalid attempt to read when no data is present.
Here is my code.
public void button1_Click(object sender, EventArgs e)
{
string results = "";
using (SqlConnection cs = new SqlConnection(#"Server=100-nurex-x-001.acds.net;Database=Report;User Id=reports;Password=mypassword"))
{
cs.Open();
string query = "select stationipaddress from station where stationname = #name";
using (SqlCommand cmd = new SqlCommand(query, cs))
{
// Add the parameter and set its value --
cmd.Parameters.AddWithValue("#name", textBox1.Text);
using (SqlDataReader dr = cmd.ExecuteReader())
{
while (dr.Read())
{
label3.Text = dr.GetSqlValue(0).ToString();
results = dr.GetValue(0).ToString();
//MessageBox.Show(dr.GetValue(0).ToString());
//MessageBox.Show(results);
}
MessageBox.Show(results);
}
}
}
}
That's correct.
When you exit from the while loop the DataReader has reached the end of the loaded data and thus cannot be used to get the value of a non-existant current record.
The Read method advances the SqlDataReader (dr) to the next record and it returns true if there are more rows, otherwise false.
If you have only one record you could use the results variable in this way
MessageBox.Show(results);
Now, this will work because you have a TOP 1 in your sql statement, but, if you have more than one record, it will show only the value of the last record.
Also as noted by marc_s in its comment, if your table is empty, your code doesn't fall inside the while loop, so probably you could initialize the results variable with a message like:
results = "No data found";
EDIT: Seeing your comment below then you should change your code in this way
.....
// Use parameters **ALWAYS** -- **NEVER** cancatenate/substitute strings
string query = "select stationipaddress from station where stationname = #name";
using (SqlCommand cmd = new SqlCommand(query, cs))
{
// Add the parameter and set its value --
cmd.Parameters.AddWithValue("#name", textBox1.Text);
using (SqlDataReader dr = cmd.ExecuteReader())
{
while (dr.Read())
{
label3.Text = dr.GetSqlValue(0).ToString();
results = dr.GetValue(0).ToString();
}
}
}
.....
I ran into a similar issue trying to get a GUID I knew was there - I could run the same SQL directly in SQL Management Studio and get my result. So instead of trying to bring it back as a GUID (it was saved in a char(35) field, even though it really was a GUID!), I brought it back as a string, instead:
SqlConnection sqlConn = null;
string projId = String.Empty;
string queryString = "SELECT * FROM project WHERE project_name='My Project'";
try
{
sqlConn = new SqlConnection(connString);
SqlCommand cmd = new SqlCommand(queryString, sqlConn);
sqlConn.Open();
SqlDataReader reader = cmd.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
projId = reader.GetSqlValue(0).ToString(); // <-- safest way I found to get the first column's parameter -- increment the index if it is another column in your result
}
}
reader.Close();
sqlConn.Close();
return projId;
}
catch (SqlException ex)
{
// handle error
return projId;
}
catch (Exception ex)
{
// handle error
return projId;
}
finally
{
sqlConn.Close();
}