error when trying to add quantity in windows form - c#

when i try to enter quantity and update the tblcart error shows that as shown in the picture the error comes as incorrect syntax near sdate..can you guys help me solve this problem..i have listed both quantity form and my posform codes below and you can also see the error in the pictures.
This is quantity form code
`using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace POSsystem
{
public partial class frmQty : Form
{
//code to connect sql database
SqlConnection cn = new SqlConnection();
SqlCommand cm = new SqlCommand();
DBConnection dbcon = new DBConnection();
SqlDataReader dr;
private String pcode;
private double price;
private string transno;
string stitle = "Simple POS System";
frmPOS fpos;
public frmQty(frmPOS frmpos)
{
InitializeComponent();
cn = new SqlConnection(dbcon.MyConnection());
fpos = frmpos;
}
private void frmQty_Load(object sender, EventArgs e)
{
}
public void ProductDetails(String pcode, double price, String transno)
{
this.pcode = pcode;
this.price = price;
this.transno = transno;
}
private void frmQty_KeyPress(object sender, KeyPressEventArgs e)
{
}
private void txtQty_KeyPress(object sender, KeyPressEventArgs e)
{
if ((e.KeyChar==13) && (txtQty.Text != String.Empty))
{
cn.Open();
cm = new SqlCommand("insert into tblcart (transno, pcode, price, qty, sdate) values
(#transno, #pcode, #price, #qty, #sdate", cn);
cm.Parameters.AddWithValue("#transno", transno);
cm.Parameters.AddWithValue("#pcode", pcode);
cm.Parameters.AddWithValue("#price", price);
cm.Parameters.AddWithValue("#qty", int.Parse(txtQty.Text));
cm.Parameters.AddWithValue("#sdate", DateTime.Now);
cm.ExecuteNonQuery();
fpos.txtSearch.Clear();
fpos.txtSearch.Focus();
this.Dispose();
}
}
}
}
`
this is the code of posform
`using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace POSsystem
{
public partial class frmPOS : Form
{
SqlConnection cn = new SqlConnection();
SqlCommand cm = new SqlCommand();
SqlDataReader dr;
DBConnection dbcon = new DBConnection();
string stitle = "Simple POS System";
public frmPOS()
{
InitializeComponent();
lblDate.Text = DateTime.Now.ToLongDateString();
cn = new SqlConnection(dbcon.MyConnection());
this.KeyPreview = true;
}
private void button4_Click(object sender, EventArgs e)
{
}
private void label1_Click(object sender, EventArgs e)
{
}
private void label2_Click(object sender, EventArgs e)
{
}
private void GetTransno()
{
try
{
string sdate = DateTime.Now.ToString("yyyyMMdd");
string transno;
int count;
cn.Open();
cm = new SqlCommand("select top 1 transno from tblcart where transno like '" + sdate +
"%' order by id desc", cn);
dr = cm.ExecuteReader();
dr.Read();
if (dr.HasRows) {
transno = dr[0].ToString();
count = int.Parse(transno.Substring(8, 4));
lblTransno.Text = sdate + (count + 1);
} else {
transno = sdate + "1001";
lblTransno.Text = transno;
} dr.Close();
cn.Close();
}
catch (Exception ex)
{
cn.Close();
MessageBox.Show(ex.Message, stitle, MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
private void btnNew_Click(object sender, EventArgs e)
{
GetTransno();
txtSearch.Enabled = true;
txtSearch.Focus();
}
private void txtSearch_Click(object sender, EventArgs e)
{
}
private void txtSearch_TextChanged(object sender, EventArgs e)
{
try
{
if (txtSearch.Text == String.Empty) { return; }
else
{
cn.Open();
cm = new SqlCommand("select * from tblproduct where barcode like '" + txtSearch.Text
+ "'", cn);
dr = cm.ExecuteReader();
dr.Read();
if (dr.HasRows)
{
frmQty frm = new frmQty(this);
frm.ProductDetails(dr["pcode"].ToString(), double.Parse(dr["price"].ToString()),
lblTransno.Text);
frm.ShowDialog();
}
dr.Close();
cn.Close();
}
}
catch (Exception ex)
{
cn.Close();
MessageBox.Show(ex.Message, stitle, MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
}
}
`

