From Combobox to textbox error message - c#

private void cbxProducts_SelectedIndexChanged(object sender, EventArgs e)
{
string constring = "Data Source = (LocalDB)\\MSSQLLocalDB; AttachDbFilename = \"C:\\Users\\hannes.corbett\\Desktop\\Barcode Scanning\\Barcode Scanning\\BarcodeDB.mdf\"; Integrated Security = True";
string Query = "SELECT Barcodes, Name, EDate, Quantity, Price FROM Products where Name='" + cbxProducts.Text + "' ; ";
SqlConnection conDataBase = new SqlConnection(constring);
SqlCommand cmdDataBase = new SqlCommand(Query, conDataBase);
SqlDataReader myReader;
try
{
conDataBase.Open();
myReader = cmdDataBase.ExecuteReader();
string sBarcode = myReader["Barcodes"].ToString();
string sName = myReader["Name"].ToString();
var sDate = myReader["EDate"];
string sQuantity = myReader["Quantity"].ToString();
string sPrice = myReader["Price"].ToString();
tbxBar.Text = sBarcode;
tbxName.Text = sName;
sDate = dateDate.Value;
tbxPrice.Text = sPrice;
tbxQua.Text = sQuantity;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
When i try to use this code i just get the error message
"An invalid attempt was made to read when no data was available" I do have data inside of my databse but it still doesn't work.

Reader object fetches rows one by one and we need to tell it to bring the next row by using the Read() method.
You need to call Read() method of SqlDataReader object to read each row, if there is single row expected then you can do via an if otehrwise you would have to do in a while loop like:
while(myReader.Read())
{
string sBarcode = myReader["Barcodes"].ToString();
string sName = myReader["Name"].ToString();
var sDate = myReader["EDate"];
string sQuantity = myReader["Quantity"].ToString();
string sPrice = myReader["Price"].ToString();
tbxBar.Text = sBarcode;
tbxName.Text = sName;
sDate = dateDate.Value;
tbxPrice.Text = sPrice;
tbxQua.Text = sQuantity;
}
another thing is that you should not be doing string concatenation when creating queries, please consider using the parameterized queries as your code is open to SQL Injection. You can read at How to: Execute a Parameterized Query know how to write parameterized queries.

Related

C# MySQL Select all entries in table

My code selects only first entry, but I'm need to select all entries in a table. Is there any way to do it? Thanks!
public string getSiteForRotator()
{
string CommandText = "SELECT `url`, `desc`, `timer` FROM sites";
string Connect = "connection_string";
MySqlConnection myConnection = new MySqlConnection(Connect);
MySqlCommand myCommand = new MySqlCommand(CommandText, myConnection);
myConnection.Open();
MySqlDataReader MyDataReader;
MyDataReader = myCommand.ExecuteReader();
while (MyDataReader.Read())
{
string url = MyDataReader.GetString(0);
string desc = MyDataReader.GetString(1);
int timer = MyDataReader.GetInt32(2);
return url+"," + desc+"," + timer.ToString();
}
MyDataReader.Close();
myConnection.Close();
return "ERROR";
}
As it is now your code return just the first record because in the while loop you exit the method at the first loop with the return that concatenates together the data from the first record. If you want to return all record then
the most simple way, is to use a DataTable
public DataTable getSiteForRotator()
{
DataTable result = new DataTable();
string CommandText = "SELECT `url`, `desc`, `timer` FROM sites";
string Connect = "connection_string";
using(MySqlConnection myConnection = new MySqlConnection(Connect))
using(MySqlDataAdapter da = new MySqlDataAdapter(CommandText))
da.Fill(dt);
return dt;
}
and in your calling code you could check if there are rows in the table and use that rows if there is any of them
DataTable result = getSiteForRotator();
if(result.Rows.Count == 0)
Console.WriteLine("No rows found");
else
... use the rows of the datatable ....
public string getSiteForRotator()
{
string CommandText = "SELECT `url`, `desc`, `timer` FROM sites";
string Connect = "connection_string";
MySqlConnection myConnection = new MySqlConnection(Connect);
MySqlCommand myCommand = new MySqlCommand(CommandText, myConnection);
myConnection.Open();
MySqlDataReader MyDataReader;
MyDataReader = myCommand.ExecuteReader();
string url = "";
while (MyDataReader.Read())
{
url = MyDataReader.GetString(0);
string desc = MyDataReader.GetString(1);
int timer = MyDataReader.GetInt32(2);
url+"," + desc+"," + timer.ToString();
}
MyDataReader.Close();
myConnection.Close();
return url;
}
Is This Helpfull ?? You use return statement in while loop, thats y it only shows single record.

How to display sql query results into textbox on c#?

I'm currently making a voting app on C# Windows Form.
So I made a SQL query to count how many people voted for a specific candidate that will be displayed on textBox4
private void button1_Click(object sender, EventArgs e)
{
string idcan = textBox3.Text;
string score = textBox4.Text;
Connection con = new Connection();
SqlConnection sqlcon = con.Sambung();
sqlcon.Open();
string cek = "select count (ID_Candidate) as Score from DataVote where ID_Candidate = #idcan";
using (sqlcon)
{
SqlCommand com = new SqlCommand(cek, sqlcon);
com.Parameters.Add("idcan", SqlDbType.VarChar, 5).Value = score;
}
try
{
sqlcon.Open();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
How to display the results of the above SQL query to textBox4?
private void button1_Click(object sender, EventArgs e)
{
string idcan = textBox3.Text;
string score = textBox4.Text;
Connection con = new Connection();
SqlConnection sqlcon = con.Sambung();
sqlcon.Open();
string cek = "select count (ID_Candidate) as Score from DataVote where ID_Candidate = #idcan";
using (sqlcon)
{
SqlCommand com = new SqlCommand(cek, sqlcon);
com.Parameters.Add("idcan", SqlDbType.VarChar, 5).Value = score;
}
try
{
sqlcon.Open();
textBox4.Text=Convert.ToString(com.ExecuteScalar());
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
You can actually do this code:
private void button1_Click(object sender, EventArgs e)
{
string idcan = textBox3.Text;
string score = textBox4.Text;
Datatable dt = new DataTable();
Connection con = new Connection();
SqlConnection sqlcon = con.Sambung();
SqlCommand com ;
sqlcon.Open();
string cek = "select count (ID_Candidate) as Score from DataVote where ID_Candidate = #idcan";
using(sqlcon)
{
using(com = new SqlCommand(cek, sqlcon))
{
sqlcon.Open();
com.Parameter.Add("#idcan",score );
SqlDataAdapter da = new SqlDataAdapter(com);
da.File(dt);
if(dt.Rows.Count > 0)
{
textBox4.Text = dt.Rows[0]["Score"].ToString();
}
}
}
}
Since your SELECT statement returns one row with one column, you can use ExecuteScalar to get it.
textBox4.Text = com.ExecuteScalar().ToString();
And your code needs a little bit refactoring like;
using(SqlConnection sqlcon = con.Sambung())
using(SqlCommand com = sqlcon.CreateCommand())
{
com.CommandText = "select count (ID_Candidate) as Score from DataVote where ID_Candidate = #idcan";
com.Parameters.Add("#idcan", SqlDbType.VarChar, 5).Value = score;
sqlcon.Open();
textBox4.Text = com.ExecuteScalar().ToString();
}
By the way, I strongly suspect your ID_Candidate column should be some numeric type instead of VarChar based on it's name.
Expand your question: If your query return as a table (many columns, many rows), you can use this code below. Similar for case return single value.
//Create class to store result value
public class ClassName
{
public string Col1 { get; set; }
public int Col2 { get; set; }
}
// In query code
ClassName[] allRecords = null;
SqlCommand command = ...; // your code
using (var reader = command.ExecuteReader())
{
var list = new List<ClassName>();
while (reader.Read())
list.Add(new ClassName {Col1 = reader.GetString(0), Col2 = reader.GetInt32(1)});
allRecords = list.ToArray();
}

How to show SQL query result in a Textbox?

I have the following code:
dbConnection cn = new dbConnection();
SqlCommand cmd = new SqlCommand();
protected void dropdown_student_SelectedIndexChanged(object sender, EventArgs e)
{
string StudentGUID = dropdown_student.SelectedValue;
cn.con.Open();
cn.cmd.Connection = cn.con;
cn.cmd.CommandText = "select SUM(Marks) AS 'Total' from Marksheet where StudentGUID = " + StudentGUID + " ";
dr = cn.cmd.ExecuteReader();
if (dr.HasRows)
{
while (dr.Read())
{
textbox_total.Text = dr["Total"].ToString();
}
cn.con.Close();
}
}
I want to show the total marks value in the textbox but it does not work. Can anyone point me in the right direction?
Try something like this:
// define your query upfront - using a PARAMETER!
string query = "SELECT SUM(Marks) FROM dbo.Marksheet WHERE StudentGUID = #StudentID;";
// put the SqlConnection and SqlCommand into using blocks
using (dbConnection cn = new dbConnection())
using (SqlCommand cmd = new SqlCommand(query, cn))
{
// define the parameter value
cmd.Parameters.Add("#StudentID", SqlDbType.UniqueIdentifier).Value = dropdown_student.SelectedValue;
cn.Open();
// use ExecuteScalar if you fetch one row, one column exactly
object result = cmd.ExecuteScalar();
cn.Close();
if(result != null)
{
int value = (int)result;
textbox_total.Text = value.ToString();
}
}
You SQL query is wrong. Try like below:
string query = string.Format("SELECT SUM(Marks) FROM dbo.Marksheet WHERE StudentGUID = '{0}';", StudentID);
Always try to follow this kind of standard practice and you will never fail.
Try putting single Quote around the GUID variable in SQL query.
cn.cmd.CommandText = "select SUM(Marks) AS 'Total' from Marksheet where StudentGUID = '" + StudentGUID + " '";

Equivalent C# of this PHP code

Trying to learn C# and I can't quite get a handle on querying and getting results. I'm trying to figure out both how to and the best way of doing the below in C# .NET. It's a MySql database.
//Interact with the DB. Find out if this hashed account #'s in there.
$dbh = $this->getPDO();
$procedure = "SELECT userPass FROM 499Users WHERE accName = :acc";
$call = $dbh->prepare($procedure);
$call->bindParam(':acc', $testAcc, PDO::PARAM_STR);
$call->execute();
//Fetch up to 1 result row
$row = $call->fetch(PDO::FETCH_ASSOC);
This is my latest try: Also I realize I should probably be using parameters, but I just want it to work first
MySqlConnectionStringBuilder conn_string = new MySqlConnectionStringBuilder();
conn_string.Server = "*";
conn_string.UserID = "*";
conn_string.Password = "*";
conn_string.Database = "*";
conn_string.Port = 3306;
MySqlConnection connection = new MySqlConnection(conn_string.ToString());
try
{
Console.WriteLine("Trying to connect to: ..." + conn_string); Console.WriteLine("Connecting to MySQL...");
connection.Open();
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
string hashedAcc = this.HashPassword(acc);
//Verify hashed account
string query = "SELECT userPass FROM 49Users WHERE accName =" + hashedAcc;
MySqlCommand cmd = new MySqlCommand(query, connection);
MySqlDataReader myReader;
myReader = cmd.ExecuteReader();
try
{
while (myReader.Read())
{
Console.WriteLine(myReader.GetString(0));
}
}
finally
{
myReader.Close();
connection.Close();
}
The following WHERE clause:
WHERE accName =" + hashedAcc;
will cause an error if accName is not of type int, it needs quotes around it.
You should use parameterized query just like you did in PDO, it avoid errors like this and SQL injections as well.
var query = "SELECT userPass FROM 49Users WHERE accName = #hashedAcc";
var cmd = new MySqlCommand(query, connection);
cmd.Parameters.AddWithValue("#hashedAcc", hashedAcc);

Connect to two tables

I have created comboBox and filled with one column, after I choose item from the combobox I would like to show other column in the textboxs so I wrote code to make it happen but what if I want to choose column from another table I mean I would like to show couple of columns from two different table in the textbox when I hit the combobox
Here is my code:
private void comboLname_SelectedIndexChanged(object sender, EventArgs e)
{
string conn = "Data Source=srv-db-02;Initial Catalog=rmsmasterdbtest;Persist Security Info=True;User ID=test;Password=*******";
string Query = "select * from rmsmasterdbtest.dbo.customer where LastName= '" + comboLname.Text + "' ;";
SqlConnection Myconn = new SqlConnection(conn);
SqlCommand cmdDataBase = new SqlCommand(Query, Myconn);
SqlDataReader Reader;
try
{
Myconn.Open();
Reader = cmdDataBase.ExecuteReader();
while (Reader.Read())
{
string ID = Reader.GetInt32(Reader.GetOrdinal("ID")).ToString();
string AccountNuber = Reader.GetString(Reader.GetOrdinal("AccountNumber"));
//string Time = Reader.GetString(Reader.GetOrdinal("Time"));
// string Deposit = Reader.GetString(Reader.GetOrdinal("Deposit"));
string sstatus = Reader.GetString(Reader.GetOrdinal("status"));
string slastname = Reader.GetString(Reader.GetOrdinal("lastname"));
txtid.Text = ID;
txtacnum.Text = AccountNuber;
//txttime.Text = Time;
//txtdeposit.Text = Deposit;
txtstatus.Text = sstatus;
txtlname.Text = slastname;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
Myconn.Close();
}
}

Categories