I'm currently creating a student attendance system using c# and MySQL.
There is a barcode scanner to scan student id. i have stored student information in std_info column and attendance information in std_att column. The scanning and adding is working perfectly. The barcode scanner is scanning the student id number.
How can it be modified to show an error message if the barcode scanner went wrong and someone add data that is not in the database?
Here is the code for add to database:
private void button3_Click(object sender, EventArgs e)
{
cmd = new MySqlCommand();
cmd.CommandText = "insert into std_att (nibm_id, nic, name, address, number, batch) SELECT * FROM `std_info` where nibm_id like '" + textBox1.Text + "%'";
if (textBox1.Text == "")
{
label10.Text = "*Please scan the ID";
errorProvider1.Clear();
}
else
{
con.Open();
cmd.Connection = con;
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Data Inserted ✔️");
string Query = "select * from std_att ;";
MySqlCommand MyCommand2 = new MySqlCommand(Query, con);
MySqlDataAdapter MyAdapter = new MySqlDataAdapter();
MyAdapter.SelectCommand = MyCommand2;
DataTable dTable = new DataTable();
MyAdapter.Fill(dTable);
dataGridView1.DataSource = dTable;
}
}
Barcode scanning part
private void VideoCaptureDevice_NewFrame(object sender, AForge.Video.NewFrameEventArgs eventArgs)
{
Bitmap bitmap = (Bitmap)eventArgs.Frame.Clone();
BarcodeReader reader = new BarcodeReader();
var result = reader.Decode(bitmap);
if (result != null)
{
textBox1.Invoke(new MethodInvoker(delegate ()
{
cmd = new MySqlCommand();
cmd.CommandText = " SELECT * FROM `std_info` where nibm_id like '" + textBox1.Text + "%'";
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
con.Open();
MySqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
textBox1.Text = result.ToString();
label3.Text = dr.GetValue(2).ToString();
label4.Text = dr.GetValue(1).ToString();
label8.Text = dr.GetValue(5).ToString();
}
con.Close();
}));
}
pictureBox1.Image = bitmap;
}
As Llama said in their comment
if(!dr.Read())
{
/* No rows returned from query - run your error code in here */
}
Note that dr.Read() will advance the reader to the next record, so you'll need an else statement to catch the first record if dr.Read() returns true.
You should probably also use using statements around your MySqlCommand and MySqlDataReader statements to ensure they get disposed of properly.
Related
i want to update the datagridview list after clicking on button update here is image
when i select raw heading its shows on textboxes and after changing the value and clicking update its showing msg record updated successfully. here's image.
but its not updating in datagridview..
private void UpdateButton_Click(object sender, EventArgs e)
{
if (ValueTextBox.Text != "" && TypeTextBox.Text != "")
{
cmd = new OleDbCommand("update Sflorotype set Sflorovalues=#value,Sflorotypes=#type where ID=#id", con);
con.Open();
cmd.Parameters.AddWithValue("#id", ID);
cmd.Parameters.AddWithValue("#value", ValueTextBox.Text);
cmd.Parameters.AddWithValue("#type", TypeTextBox.Text);
var returnValue =
cmd.ExecuteNonQuery();
MessageBox.Show("Record Updated Successfully");
con.Close();
DisplayData();
ClearData();
}
else
{
MessageBox.Show("Please Select Record to Update");
}
}
OleDbDataAdapter adapt;
private void DisplayData()
{
con.Open();
DataTable dt = new DataTable();
adapt = new OleDbDataAdapter("select * from Sflorotype", con);
adapt.Fill(dt);
dataGridViewList.DataSource = dt;
con.Close();
}
private void ClearData()
{
ValueTextBox.Text = "";
TypeTextBox.Text = "";
ID = 0;
}
private void dataGridViewList_RowHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{
ID = Convert.ToInt32(dataGridViewList.Rows[e.RowIndex].Cells[0].Value.ToString());
ValueTextBox.Text = dataGridViewList.Rows[e.RowIndex].Cells[1].Value.ToString();
TypeTextBox.Text = dataGridViewList.Rows[e.RowIndex].Cells[2].Value.ToString();
}
Sorry can't add comment - I am new here.
cmd = new OleDbCommand("update Sflorotype set Sflorovalues=#value,Sflorotypes=#type where ID=#id", con);
Are you sure as ID is 94? (at your image, there is ID 94) Because I don't see where you get this value.
I found ID only here, and you set it to 0:
private void ClearData()
{
ValueTextBox.Text = "";
TypeTextBox.Text = "";
ID = 0;
}
I see only here some ID value. And if you don't change it elsewhere, it will update ID with value 0.
You can easily get info what you are executing:
string command = "update Sflorotype set Sflorovalues=#value,Sflorotypes=#type where ID=#id";
MessageBox.Show(command);
cmd = new OleDbCommand(command, con);
EDIT:
try this in your UpdateButton_Click:
cmd = new OleDbCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "update Sflorotype set Sflorovalues=#value,Sflorotypes=#type where ID=#id";
cmd.Parameters.AddWithValue("#value", ValueTextBox.Text);
cmd.Parameters.AddWithValue("#type", TypeTextBox.Text);
cmd.Parameters.AddWithValue("#id", ID);
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery(); {
MessageBox.Show("Record Updated Successfully");
con.Close();
}
DisplayData();
ClearData();
Parameters.AddWithValue("#id", ID) - this should be the last one in adding parameters.
When i search differennt building number in search box it always display first record in the table.
When i tried diffrent building number it does now display it always stay first record of the table.
Can anybody correct my code. Thanks.
private void button3_Click(object sender, EventArgs e)
{
OleDbConnection con2 = new OleDbConnection(#"provider=Microsoft.ACE.OLEDB.12.0;Data Source= C:\Users\test\TDB.accdb");
try
{
con2.Open();
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = con2;
string query = "select * from TestDatabase where Building_No='" + textBox1.Text + "'";
cmd.CommandText = query;
cmd.Parameters.AddWithValue("#Building_No", textBox1.Text);
cmd.Parameters.AddWithValue("#Building_Name", textBox4.Text);
cmd.Parameters.AddWithValue("#Year_", textBox2.Text);
OleDbDataReader reader = cmd.ExecuteReader();
if (reader.Read())
{
textBox4.Text = reader["Building_Name"].ToString();
textBox2.Text = reader["Year_"].ToString();
}
}
catch (Exception)
{
MessageBox.Show("No Reference # found!", "Error");
textBox4.Clear();
textBox2.Clear();
}
}
If the result of 'OleDbCommand.ExecuteReader' is multiple rows
You must call OleDbDataReader.Read() multiple.
example:
while (reader.Read())
{
Console.WriteLine(reader["Building_Name"].ToString());
}
e.g.
textBox4.Text = "";
while (reader.Read())
{
textBox4.Text += reader["Building_Name"].ToString() + ",";
}
It could be because you didn't close the connections. Can you try the code below?
private void button3_Click(object sender, EventArgs e)
{
OleDbConnection con2 = new OleDbConnection(#"provider=Microsoft.ACE.OLEDB.12.0;Data Source= C:\Users\test\TDB.accdb");
try
{
con2.Open();
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = con2;
string query = "select * from TestDatabase where Building_No='" + textBox1.Text + "'";
cmd.CommandText = query;
cmd.Parameters.AddWithValue("#Building_No", textBox1.Text);
cmd.Parameters.AddWithValue("#Building_Name", textBox4.Text);
cmd.Parameters.AddWithValue("#Year_", textBox2.Text);
OleDbDataReader reader = cmd.ExecuteReader();
if (reader.Read())
{
textBox4.Text = reader["Building_Name"].ToString();
textBox2.Text = reader["Year_"].ToString();
}
reader.Close();
cmd.Dispose();
con2.Close();
}
catch (Exception)
{
MessageBox.Show("No Reference # found!", "Error");
textBox4.Clear();
textBox2.Clear();
}
}
I'm trying to retrieve data from a table according to the ID number and insert it to another table. The program is in C# and database in MySQL.
The retrieving table name is student_dt and the table name i want to insert is student_att
Here's what I'm doing so far
private void button1_Click(object sender, EventArgs e)
{
cmd = new MySqlCommand();
cmd.CommandText = "Insert into student_att values(`id`, `nic`, `name`, `address`, `number`, `batch`)";
string Query1 = "select * from student_dt where id like '" + textBox1.Text + "%'";
if (textBox1.Text == "")
{
MessageBox.Show("Please provide all data");
}
else
{
con.Open();
cmd.Connection = con;
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Data Inserted");
string Query = "select * from student_att ;";
MySqlCommand MyCommand2 = new MySqlCommand(Query, con);
MySqlDataAdapter MyAdapter = new MySqlDataAdapter();
MyAdapter.SelectCommand = MyCommand2;
DataTable dTable = new DataTable();
MyAdapter.Fill(dTable);
dataGridView2.DataSource = dTable;
}
You can do from one query
string query = "insert into student_att (`id`, `nic`, `name`, `address`,
`number`, `batch`) select * from student_dt where id like '" + textBox1.Text + "%'"
I am trying to Display a name in the textbox from the database if the ID entered by the user matches the record in the MS ACCESS DATABASE.
I'm getting the error Data type mismatch in criteria expression at the line int count = Convert.ToInt32(cmd.ExecuteScalar());
The following is my aspx.cs code-
protected void Button1_Click(object sender, EventArgs e)
{
clear();
idcheck();
DataTable dt = new DataTable();
OleDbConnection con = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\dfg\fd\Visual Studio 2010\WebSites\WebSite21\App_Data\UPHealth.mdb");
con.Open();
str = "SELECT [DoctorName] FROM [DoctorInfo] WHERE DoctorID='" + TextBox1.Text.Trim() + "'";
OleDbCommand cmd = new OleDbCommand(str, con);
OleDbDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
TextBox2.Text = dr["DoctorID"].ToString();
dr.Close();
con.Close();
}
}
public void idcheck()
{
OleDbConnection con = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\dfg\fd\Visual Studio 2010\WebSites\WebSite21\App_Data\UPHealth.mdb");
con.Open();
str = "SELECT count(DoctorName) FROM [DoctorInfo] WHERE DoctorID='" + TextBox1.Text.Trim() + "'";
OleDbCommand cmd = new OleDbCommand(str, con);
int count = Convert.ToInt32(cmd.ExecuteScalar());
if (count > 0)
{
Label21.Text = "Doctor Name";
}
else
{
Label21.Text = "Id Does not Exist";
}
}
void clear()
{
TextBox2.Text = "";
}
I guess that is because you as passing in an ID, which is usually a numeric value, as a text field:
DoctorID='" + TextBox1.Text.Trim() + "'
Which should be:
DoctorID=" + TextBox1.Text.Trim()
Another problem arises, since you are vulnerable to SQL injection. What if the text box contained 1; delete users? Then your entire users table would be empty. The lesson learned: use parameterized queries!
Then you can express the SQL as:
DoctorID= ?
And add the parameter to the request:
cmd.Parameters.AddWithValue("?", TextBox1.Text.Trim());
I have two combo boxes "Year" & "Amount" on the top of them I do get values for user info, because there are text boxes when called with user ID text boxes fill up with correct data.
The two combo boxes are also filled with correct data but I have to manually select year and the amount corresponding to it.
I need help in when I call the data "Year" & "Amount" should appear visible in the combo box. When I select a Year then the Amount should change accordingly. Last but not the least my reset is not clearing the combo boxes.
using System;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Data;
namespace dss
{
public partial class Form1 : Form
{
SqlConnection con = new SqlConnection("Data Source=USER-PC\\sqlexpress;Initial Catalog=JG_Test;Integrated Security=True");
public Form1()
{
InitializeComponent();
}
private void btnSearch_Click(object sender, EventArgs e)
{
cmbYear.Items.Clear();
string sql = "";
con.Open();
SqlCommand cmd = new SqlCommand();
try
{
sql += "SELECT m.MemberId, m.Name, m.Address, m.Cellular, m.Email, p.PaymentId, p.Year, p.Amount from Members as m";
sql += " INNER JOIN Payments as p ON m.MemberId = p.MemberId";
sql += " WHERE m.MemberId = '" + tbID.Text + "' ORDER BY p.Year ASC";
cmd.Connection = con;
cmd.CommandText = sql;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
con.Close();
if(dt.Rows.Count >0)
{
for(int i = 0; i<=dt.Rows.Count -1;i++)
{
tbID.Text = dt.Rows[i]["MemberId"].ToString();
tbName.Text = dt.Rows[i]["Name"].ToString();
tbCellular.Text = dt.Rows[i]["Cellular"].ToString();
tbEmail.Text = dt.Rows[i]["Email"].ToString();
tbAddress.Text = dt.Rows[i]["Address"].ToString();
cmbAmount.Items.Add(dt.Rows[i]["Amount"].ToString());
cmbYear.Items.Add(dt.Rows[i]["Year"].ToString());
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
}
//This part displaying og the existing data from all the fileds corrssponding within the database//
private void btnAdd_Click(object sender, EventArgs e)
{
{
con.Open();
string Sql = "INSERT INTO Members ( MemberId, Name, Cellular, Email, Address ) VALUES " + " (#Id, #name, #cell, #email, #address)";
using (SqlCommand cmd = new SqlCommand(Sql, con))
{
cmd.CommandText = Sql;
cmd.Parameters.AddWithValue("#Id", tbID.Text);
cmd.Parameters.AddWithValue("#name", tbName.Text);
cmd.Parameters.AddWithValue("#cell", tbCellular.Text);
cmd.Parameters.AddWithValue("#email", tbCellular.Text);
cmd.Parameters.AddWithValue("#address", tbAddress.Text);
cmd.ExecuteNonQuery();
Sql = "INSERT INTO Payments ( MemberId, [Year], [Amount] ) VALUES " + " (#Id, Amount, Year)";
cmd.Parameters.Clear();
cmd.CommandText = Sql;
cmd.Parameters.AddWithValue("#Id", tbID.Text);
cmd.Parameters.AddWithValue("#year", cmbYear.Text);
cmd.Parameters.AddWithValue("#amount", cmbAmount.Text);
cmd.ExecuteNonQuery();
MessageBox.Show("Data Added");
tbID.Clear(); tbName.Clear(); tbCellular.Clear(); tbEmail.Clear(); tbAddress.Clear(); cmbYear.Items.Clear(); cmbAmount.Items.Clear();
con.Close();
}
}
}
//This part represents adding of new input data from all the fileds into the database//
private void btnUpdate_Click(object sender, EventArgs e)
{
try
{
SqlCommand cmd = new SqlCommand();
string Sql = "UPDATE Members SET MemberId = '" + tbID.Text + "', Name = '" + tbName.Text + "', Cellular = '" + tbCellular.Text + "', Email = '" + tbEmail.Text + "', Address = '" + tbAddress.Text + "' WHERE MemberId = '" + tbID.Text + "' ";
cmd.CommandText = Sql;
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
Sql = "UPDATE Payments SET MemberId = '" + tbID.Text + "', Year = '" + cmbYear.Text + "', Amount = '" + cmbAmount.Text + "' WHERE MemberId = '" + tbID.Text + "' ";
cmd.CommandText = Sql;
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Data Updated");
tbID.Clear(); tbName.Clear(); tbAddress.Clear(); tbCellular.Clear(); tbEmail.Clear(); cmbYear.Items.Clear(); cmbAmount.Items.Clear();
}
catch (Exception error)
{
MessageBox.Show(error.ToString());
}
}
//This part represents deleteing of input data from all the fileds into the database//
private void btnDelete_Click(object sender, EventArgs e)
{
try
{
SqlCommand cmd = new SqlCommand();
string Sql = "DELETE FROM Members WHERE MemberId = '" + tbID.Text + "' ";
cmd.CommandText = Sql;
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
Sql = "DELETE FROM Payments WHERE MemberId = '" + tbID.Text + "' ";
cmd.CommandText = Sql;
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
tbID.Clear(); tbName.Clear(); tbAddress.Clear(); tbCellular.Clear(); tbEmail.Clear(); cmbYear.Items.Clear(); cmbAmount.Items.Clear();
MessageBox.Show("Data Deleted");
con.Close();
}
catch (Exception error)
{
MessageBox.Show(error.ToString());
}
}
//This part represents clearing of input data from all the fileds//
private void btnReset_Click(object sender, EventArgs e)
{
tbID.Clear(); tbName.Clear(); tbAddress.Clear(); tbCellular.Clear(); tbEmail.Clear(); cmbYear.Items.Clear(); cmbAmount.Items.Clear();
}
//This part represents shuting down the application//
private void btnExit_Click(object sender, EventArgs e)
{
Application.Exit();
}
}
}
I would be inclined to simplify things a bit. Treat the personal data and the finance data as 2 parts.
Firstly, request the personal data - keep it simple
private void btnSearch_Click(object sender, EventArgs e)
{
string sql = "SELECT MemberId, Name, Address, Cellular, Email FROM Members WHERE MemberId = #Id";
SqlConnection con = new SqlConnection("myconnectionstring");
SqlCommand cmd = new SqlCommand(sql,con);
cmd.Parameters.Add("#Id",SqlDbType.Int).Value = tbID.Text;
DataTable dt = new DataTable();
try
{
con.Open();
dt.Load(cmd.ExecuteReader());
con.Close();
}
catch (Exception ex)
{
con.Close();
Console.WriteLine(ex.Message);
}
tbID.Text = dt.Rows[0]["MemberId"].ToString();
tbName.Text = dt.Rows[0]["Name"].ToString();
tbCellular.Text = dt.Rows[0]["Cellular"].ToString();
tbEmail.Text = dt.Rows[0]["Email"].ToString();
tbAddress.Text = dt.Rows[0]["Address"].ToString();
}
Once thats done, move on to second part - the years/amounts combo (which is almost identical code)
string sql = "SELECT Year, Amount FROM Payments WHERE MemberId = #Id"
SqlConnection con = new SqlConnection("myconnectionstring");
SqlCommand cmd = new SqlCommand(sql,con);
cmd.Parameters.Add("#Id",SqlDbType.Int).Value = tbID.Text;
DataTable dt = new DataTable();
try
{
con.Open();
dt.Load(cmd.ExecuteReader());
con.Close();
}
catch (Exception ex)
{
con.Close();
Console.WriteLine(ex.Message);
}
cmbYear.DataSource = dt;
cmbYear.DisplayMember = "Year";
cmbYear.ValueMember = "Amount";
And finally, tell the textbox what it needs to read by using
private void cmbYear_SelectionChangeCommitted(object sender, EventArgs e)
{
amountTxt.Text = cmbYear.SelectedValue.ToString();
}
in the combobox's SelectionChangeCommitted event
And that should have you sorted!