very likely is this line cm.Parameters.AddWithValue("#sdate", DateTime.Now);
try using
cm.Parameters.AddWithValue("#sdate", $"'{DateTime.Now:yyyy-MM-dd}'");
not sure about your data schema, but pass a string instead of a DateTime to it.
the above sample code omits the time portion, so make the adjustment you want

Related

When I try to load image from mysql database i get error "Parameter is not valid" and when i try to load an image from db

The program is made in C# and database is MySQL.
I have 2 errors, first one when program loads (parameter is not valid) and second one (You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '(Slika) values (_binary '?PNG).
So i tried the #blob thing (before i was only saving it as pictureBox which people said its false) and i get this error.
Also good to mention that i always get saved the same file which is BLOB - 55B.
This is the code:
private void button3_Click(object sender, EventArgs e)
{
con.OpenConnection2();
string query2 = "update tabla set (Slika) values (#Blob)";
cmd.Connection = Connectioncl.connection2;
cmd.CommandText = query2;
cmd.Parameters.AddWithValue("Blob", save(pictureBox3));
cmd.ExecuteNonQuery();
MessageBox.Show("Data Save in Database ", "Data Save", MessageBoxButtons.OK, MessageBoxIcon.Information);
pictureBox2.Image = pictureBox3.Image;
this.Refresh();
}
I get parameter is invalid in this code where image has to load from database as soon as program is started:
private void Form2_Load(object sender, EventArgs e)
{
try
{
textBox1.Text = Form1.id; //just to check if its the correct ID
con.OpenConnection();
label1.Text = Form1.ime;
label2.Text = Form1.prezime;
timer1.Start();
string query = "select * from tabla where ID='" + ID + "'";
cmd.Connection = Connectioncl.connection;
cmd.CommandText = query;
MySqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
pictureBox2.Image = displayImage((byte[])dr["Slika"]);
}
dr.Close();
con.CloseConnection();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
And here is the whole code of the Form2 (Form1 works perfectly fine):
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
using System.IO;
namespace Maturski_Rad_1
{
public partial class Form2 : Form
{
Connectioncl con = new Connectioncl();
MySqlCommand cmd = new MySqlCommand();
string ID = Form1.id;
public Form2()
{
InitializeComponent();
}
public byte[] save(PictureBox pb)
{
MemoryStream mstr = new MemoryStream();
pictureBox3.Image.Save(mstr, pb.Image.RawFormat);
return mstr.GetBuffer();
}
public Image displayImage(byte[] slika)
{
MemoryStream mstr = new MemoryStream(slika);
return Image.FromStream(mstr);
}
private void Form2_Load(object sender, EventArgs e)
{
try
{
textBox1.Text = Form1.id; //just to check if its the correct ID
con.OpenConnection();
label1.Text = Form1.ime;
label2.Text = Form1.prezime;
timer1.Start();
string query = "select * from tabla where ID='" + ID + "'";
cmd.Connection = Connectioncl.connection;
cmd.CommandText = query;
MySqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
pictureBox2.Image = displayImage((byte[])dr["Slika"]);
}
dr.Close();
con.CloseConnection();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void toolTip1_Popup(object sender, PopupEventArgs e)
{
}
private void button2_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void panel1_MouseHover(object sender, EventArgs e)
{
toolTip1.Show("Vas ID je: " + Form1.id, panel1);
toolTip1.UseFading = true;
}
private void label3_Click(object sender, EventArgs e)
{
}
private void timer1_Tick(object sender, EventArgs e)
{
label4.Text = DateTime.Now.ToShortTimeString();
}
private void button1_Click(object sender, EventArgs e)
{
try
{
OpenFileDialog dialog = new OpenFileDialog();
dialog.Title = "Odaberite sliku";
dialog.Filter = " (*.jpg;*.png;*.jpeg) | *.jpg;*.png;*.jpeg";
DialogResult dr = new DialogResult();
dr = dialog.ShowDialog();
if (dr == DialogResult.OK)
{
pictureBox3.Image = new Bitmap(dialog.FileName);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void button3_Click(object sender, EventArgs e)
{
con.OpenConnection2();
string query2 = "update tabla set (Slika) values (#Blob)";
cmd.Connection = Connectioncl.connection2;
cmd.CommandText = query2;
cmd.Parameters.AddWithValue("Blob", save(pictureBox3));
cmd.ExecuteNonQuery();
MessageBox.Show("Data Save in Database ", "Data Save", MessageBoxButtons.OK, MessageBoxIcon.Information);
pictureBox2.Image = pictureBox3.Image;
this.Refresh();
}
private void pictureBox1_Click(object sender, EventArgs e)
{
if (panel3.Visible = !panel3.Visible)
{
panel3.Visible = panel3.Visible;
}
else if(panel3.Visible = panel3.Visible)
{
panel3.Visible = !panel3.Visible;
}
}
}
}
Thanks for any help!!
UPDATE
So I have decided to insert full data and image directly to table in phpmyadmin and when I entered credentials no errors were showing.
It just seems to be an error while converting to blob while updating the table, now if someone can help me with this i'm pretty new to C# and MySQL especially.
[1]: https://i.stack.imgur.com/KUK7a.png
UPDATE #2
I have changed mstr.GetBuffer() to mstr.GetArray(), also I added few lines to code and there are no more errors at saving picture, but I still have problem when it gets saved its corrupted or it just doesn't convert correctly.
When image gets uploaded it doesn't take nearly as much memory as same image i inserted directly into the table which had no problem loading into program.
So now it's just problem converting to binary ! guess, any help is appreciated!
This is how code looks after I added couple lines to save button:
private void button3_Click(object sender, EventArgs e)
{
byte[] ImageData;
FileStream fs = new FileStream(fname, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
ImageData = br.ReadBytes((int)fs.Length);
br.Close();
fs.Close();
con.OpenConnection2();
string query2 = "update tabla set Slika = '" + ImageData + "' where ID = '" + ID + "'";
cmd.Connection = Connectioncl.connection2;
cmd.CommandText = query2;
cmd.Parameters.AddWithValue("Slika", ImageData);
cmd.ExecuteNonQuery();
MessageBox.Show("Data Save in Database ", "Data Save", MessageBoxButtons.OK, MessageBoxIcon.Information);
this.Refresh();
con.CloseConnection2();
}
I am happy to say that the problem has been fixed, it was indeed problem with saving picture to the database.
The problem was that I had to add parameter MySqlDbType.Blob like so:
cmd.Parameters.Add("#Slika", MySqlDbType.Blob);
And then I had to give that parameter the picture, like so:
cmd.Parameters["#Slika"].Value = ImageData;
Easy as that, feels much more rewarding when you solve the problem yourself :D
I will post the whole code so if someone wants to use it feel free.
Code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
using System.IO;
namespace Maturski_Rad_1
{
public partial class Form2 : Form
{
Connectioncl con = new Connectioncl();
MySqlCommand cmd = new MySqlCommand();
string ID = Form1.id;
string fname;
public Form2()
{
InitializeComponent();
}
public Image displayImage(byte[] slika)
{
MemoryStream mstr = new MemoryStream(slika);
return Image.FromStream(mstr);
}
private void Form2_Load(object sender, EventArgs e)
{
try
{
textBox1.Text = Form1.id; //just to check if its the correct ID
con.OpenConnection();
label1.Text = Form1.ime;
label2.Text = Form1.prezime;
timer1.Start();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
try {
string query = "select Slika,ID from tabla where ID='" + ID + "'";
cmd.Connection = Connectioncl.connection;
cmd.CommandText = query;
MySqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
pictureBox2.Image = displayImage((byte[])dr["Slika"]);
}
dr.Close();
con.CloseConnection();
}
catch
{
MessageBox.Show("Error: Profilna slika nije pronadjena!");
}
}
private void toolTip1_Popup(object sender, PopupEventArgs e)
{
}
private void button2_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void panel1_MouseHover(object sender, EventArgs e)
{
toolTip1.Show("Vas ID je: " + Form1.id, panel1);
toolTip1.UseFading = true;
}
private void label3_Click(object sender, EventArgs e)
{
}
private void timer1_Tick(object sender, EventArgs e)
{
label4.Text = DateTime.Now.ToShortTimeString();
}
private void button1_Click(object sender, EventArgs e)
{
try
{
OpenFileDialog dialog = new OpenFileDialog();
dialog.Title = "Odaberite sliku";
dialog.Filter = " (*.jpg;*.png;*.jpeg) | *.jpg;*.png;*.jpeg";
DialogResult dr = new DialogResult();
dr = dialog.ShowDialog();
if (dr == DialogResult.OK)
{
pictureBox3.Image = new Bitmap(dialog.FileName);
fname = dialog.FileName;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void button3_Click(object sender, EventArgs e)
{
byte[] ImageData;
FileStream fs = new FileStream(fname, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
ImageData = br.ReadBytes((int)fs.Length);
br.Close();
fs.Close();
con.OpenConnection2();
string query2 = "update tabla set Slika= #Slika where ID = '" + ID + "'";
cmd.Connection = Connectioncl.connection2;
cmd.CommandText = query2;
cmd.Parameters.Add("#Slika", MySqlDbType.Blob);
cmd.Parameters["#Slika"].Value = ImageData;
cmd.ExecuteNonQuery();
MessageBox.Show("Data Save in Database ", "Data Save", MessageBoxButtons.OK, MessageBoxIcon.Information);
con.CloseConnection2();
pictureBox2.Image = pictureBox3.Image;
}
private void pictureBox1_Click(object sender, EventArgs e)
{
pictureBox3.Image = pictureBox2.Image;
if (panel3.Visible = !panel3.Visible)
{
panel3.Visible = panel3.Visible;
}
else if(panel3.Visible = panel3.Visible)
{
panel3.Visible = !panel3.Visible;
}
}
}
}
Enjoy!
PS. Slika or #Slika means image in my language, its just that I called my image column in the database like that.

Set a Label text in 1st winform page to display on 2nd form page

Im fairly new to C# so please forgive me if my terminology isn't to par. In my winform application I want to grab a name from a MySQL database # login and display the name on a second page(home.cs). Im currently getting an error which is "An Object Reference is required for the non static field. In login.cs im trying to add something like -> Home.bunifuCustomLabel2.Text = "test"; to set the label in home.cs basically... Login.cs is my 1st loading page and Home.cs is my 2nd page which loads after successful login. I would like to query the database while the connection is open and eventually set the label text for home.cs to display something like Welcome, Name
LOGIN.CS:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
namespace Firemax
{
public partial class Login : Form
{
MySqlConnection con = new MySqlConnection(#"Data Source=xyz.com;port=3333;Initial Catalog = test_db;User Id = fml;password=imscrewed");
int i;
public Login()
{
InitializeComponent();
this.CenterToScreen();
}
private void BunifuMaterialTextbox1_OnValueChanged(object sender, EventArgs e)
{
}
private void BunifuMaterialTextbox2_OnValueChanged(object sender, EventArgs e)
{
bunifuMaterialTextbox2.isPassword = true;
}
private void BunifuFlatButton1_Click(object sender, EventArgs e)
{
i = 0;
con.Open();
MySqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select * from users where username='" + bunifuMaterialTextbox1.Text + "' and password='" + bunifuMaterialTextbox2.Text + "'";
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
da.Fill(dt);
i = Convert.ToInt32(dt.Rows.Count.ToString());
if (i==0)
{
bunifuCustomLabel3.Text = "You have entered either a wrong Username and/or Password";
Home.bunifuCustomLabel2.Text = "test";
}
else
{
this.Hide();
Home fm = new Home();
fm.Show();
fm.Location = this.Location;
}
con.Close();
}
private void BunifuMaterialTextbox1_OnValueChanged_1(object sender, EventArgs e)
{
}
private void BunifuImageButton1_Click(object sender, EventArgs e)
{
this.Close();
}
}
}
HOME.CS:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
namespace Firemax
{
public partial class Home : Form
{
public Home()
{
InitializeComponent();
this.CenterToScreen();
}
private void BunifuImageButton1_Click(object sender, EventArgs e)
{
this.Close();
}
}
}
Welcome to C# world! Changing code of logic.cs to following will eliminate the problem you are facing.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
namespace Firemax
{
public partial class Login : Form
{
MySqlConnection con = new MySqlConnection(#"Data Source=xyz.com;port=3333;Initial Catalog = test_db;User Id = fml;password=imscrewed");
int i;
public Login()
{
InitializeComponent();
this.CenterToScreen();
}
private void BunifuMaterialTextbox1_OnValueChanged(object sender, EventArgs e)
{
}
private void BunifuMaterialTextbox2_OnValueChanged(object sender, EventArgs e)
{
bunifuMaterialTextbox2.isPassword = true;
}
private void BunifuFlatButton1_Click(object sender, EventArgs e)
{
i = 0;
con.Open();
MySqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select * from users where username='" + bunifuMaterialTextbox1.Text + "' and password='" + bunifuMaterialTextbox2.Text + "'";
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
da.Fill(dt);
i = Convert.ToInt32(dt.Rows.Count.ToString());
Home fm = new Home();
if (i==0)
{
bunifuCustomLabel3.Text = "You have entered either a wrong Username and/or Password";
fm.bunifuCustomLabel2.Text = "test";
}
else
{
this.Hide();
fm.Show();
fm.Location = this.Location;
}
con.Close();
}
private void BunifuMaterialTextbox1_OnValueChanged_1(object sender, EventArgs e)
{
}
private void BunifuImageButton1_Click(object sender, EventArgs e)
{
this.Close();
}
}
}
Your code needs improvements. I would highly recommend investing 70 minutes in C# video series by Mosh.
Maybe this can help you
In your first activity
public static string myText= "";
myText=myLabel.Text;
In your second activity Form_Load
seconLabel.Text = Form3.myText;

No value given for one or more required parameters - C#/Access

This is my first time attempting to read an Access database and write each row to the console. When I execute the application I get thrown an exception that says, "No value given for one or more required parameters" on the following statement:
OleDbDataReader reader = cmd.ExecuteReader();
I'm relatively new to c# programming and after hours of research, I can't figure out what I'm doing wrong. Here's my code:
private void maintenanceToolStripMenuItem_Click(object sender, EventArgs e)
{
//Use a variable to hold the SQL statement.
string inputString = "SELECT Full_Name, First_Name, Last_Name, Company FROM CONTACTS";
try
{
//Create an OleDbCommand object and pass in the SQL statement and OleDbConnection object
OleDbCommand cmd = new OleDbCommand(inputString, conn);
//Send the CommandText to the connection, and then build an OleDbDataReader.
OleDbDataReader reader = cmd.ExecuteReader();
while (reader.HasRows)
{
while (reader.Read())
{
Console.WriteLine("\t{0}\t{1}", reader.GetString(1));
reader.NextResult();
}
}
reader.Close();
}
catch (Exception ex)
{
error_message = ex.Message;
MessageBox.Show(error_message);
}
In response to the commenters, I'm posting a larger piece of code to eliminate any assumptions and give a better overall picture of what I'm trying to do:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.OleDb;
using System.IO;
namespace AzFloodSquad
{
public partial class frm1DefaultScreen : Form
{
//Initialize the application
String conn_string = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source = C:\\Databases\\AzFloodSquad\\AzFloodSquad.accdb;Persist Security Info=False;";
OleDbConnection conn = null;
String error_message = "";
String q = "";
string varReportId = "";
public frm1DefaultScreen()
{
InitializeComponent();
}
//Load the default form
private void frm1DefaultScreen_Load(object sender, EventArgs e)
{
connectToolStripMenuItem.PerformClick();
contactsToolStripMenuItem.PerformClick();
}
//Exit the application
private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
Application.Exit();
}
//Start the database
private void connectToolStripMenuItem_Click(object sender, EventArgs e)
{
try
{
conn = new OleDbConnection(conn_string);
conn.Open();
disconnectToolStripMenuItem.Enabled = true;
connectToolStripMenuItem.Enabled = false;
}
catch (Exception ex) { MessageBox.Show(ex.Message); }
}
//Stop the database
private void disconnectToolStripMenuItem_Click(object sender, EventArgs e)
{
try
{
conn.Close();
disconnectToolStripMenuItem.Enabled = false;
connectToolStripMenuItem.Enabled = true;
}
catch (Exception ex) { MessageBox.Show(ex.Message); }
}
//Clean up database whem form close button clicked
private void frm1DefaultScreen_FormClosing(object sender, FormClosingEventArgs e)
{
disconnectToolStripMenuItem.PerformClick();
}
private void contactsToolStripMenuItem_Click(object sender, EventArgs e)
{
varReportId = "Contacts";
q = "SELECT * " +
"FROM CONTACTS WHERE CONTACTS.CONTACT_TYPE = 'CUSTOMER' " +
"OR CONTACTS.CONTACT_TYPE = 'HOMEOWNER' OR CONTACTS.CONTACT_TYPE = 'HOME OWNER' " +
"OR CONTACTS.CONTACT_TYPE = 'TENANT'" +
"ORDER BY FULL_NAME";
this.Cursor = Cursors.WaitCursor;
run_Query_Parm(q);
this.Cursor = Cursors.Default;
}
//Pull data from the database using the parameter field
private void run_Query_Parm(String q)
{
error_message = "";
try
{
OleDbCommand cmd = new OleDbCommand(q, conn);
OleDbDataAdapter a = new OleDbDataAdapter(cmd);
DataTable dt = new DataTable();
a.SelectCommand = cmd;
a.Fill(dt);
results.DataSource = dt;
results.AutoResizeColumns();
}
catch (Exception ex)
{
error_message = ex.Message;
MessageBox.Show(error_message);
}
}
//Clear all data from the screen
private void clearFormToolStripMenuItem_Click(object sender, EventArgs e)
{
varReportId = "";
if (this.results.DataSource != null)
{
this.results.DataSource = null;
}
else
{
this.results.Rows.Clear();
}
}
private void maintenanceToolStripMenuItem_Click(object sender, EventArgs e)
{
//Use a variable to hold the SQL statement.
string inputString = "SELECT Full_Name, First_Name, Last_Name, Company FROM CONTACTS";
try
{
//Create an OleDbCommand object and pass in the SQL statement and OleDbConnection object
OleDbCommand cmd = new OleDbCommand(inputString, conn);
//Send the CommandText to the connection, and then build an OleDbDataReader.
OleDbDataReader reader = cmd.ExecuteReader();
while (reader.HasRows)
{
while (reader.Read())
{
Console.WriteLine("\t{0}\t{1}", reader.GetString(1));
reader.NextResult();
}
}
reader.Close();
}
catch (Exception ex)
{
error_message = ex.Message;
MessageBox.Show(error_message);
}
}
Any help provided would be greatly appreciated. Thanks in advance.
I found the problem. Apparently, I had improper syntax on my SELECT statement. When I replaced my SELECT, (shown in the first code example I posted), with the following, it worked fine:
string inputString = "SELECT Contacts.[Account_Number], " +
"Contacts.[Full_Name], Contacts.[ID], Contacts.[Street], " +
"Contacts.[City], Contacts.[State], Contacts.[Zip] FROM Contacts";

How can I add search button code where I just want to find record and want to display it in listBoxes

I am new to C# and I am making a simple database project in which I want to add a functionality in which if user enter the identity number and click the button all the records will be displayed in the list boxes... Please help me to complete it... the code I want to add is in the last section of the code in button2_click.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace main_form
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=windowDb;Integrated Security=True;Pooling=False");
SqlCommand command = new SqlCommand();
//SqlDataReader dataSearch;
private void Form1_Load(object sender, EventArgs e) {}
private void monthCalendar1_DateChanged(object sender, DateRangeEventArgs e) {}
private void btn_save_Click(object sender, EventArgs e)
{
if(id_Txt.Text!=""& f_txt.Text!=""& Lname_txt.Text!=""& m_txt.Text!=""& dateTimePicker1.Text!=""){
command.Connection = con;
con.Open();
command.CommandText = "insert into people(id,fname,lname,mobile,TDATE) values('"+id_Txt.Text+"','"+f_txt.Text+"','"+Lname_txt.Text+"','"+m_txt.Text+"','"+dateTimePicker1.Text/*Value.ToString()*/+"')";
command.ExecuteNonQuery();
con.Close();
MessageBox.Show("Data Saved Successfully");
id_Txt.Clear();
f_txt.Clear();
Lname_txt.Clear();
m_txt.Clear();
dateTimePicker1.Value = DateTime.Now;
search();
}
}
private void search() {
listBox1.Items.Clear();
listBox2.Items.Clear();
listBox3.Items.Clear();
listBox4.Items.Clear();
listBox5.Items.Clear();
con.Open();
command.CommandText = "select * from people";
command.Connection = con;
SqlDataReader dataSearch = command.ExecuteReader();
if(dataSearch.HasRows){
while (dataSearch.Read())
{
listBox1.Items.Add(dataSearch["id"].ToString());
listBox2.Items.Add(dataSearch["fname"].ToString());
listBox3.Items.Add(dataSearch["lname"].ToString());
listBox4.Items.Add(dataSearch["mobile"].ToString());
listBox5.Items.Add(dataSearch["TDATE"].ToString());
}
}
con.Close();
}
private void btn_view_Click(object sender, EventArgs e)
{
search();
}
private void bn_update_Click(object sender, EventArgs e)
{
if (id_Txt.Text != "" & f_txt.Text != "" & Lname_txt.Text != "" & m_txt.Text != "" & dateTimePicker1.Text != "")
{
command.Connection = con;
con.Open();
command.CommandText = "update people set fname='" + f_txt.Text + "',lname='" + Lname_txt.Text + "',mobile='" + m_txt.Text + "',TDATE='" + dateTimePicker1.Text + "' where id='" +id_Txt.Text + "'";
command.ExecuteNonQuery();
con.Close();
MessageBox.Show("Data updated Successfully");
id_Txt.Clear();
f_txt.Clear();
Lname_txt.Clear();
m_txt.Clear();
dateTimePicker1.Value = DateTime.Now;
search();
}
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
ListBox list = sender as ListBox;
if(list.SelectedIndex!=-1)
{
listBox1.SelectedIndex = list.SelectedIndex;
listBox2.SelectedIndex = list.SelectedIndex;
listBox3.SelectedIndex = list.SelectedIndex;
listBox4.SelectedIndex = list.SelectedIndex;
listBox5.SelectedIndex = list.SelectedIndex;
// retrive to TextBox of AllowDrop events;
/* id_Txt.Text = listBox1.SelectedIndex.ToString();
f_txt.Text = listBox2.SelectedIndex.ToString();
Lname_txt.Text = listBox3.SelectedIndex.ToString();
m_txt.Text = listBox4.SelectedIndex.ToString();
dateTimePicker1.Value = DateTime.Now;*/
id_Txt.Text = listBox1.SelectedItem.ToString();
f_txt.Text = listBox2.SelectedItem.ToString();
Lname_txt.Text = listBox3.SelectedItem.ToString();
m_txt.Text = listBox4.SelectedItem.ToString();
dateTimePicker1.Value = DateTime.Now;
}
}
private void btn_delete_Click(object sender, EventArgs e)
{
if (id_Txt.Text != "")
{
command.Connection = con;
con.Open();
command.CommandText = "delete from people where id='" + id_Txt.Text + "'";
command.ExecuteNonQuery();
con.Close();
MessageBox.Show("Data deleted Successfully");
id_Txt.Clear();
f_txt.Clear();
Lname_txt.Clear();
m_txt.Clear();
dateTimePicker1.Value = DateTime.Now;
search();
}
}
private void label1_Click(object sender, EventArgs e) {}
private void button1_Click(object sender, EventArgs e) {}
private void button2_Click(object sender, EventArgs e)
{
if (text_search.Text == "")
{
MessageBox.Show("Enter the Rollno.");
}
else {
}
}
}
}

Automatic insertion of ID in execution

I have created inserting Employee details in Visual studio 2010.When I click on Add,it displays as added and the id automatically increments in backend.But instead of added,if I had to display as ("You EMP ID is somenumber(eg.10) )in front end while execution,what should I do?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using HRMSController;
using HRMSBusinessEntities;
using System.Data;
namespace HumanResourceManagementSystems
{
public partial class HRMSEmployee : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string username = (string)(Session["LoginUser"]);
if (Session["LoginUser"] != null)
{
lblDisplay.Text = "Welcome..." + username;
}
Calendar1.Visible = false;
Label1.Visible = false;
txtcurrdate.Text = System.DateTime.Now.ToLongDateString();
}
protected void Btnmodified_Click(object sender, EventArgs e)
{
Calendar1.Visible = true;
}
protected void Add_Click(object sender, EventArgs e)
{
EmployeeEntity record = new EmployeeEntity
{
name = txtname.Text,
currentdate = Convert.ToDateTime(txtcurrdate.Text),
modifieddate = Convert.ToDateTime(txtmodifieddate.Text)
};
EmployeeController add = new EmployeeController();
add.Add(record);
Label1.Visible = true;
Label1.Text = "Added" ;
Clear();
}
public void Clear()
{
txtname.Text = "";
txtcurrdate.Text = "";
txtmodifieddate.Text = "";
}
protected void Calendar1_SelectionChanged(object sender, EventArgs e)
{
txtmodifieddate.Text = Calendar1.SelectedDate.ToString();
}
protected void Button3_Click(object sender, EventArgs e)
{
Clear();
}
protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
{
Calendar1.Visible = true;
}
}
}
After adding the record you can pull up the max id record and show the record in the UI
Query might look like
Select * from Employee ORDER BY EmpId DESC LIMIT 1;
As suggested for performance issue we can do
Select max(EmpId) from Employee;
EDIT
add.Add(record);
SqlConnection con = new SqlConnection(ConnString);
con.Open();
IDbCommand Cmd = con.CreateCommand();
Cmd.CommandText = "Select max(EmpId) from Employee";
IDataReader LastID = Cmd.ExecuteReader();
LastID.Read();
Label1.Visible = true;
Label1.Text = Your Empl ID is " + LastID[0].ToString() ;
Clear();
con.Close();
Another way could be
protected void Add_Click(object sender, EventArgs e)
{
EmployeeEntity record = new EmployeeEntity
{
name = txtname.Text,
currentdate = Convert.ToDateTime(txtcurrdate.Text),
modifieddate = Convert.ToDateTime(txtmodifieddate.Text)
};
EmployeeController add = new EmployeeController();
add.Add(record);
Label1.Visible = true;
Label1.Text = "Your Empl ID is " + FetchLastID();
Clear();
}
public string FetchLastID()
{
SqlConnection con = new SqlConnection(ConnString);
con.Open();
IDbCommand Cmd = con.CreateCommand();
Cmd.CommandText = "Select max(EmpId) from Employee";
IDataReader LastID = Cmd.ExecuteReader();
LastID.Read();
return LastID[0].ToString() ;
}

Categories

Resources