Could not find file in declared path - c#

C#, WFA, using .NET 4.5 platform,
I dropped textBox1 (firstname), textBox2 (lastname), pictureBox1 (employee phot), button2 (browse), and button1 (save) to insert new employees.
button2 -> must browse image and display in pictureBox1,
button1 -> must save the image, which was browsed by button2 and is in display by pictureBox1, to this table in localhost.
After I run the program, I GET THIS ERROR (file could not be found.)
(I don't get any error on browsing alone though)
I just want answers that contain codes to fix this WFA. Just want to be sure I'm crystal clear on this.
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.IO;
using System.Data.SqlClient;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
SqlConnection cnn = new SqlConnection("Initial Catalog=randomcompany;Data Source=localhost;Integrated Security=SSPI;");
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button2_Click(object sender, EventArgs e) //Browse button
{
try
{
OpenFileDialog dlg = new OpenFileDialog();
dlg.Filter = "Images (*.BMP;*.JPG;*.GIF)|*.BMP;*.JPG;*.GIF|" + "All files (*.*)|*.*";
dlg.Title = "Select Employee Picture";
if (dlg.ShowDialog() == DialogResult.OK)
{
pictureBox1.Image = System.Drawing.Image.FromFile(dlg.FileName);
pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void button1_Click(object sender, EventArgs e) //Save button
{
try
{
cnn.Open();
string path = pictureBox1.Image.ToString();
Byte[] imagedata = File.ReadAllBytes(path);
SqlCommand cmd = new SqlCommand("INSERT INTO Employees (EmployeeFirstname, EmployeeLastname, EmployeePhoto) VALUES (#item1,#item2,#img", cnn);
cmd.Parameters.AddWithValue("#item1", textBox1.Text);
cmd.Parameters.AddWithValue("#item2", textBox2.Text);
cmd.Parameters.AddWithValue("#img", imagedata);
cmd.ExecuteNonQuery();
cnn.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}

When you try to get image file path from your image here:
string path = pictureBox1.Image.ToString();
you actually get the name of Image type (System.Drawing.Bitmap)
You need to keep path to image file after selecting it in dialog. You can do it like this:
pictureBox1.Image = System.Drawing.Image.FromFile(dlg.FileName);
pictureBox1.Tag = dlg.FileName;
Then you need to read this name like this:
string path = pictureBox1.Tag as string;

The issue is that this:
string path = pictureBox1.Image.ToString();
does not return a path. Store the path when you get it in a class field. Let's name it _path:
private string _path;
and then let's set it when you get the file name:
_path = dlg.FileName;
and then just use it here:
Byte[] imagedata = File.ReadAllBytes(_path);
Here is the full code modified:
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.IO;
using System.Data.SqlClient;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
private string _path;
SqlConnection cnn = new SqlConnection("Initial Catalog=randomcompany;Data Source=localhost;Integrated Security=SSPI;");
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button2_Click(object sender, EventArgs e) //Browse button
{
try
{
OpenFileDialog dlg = new OpenFileDialog();
dlg.Filter = "Images (*.BMP;*.JPG;*.GIF)|*.BMP;*.JPG;*.GIF|" + "All files (*.*)|*.*";
dlg.Title = "Select Employee Picture";
if (dlg.ShowDialog() == DialogResult.OK)
{
pictureBox1.Image = System.Drawing.Image.FromFile(dlg.FileName);
_path = dlg.FileName;
pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void button1_Click(object sender, EventArgs e) //Save button
{
try
{
cnn.Open();
Byte[] imagedata = File.ReadAllBytes(_path);
SqlCommand cmd = new SqlCommand("INSERT INTO Employees (EmployeeFirstname, EmployeeLastname, EmployeePhoto) VALUES (#item1,#item2,#img", cnn);
cmd.Parameters.AddWithValue("#item1", textBox1.Text);
cmd.Parameters.AddWithValue("#item2", textBox2.Text);
cmd.Parameters.AddWithValue("#img", imagedata);
cmd.ExecuteNonQuery();
cnn.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}

You are using wrong property to get the image path. You should you
PictureBox.ImageLocation property of picture box to get the exact location of image.
Modify this part
private void button1_Click(object sender, EventArgs e) //Save button
{
try
{
cnn.Open();
string path = pictureBox1.ImageLocation; // this will work
string path = pictureBox1.Image.ToString(); // here error comes
Byte[] imagedata = File.ReadAllBytes(path);
SqlCommand cmd = new SqlCommand("INSERT INTO Employees (EmployeeFirstname, EmployeeLastname, EmployeePhoto) VALUES (#item1,#item2,#img", cnn);
cmd.Parameters.AddWithValue("#item1", textBox1.Text);
cmd.Parameters.AddWithValue("#item2", textBox2.Text);
cmd.Parameters.AddWithValue("#img", imagedata);
cmd.ExecuteNonQuery();
cnn.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}

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.

error when trying to add quantity in windows form

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

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;

Convert this upload image-application to MVC architecture

So I've created this image uploader following a tutorial. The problem is that i did all of it in the frame. Now i want to make it MVC. I've created classes for Controller and Dataaccesslayer. Can someone help me get started?
Regards William
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.IO;
namespace ImageSaveToSQLServer
{
public partial class Form1 : Form
{
SqlConnection conn = new SqlConnection("server=localhost; Trusted_Connection=yes; database=ImageDataBase");
SqlCommand command;
string imgLoc = "";
public Form1()
{
InitializeComponent();
}
private void pictureBox1_Click(object sender, EventArgs e)
{
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void buttonBrowse_Click(object sender, EventArgs e)
{
try
{
OpenFileDialog dlg = new OpenFileDialog();
dlg.Filter = "JPG Files (*.jpg)|*.jpg|GIF Files (*.gif)|*.gif|All Files (*.*)|*.*";
dlg.Title = "Select Employee Picture";
if(dlg.ShowDialog() == DialogResult.OK)
{
imgLoc = dlg.FileName.ToString();
picEmp.ImageLocation = imgLoc;
}
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void buttonSave_Click(object sender, EventArgs e)
{
try {
byte[] img = null;
FileStream fs = new FileStream(imgLoc, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
img = br.ReadBytes((int)fs.Length);
string sql = "INSERT INTO Employee(EID,FIRST_NAME,LAST_NAME,IMAGE)VALUES("+textBoxEID.Text+",'"+textBoxFNAME.Text+"','"+textBoxLname.Text+"',#img)";
if (conn.State != ConnectionState.Open)
conn.Open();
command = new SqlCommand(sql, conn);
command.Parameters.Add(new SqlParameter("#img",img));
int x = command.ExecuteNonQuery();
conn.Close();
MessageBox.Show(x.ToString() + " record(s) saved.");
textBoxEID.Text = "";
textBoxFNAME.Text = "";
textBoxLname.Text = "";
picEmp.Image = null;
}
catch (Exception ex)
{
conn.Close();
MessageBox.Show(ex.Message);
}
}
private void buttonShow_Click(object sender, EventArgs e)
{
try
{
string sql = "SELECT FIRST_NAME,LAST_NAME,IMAGE FROM Employee WHERE EID="+textBoxEID.Text+"";
if(conn.State!=ConnectionState.Open)
conn.Open();
command = new SqlCommand(sql, conn);
SqlDataReader reader = command.ExecuteReader();
reader.Read();
if (reader.HasRows)
{
textBoxFNAME.Text=reader[0].ToString();
textBoxLname.Text=reader[1].ToString();
byte[] img = (byte[])(reader[2]);
if(img==null)
picEmp.Image= null;
else
{
MemoryStream ms = new MemoryStream(img);
picEmp.Image = Image.FromStream(ms);
}
}
else
{
MessageBox.Show("FINNS INTE");
}
conn.Close();
}
catch(Exception ex)
{
conn.Close();
MessageBox.Show(ex.Message);
}
}
}
}
here i leave you a link with a nice implementation, it has a demo so you wont have any kind of trouble testing it.
http://www.codeproject.com/Articles/379980/Fancy-ASP-NET-MVC-Image-Uploader

Pop up access denied message when certain button is clicked depending on which user has logged in

In login form, When I login as Jack which exist in the DOCTOR table, it will go to page_two. I want to pop up a access denied message if nurse button 1 or nurse button 2 is clicked since Jack is not a nurse but a doctor. Then for the opposite, if I login as Mary, which exist in the NURSE table, it will go to page_two. I want to pop up a access denied message when doctor button 1 or doctor button 2 is clicked since Mary is not a doctor but a nurse.
The button names for Page_two is btnDoctor1, btnDoctor2, btnNurse1 and btnNurse2
**//login Form codes**
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Configuration;
namespace GRP_02_03_SACP
{
public partial class page_one : Form
{
public page_one()
{
InitializeComponent();
}
private void page_one_Load(object sender, EventArgs e)
{
}
private void btnLogin_Click(object sender, EventArgs e)
{
//retrieve connection information info from App.config
string strConnectionString = ConfigurationManager.ConnectionStrings["sacpConnection"].ConnectionString;
//STEP 1: Create connection
SqlConnection myConnect = new SqlConnection(strConnectionString);
//STEP 2: Create command
string strCommandtext = "SELECT dUsername, dPassword from DOCTOR";
// Add a WHERE Clause to SQL statement
strCommandtext += " WHERE dUsername=#dname AND dPassword=#dpwd;";
strCommandtext += "SELECT nUsername, nPassword from NURSE WHERE nUsername=#nname AND nPassword=#npwd;";
SqlCommand cmd = new SqlCommand(strCommandtext, myConnect);
cmd.Parameters.AddWithValue("#dname", textUsername.Text);
cmd.Parameters.AddWithValue("#dpwd", txtPassword.Text);
cmd.Parameters.AddWithValue("#nname", textUsername.Text);
cmd.Parameters.AddWithValue("#npwd", txtPassword.Text);
try
{
// STEP 3: open connection and retrieve data by calling ExecuteReader
myConnect.Open();
// STEP 4: Access Data
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read()) //For Doctor
{
if (MessageBox.Show("Login Successful") == DialogResult.OK)
{
page_two form = new page_two();
form.Show();
return;
}
}
reader.NextResult();
while (reader.Read()) //For Nurse
{
if (MessageBox.Show("Login Successful") == DialogResult.OK)
{
page_two form = new page_two();
form.Show();
return;
}
}
//STEP 5: close connection
reader.Close();
MessageBox.Show("Invalid username or password");
}
catch (SqlException ex)
{
}
finally
{
//STEP 5: close connection
myConnect.Close();
}
}
}
}
//Page_two codes
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace GRP_02_03_SACP
{
public partial class page_two : Form
{
public page_two()
{
InitializeComponent();
}
private void btnDoctor1_Click(object sender, EventArgs e)
{
}
private void btnDoctor2_Click(object sender, EventArgs e)
{
}
private void btnNurse1_Click(object sender, EventArgs e)
{
}
private void btnNurse2_Click(object sender, EventArgs e)
{
}
}
}
Add This To your Code :
public Int JobPosition;
Here you will Define the position for each.
Change the Code on your btnLogin_Click to this :
private void btnLogin_Click(object sender, EventArgs e)
{
//retrieve connection information info from App.config
string strConnectionString = ConfigurationManager.ConnectionStrings["sacpConnection"].ConnectionString;
//STEP 1: Create connection
SqlConnection myConnect = new SqlConnection(strConnectionString);
//STEP 2: Create command
string strCommandtext = "SELECT dUsername, dPassword from DOCTOR";
// Add a WHERE Clause to SQL statement
strCommandtext += " WHERE dUsername=#dname AND dPassword=#dpwd;";
strCommandtext += "SELECT nUsername, nPassword from NURSE WHERE nUsername=#nname AND nPassword=#npwd;";
SqlCommand cmd = new SqlCommand(strCommandtext, myConnect);
cmd.Parameters.AddWithValue("#dname", textUsername.Text);
cmd.Parameters.AddWithValue("#dpwd", txtPassword.Text);
cmd.Parameters.AddWithValue("#nname", textUsername.Text);
cmd.Parameters.AddWithValue("#npwd", txtPassword.Text);
try
{
// STEP 3: open connection and retrieve data by calling ExecuteReader
myConnect.Open();
// STEP 4: Access Data
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read()) //For Doctor
{
if (MessageBox.Show("Login Successful") == DialogResult.OK)
{
JobPosition = 1; //Doctor
page_two form = new page_two(JobPosition);
form.Show();
return;
}
}
reader.NextResult();
while (reader.Read()) //For Nurse
{
if (MessageBox.Show("Login Successful") == DialogResult.OK)
{
JobPosition = 2; //Nurse
page_two form = new page_two(JobPosition);
form.Show();
return;
}
}
//STEP 5: close connection
reader.Close();
MessageBox.Show("Invalid username or password");
}
catch (SqlException ex)
{
}
finally
{
//STEP 5: close connection
myConnect.Close();
}
}
On Page_two Code :
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace GRP_02_03_SACP
{
public partial class page_two : Form
{
private Int JopPosition;
public page_two()
{
InitializeComponent();
}
public page_two(Int _Position)
{
InitializeComponent();
JopPosition = _Position;
}
private void btnDoctor1_Click(object sender, EventArgs e)
{
}
private void btnDoctor2_Click(object sender, EventArgs e)
{
}
private void btnNurse1_Click(object sender, EventArgs e)
{
if (JopPosition == 1)
{
MessageBox.Show("access denied");
}
}
private void btnNurse2_Click(object sender, EventArgs e)
{
}
}
}

Categories

Resources