I created a simple project for parking car. When i register any user and save it in access database.After saving Dialog box is shown and ask me to save that user but problem when Dialog Box is shown error comes out about access violation exception.Read or write protected memory i don't know how to fix.
I read some blogs and posts about this error but no provide a correct solution and also not post any correct idea.
Below is my complete code how can i fix.
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.Configuration;
using System.Data.OleDb;
using MessagingToolkit.QRCode.Codec;
using MessagingToolkit.QRCode.Codec.Data;
using System.IO;
using NPR.Properties;
namespace NPR
{
public partial class UserAdd : Form
{
public UserAdd()
{
InitializeComponent();
}
private int userId = 0;
public int UserId
{
get { return userId; }
set { userId = value; }
}
private bool isUpdate = false;
public bool IsUpdate
{
get { return isUpdate; }
set { isUpdate = value; }
}
private void UpdateRecord()
{
string connString = ConfigurationManager.ConnectionStrings["dbx"].ConnectionString;
string cmdString = "Update users SET u_name = #name,u_car_no = #car_no, u_mobile_no = #mobile_no,u_license_no = #license_no,u_reg_date = #reg_date , u_image=#firstimage,u_car_background=#secondimage WHERE Id = #userId";
using (OleDbConnection con = new OleDbConnection(connString))
{
using (OleDbCommand cmd = new OleDbCommand(cmdString, con))
{
con.Open();
cmd.Parameters.AddWithValue("#name", NameTextBox.Text);
cmd.Parameters.AddWithValue("#car_no", PlateNoTextBox.Text);
cmd.Parameters.AddWithValue("#mobile_no", MobileTextBox.Text);
cmd.Parameters.AddWithValue("#license_no", LicenseTextBox.Text);
cmd.Parameters.AddWithValue("#reg_date", DateTime.Text);
cmd.Parameters.AddWithValue("#firstimage", savePhoto());
cmd.Parameters.AddWithValue("#secondimage", savePhoto2());
cmd.Parameters.AddWithValue("#userId", this.userId);
cmd.ExecuteNonQuery();
}
}
}
private void SaveRecord()
{
string connString = ConfigurationManager.ConnectionStrings["dbx"].ConnectionString;
string cmdString = "INSERT INTO users (u_name,u_car_no,u_mobile_no,u_license_no,u_reg_date,u_image,u_car_background) VALUES (#name,#car_no,#mobile_no,#license_no,#reg_date,#firstimage,#secondimage)";
using (OleDbConnection con = new OleDbConnection(connString))
{
using (OleDbCommand cmd = new OleDbCommand(cmdString, con))
{
con.Open();
cmd.Parameters.AddWithValue("#name", NameTextBox.Text);
cmd.Parameters.AddWithValue("#car_no", PlateNoTextBox.Text);
cmd.Parameters.AddWithValue("#mobile_no", MobileTextBox.Text);
cmd.Parameters.AddWithValue("#license_no", LicenseTextBox.Text);
cmd.Parameters.AddWithValue("#reg_date", DateTime.Text);
cmd.Parameters.AddWithValue("#firstimage", savePhoto());
cmd.Parameters.AddWithValue("#secondimage", savePhoto2());
cmd.ExecuteNonQuery();
}
}
}
private byte[] savePhoto()
{
MemoryStream ms = new MemoryStream();
FirstpictureBox.Image.Save(ms, FirstpictureBox.Image.RawFormat);
return ms.GetBuffer();
}
private byte[] savePhoto2()
{
MemoryStream ms = new MemoryStream();
SecondpictureBox.Image.Save(ms, SecondpictureBox.Image.RawFormat);
return ms.GetBuffer();
}
private bool IsValidated()
{
if (NameTextBox.Text.Trim() == string.Empty)
{
MessageBox.Show("Name is Required.", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error);
NameTextBox.Focus();
return false;
}
if (PlateNoTextBox.Text.Trim() == string.Empty)
{
MessageBox.Show("Car Plate No. is Required.", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error);
PlateNoTextBox.Focus();
return false;
}
if (MobileTextBox.Text.Trim() == string.Empty)
{
MessageBox.Show("Mobile No. is Required.", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error);
MobileTextBox.Focus();
return false;
}
if (LicenseTextBox.Text.Trim() == string.Empty)
{
MessageBox.Show("License No. is Required.", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error);
NameTextBox.Focus();
return false;
}
if (DateTime.Text.Trim() == string.Empty)
{
MessageBox.Show("Date is Required.", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error);
DateTime.Focus();
return false;
}
return true;
}
private DataTable GetUserInfoById()
{
DataTable dtUsersInfo = new DataTable();
string connString = ConfigurationManager.ConnectionStrings["dbx"].ConnectionString;
string cmdString = "SELECT * FROM users WHERE Id = #UserId";
using (OleDbConnection con = new OleDbConnection(connString))
{
using (OleDbCommand cmd = new OleDbCommand(cmdString, con))
{
con.Open();
cmd.Parameters.AddWithValue("#UserId", this.UserId);
OleDbDataReader reader = cmd.ExecuteReader();
dtUsersInfo.Load(reader);
}
}
return dtUsersInfo;
}
private Image LoadImg(byte[] img)
{
MemoryStream ms = new MemoryStream(img);
return Image.FromStream(ms);
}
private void button2_Click(object sender, EventArgs e)
{
this.Close();
}
private void SecondpictureBox_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Title = "Select Car Background Image";
ofd.Filter = "Image File(*.png;*.jpg;*.bmp;*.gif)|*.png;*.jpg;*.bmp;*.gif";
if (ofd.ShowDialog() == DialogResult.OK)
{
SecondpictureBox.Image = new Bitmap(ofd.FileName);
}
}
private void FirstpictureBox_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Title = "Select User Profile Image";
ofd.Filter = "Image File(*.png;*.jpg;*.bmp;*.gif)|*.png;*.jpg;*.bmp;*.gif";
if (ofd.ShowDialog() == DialogResult.OK)
{
FirstpictureBox.Image = new Bitmap(ofd.FileName);
}
}
private void button3_Click(object sender, EventArgs e)
{
DataTable dtUsers = GetUserInfoById();
DataRow row = dtUsers.Rows[0];
PlateNoTextBox.Text = row["u_car_no"].ToString();
string connString = ConfigurationManager.ConnectionStrings["dbx"].ConnectionString;
string cmdString = "DELETE * FROM users WHERE Id = #UserId";
using (OleDbConnection con = new OleDbConnection(connString))
{
using (OleDbCommand cmd = new OleDbCommand(cmdString, con))
{
con.Open();
cmd.Parameters.AddWithValue("#UserId", this.UserId);
cmd.ExecuteNonQuery();
}
}
string connString2 = ConfigurationManager.ConnectionStrings["dbx"].ConnectionString;
string camdString = "Update slots SET u_name = #name,u_car_no = #car_no,Status = 0 WHERE u_car_no = #slotId";
using (OleDbConnection conn = new OleDbConnection(connString2))
{
using (OleDbCommand cmd = new OleDbCommand(camdString, conn))
{
conn.Open();
cmd.Parameters.AddWithValue("#name", " ");
cmd.Parameters.AddWithValue("#car_no", " ");
cmd.Parameters.AddWithValue("#slotId", row["u_car_no"]);
cmd.ExecuteNonQuery();
conn.Close();
conn.Dispose();
}
}
MessageBox.Show("User Deleted Successfully.", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
this.Close();
}
private void viewDataToolStripMenuItem_Click(object sender, EventArgs e)
{
this.Hide();
AllUserDetail mef = new AllUserDetail();
mef.ShowDialog();
}
private void toolStripMenuItem1_Click(object sender, EventArgs e)
{
this.Hide();
Dashboard dsh = new Dashboard();
dsh.ShowDialog();
}
private void UserAdd_Load(object sender, EventArgs e)
{
if (this.IsUpdate)
{
DataTable dtUsers = GetUserInfoById();
DataRow row = dtUsers.Rows[0];
NameTextBox.Text = row["u_name"].ToString();
PlateNoTextBox.Text = row["u_car_no"].ToString();
MobileTextBox.Text = row["u_mobile_no"].ToString();
LicenseTextBox.Text = row["u_license_no"].ToString();
DateTime.Text = row["u_reg_date"].ToString();
FirstpictureBox.Image = (row["u_image"] is DBNull) ? Resources.no_thumb : LoadImg((byte[])row["u_image"]);
SecondpictureBox.Image = (row["u_car_background"] is DBNull) ? Resources.no_thumb : LoadImg((byte[])row["u_car_background"]);
}
}
private void button1_Click(object sender, EventArgs e)
{
if (IsValidated())
{
try
{
if (this.isUpdate)
{
UpdateRecord();
String plate = PlateNoTextBox.Text;
QRCodeEncoder encoder = new QRCodeEncoder();
Bitmap qrcode = encoder.Encode(plate);
qrimage.Image = qrcode as Image;
MessageBox.Show("Record Updated Successfully.", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
SaveFileDialog s = new SaveFileDialog();
s.Title = "Save QR Code";
s.Filter = "JPEG|*.jpg|PNG|*.png|BMP|*.bmp|GIF|*.gif";
if (s.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
try
{
qrimage.Image.Save(s.FileName);
}
catch (ApplicationException ex)
{
MessageBox.Show("ERROR:" + ex.Message, "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
else
{
SaveRecord();
String plate = PlateNoTextBox.Text;
QRCodeEncoder encoder = new QRCodeEncoder();
Bitmap qrcode = encoder.Encode(plate);
qrimage.Image = qrcode as Image;
MessageBox.Show("Record Save Successfully.", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
SaveFileDialog s = new SaveFileDialog();
s.Title = "Save QR Code";
s.Filter = "JPEG|*.jpg|PNG|*.png|BMP|*.bmp|GIF|*.gif";
if (s.ShowDialog() == DialogResult.OK)
{
try
{
qrimage.Image.Save(s.FileName);
}
catch (ApplicationException ex)
{
MessageBox.Show("ERROR:" + ex.Message, "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
this.Close();
}
catch (ApplicationException ex)
{
MessageBox.Show("ERROR:" + ex.Message, "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
}
Problem i face it in SaveRecord(); function dialog box.
if (s.ShowDialog() == DialogResult.OK) //Here is error
{
try
{
qrimage.Image.Save(s.FileName);
}
Please try to add s.InitialDirectory = "D:\\"; to prevent access to special directories when dialog opens
Related
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.
This is my first time using C# and SQL. I've managed to get the datagridview to work, be it insert, update or delete. However, all the changes that is reflected in the datagridview is NOT updating in the SQL Table (When I open the database and click "Show Table Data", the Insert, Update and Delete changes are not reflected there.)
Please Help! All the videos I've searched up only shows their datagridview changes being reflected, but doesn't show if their SQL Table is actually updated.
My 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;
using System.Configuration;
using System.Runtime.InteropServices;
namespace CRUDProj
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
displaydata();
button3.Visible = false;
DataGridViewCheckBoxColumn chk = new DataGridViewCheckBoxColumn();
chk.HeaderText = "Select";
chk.ValueType = typeof(bool);
chk.Name = "chkbox";
infoDataGridView.Columns.Insert(0, chk);
}
private void Form1_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'cRUDDBDataSet.Info' table. You can move, or remove it, as needed.
this.infoTableAdapter.Fill(this.cRUDDBDataSet.Info);
}
private void infoBindingNavigatorSaveItem_Click(object sender, EventArgs e)
{
this.Validate();
this.infoBindingSource.EndEdit();
this.tableAdapterManager.UpdateAll(this.cRUDDBDataSet);
}
private void displaydata()
{
string mainconn = ConfigurationManager.ConnectionStrings["CRUDProj.Properties.Settings.CRUDDBConnectionString"].ConnectionString;
SqlConnection sqlconn = new SqlConnection(mainconn);
string sqlquery = "select * from [dbo].[Info]";
sqlconn.Open();
SqlCommand sqlcomm = new SqlCommand(sqlquery, sqlconn);
DataTable dt = new DataTable();
SqlDataAdapter sdr = new SqlDataAdapter(sqlcomm);
sdr.Fill(dt);
infoDataGridView.DataSource = dt;
sqlconn.Close();
}
private void button1_Click(object sender, EventArgs e)
{
string mainconn = ConfigurationManager.ConnectionStrings["CRUDProj.Properties.Settings.CRUDDBConnectionString"].ConnectionString;
SqlConnection sqlconn = new SqlConnection(mainconn);
string sqlquery = "insert into [dbo].[Info] values (#Id, #FullName, #NRIC, #Phone, #Temperature, #LocationLevel, #Date)";
sqlconn.Open();
SqlCommand sqlcomm = new SqlCommand(sqlquery, sqlconn);
sqlcomm.Parameters.AddWithValue("#Id", iDTextBox.Text);
sqlcomm.Parameters.AddWithValue("#FullName", fullNameTextBox.Text);
sqlcomm.Parameters.AddWithValue("#NRIC", nRICTextBox.Text);
sqlcomm.Parameters.AddWithValue("#Phone", phoneTextBox.Text);
sqlcomm.Parameters.AddWithValue("#Temperature", temperatureTextBox.Text);
sqlcomm.Parameters.AddWithValue("#LocationLevel", locationLevelTextBox.Text);
sqlcomm.Parameters.AddWithValue("#Date", dateTextBox.Text);
sqlcomm.ExecuteNonQuery();
MessageBox.Show("Record Successfully Inserted");
displaydata();
sqlconn.Close();
}
public string message = string.Empty;
private void button2_Click(object sender, EventArgs e)
{
foreach(DataGridViewRow row in infoDataGridView.Rows)
{
bool issellected = Convert.ToBoolean(row.Cells["chkbox"].Value);
if (issellected)
{
message = Environment.NewLine;
message = row.Cells[1].Value.ToString();
}
}
label1.Text = message;
label1.Visible = true;
button3.Visible = true;
button1.Enabled = false;
button2.Enabled = false;
button4.Enabled = false;
button5.Enabled = false;
}
private void button3_Click(object sender, EventArgs e)
{
string mainconn = ConfigurationManager.ConnectionStrings["CRUDProj.Properties.Settings.CRUDDBConnectionString"].ConnectionString;
SqlConnection sqlconn = new SqlConnection(mainconn);
string sqlquery = "update [dbo].[Info] set Id=#Id, FullName=#FullName, NRIC=#NRIC, Phone=#Phone, Temperature=#Temperature, LocationLevel=#LocationLevel, Date=#Date where Id=#Id";
sqlconn.Open();
SqlCommand sqlcomm = new SqlCommand(sqlquery, sqlconn);
sqlcomm.Parameters.AddWithValue("#Id" ,label1.Text);
sqlcomm.Parameters.AddWithValue("#FullName", fullNameTextBox.Text);
sqlcomm.Parameters.AddWithValue("#NRIC", nRICTextBox.Text);
sqlcomm.Parameters.AddWithValue("#Phone", phoneTextBox.Text);
sqlcomm.Parameters.AddWithValue("#Temperature", temperatureTextBox.Text);
sqlcomm.Parameters.AddWithValue("#LocationLevel", locationLevelTextBox.Text);
sqlcomm.Parameters.AddWithValue("#Date", dateTextBox.Text);
sqlcomm.ExecuteNonQuery();
infoTableAdapter.Update(cRUDDBDataSet.Info);
sqlconn.Close();
MessageBox.Show("Record Updated Successfully! ");
displaydata();
button3.Visible = false;
button1.Enabled = true;
button2.Enabled = true;
button4.Enabled = true;
button5.Enabled = true;
DataRowView drv = infoDataGridView.CurrentRow.DataBoundItem as DataRowView;
DataRow[] rowsToUpdate = new DataRow[] { drv.Row };
SqlDataAdapter adapter = new SqlDataAdapter("SELECT * FROM dbo.Info", sqlconn);
SqlCommandBuilder builder = new SqlCommandBuilder(adapter);
adapter.Update(rowsToUpdate);
this.infoTableAdapter.Update(this.cRUDDBDataSet.Info);
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void button5_Click(object sender, EventArgs e)
{
string mainconn = ConfigurationManager.ConnectionStrings["CRUDProj.Properties.Settings.CRUDDBConnectionString"].ConnectionString;
SqlConnection sqlconn = new SqlConnection(mainconn);
List<String> empselect = new List<String>();
DataGridViewRow row = new DataGridViewRow();
for (int i = 0; i<= infoDataGridView.Rows.Count-1; i++)
{
row = infoDataGridView.Rows[i];
if (Convert.ToBoolean(row.Cells [0].Value)==true)
{
string id = row.Cells[1].Value.ToString();
empselect.Add(id);
}
sqlconn.Open();
foreach (string s in empselect)
{
SqlCommand sqlcomm = new SqlCommand("delete from [dbo].[Info] where Id = ' " + s + " ' ", sqlconn);
sqlcomm.ExecuteNonQuery();
}
sqlconn.Close();
}
MessageBox.Show("Record Deleted Successfully! ");
displaydata();
}
private void iDTextBox1_TextChanged(object sender, EventArgs e)
{
}
private void button4_Click(object sender, EventArgs e)
{
iDTextBox.Clear();
fullNameTextBox.Clear();
nRICTextBox.Clear();
phoneTextBox.Clear();
temperatureTextBox.Clear();
locationLevelTextBox.Clear();
dateTextBox.Clear();
}
}
}
Bind your DGV to Database this will help you to perform crud operations easily.
This is a sample code on DGV to perform some actions may it will help you. but make sure that you bind your DGV to the database table.
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
_id = Convert.ToInt16(dataGridView1.Rows[e.RowIndex].Cells[0].Value);
string _name = dataGridView1.Rows[e.RowIndex].Cells[1].Value.ToString();
string _lname = dataGridView1.Rows[e.RowIndex].Cells[2].Value.ToString();
string _sex = dataGridView1.Rows[e.RowIndex].Cells[3].Value.ToString();
string _age = dataGridView1.Rows[e.RowIndex].Cells[4].Value.ToString();
if (e.ColumnIndex == dataGridView1.Columns["delete"].Index && e.RowIndex >= 0)
{
if(groupBox1.Visible==true)
{
groupBox1.Visible = false;
}
_id = Convert.ToInt16(dataGridView1.Rows[e.RowIndex].Cells[0].Value);
DialogResult result = MessageBox.Show("Do You Want to delete?", "Delete", MessageBoxButtons.OKCancel, MessageBoxIcon.Information);
if (result.Equals(DialogResult.OK) && service.deleterecord(_id, _name, _lname, _age, _sex))
{
MessageBox.Show("deleted record");
this.Close();
}
else
{
MessageBox.Show("not deleted");
}
}
if (e.ColumnIndex == dataGridView1.Columns["edit"].Index && e.RowIndex >= 0)
{
groupBox1.Visible = true;
firstname.Text = _name;
lastname.Text = _lname;
gender.Text = _sex;
age.Text = _age;
}
}
private void update_Click(object sender, EventArgs e)
{
string _fname = firstname.Text;
string _lname = lastname.Text;
string _age = age.Text;
string _sex = gender.Text;
try
{
if (string.IsNullOrWhiteSpace(_fname) || string.IsNullOrWhiteSpace(_lname) || string.IsNullOrWhiteSpace(_age) || string.IsNullOrWhiteSpace(_sex) || gender.Equals(null))
{
MessageBox.Show("Please enter the empty fields");
}
else
{
if (Updatedata("Update Query"))
{
MessageBox.Show("Record Updated");
//this.recordTableAdapter.Fill(this.task2DataSet.record);
groupBox1.Visible = false;
this.Size = new Size(595, 258);
this.Close();
}
else
{
MessageBox.Show("Failed to update");
}
}
}
catch (FormatException ex)
{
MessageBox.Show(ex.Message);
}
catch (ArgumentNullException ex)
{
MessageBox.Show(ex.Message);
}
}
Here is my code:
private void btnSimpan_Click(object sender, EventArgs e)
{
Employees employees = new Employees();
employees.EmployeeNumber = txtEmployeeNumber.Text;
employees.LastName = txtLastName.Text;
employees.FirstName = txtFirstName.Text;
employees.Extension = txtExtension.Text;
employees.Email = txtEmail.Text;
employees.OfficeCode = cboOfficeCode.Text;
if (employees.OfficeCode.CompareTo("1") == 0 || employees.OfficeCode.CompareTo("2") == 0 || employees.OfficeCode.CompareTo("3") == 0) employees.ReportsTo = "1143";
else if (employees.OfficeCode.CompareTo("4") == 0 || employees.OfficeCode.CompareTo("5") == 0) employees.ReportsTo = "1102";
else employees.ReportsTo = "1088";
employees.JobTitle = "Sales Rep";
try
{
stringBuilder = new StringBuilder();
stringBuilder.Append(#"INSERT INTO employees (employeeNumber, lastName, firstName, extension, email, officeCode, reportsTo, jobTitle) VALUES (");
stringBuilder.Append(employees.EmployeeNumber);
stringBuilder.Append(", '");
stringBuilder.Append(employees.LastName);
stringBuilder.Append("', '");
stringBuilder.Append(employees.FirstName);
stringBuilder.Append("', '");
stringBuilder.Append(employees.Extension);
stringBuilder.Append("', '");
stringBuilder.Append(employees.Email);
stringBuilder.Append("', ");
stringBuilder.Append(employees.OfficeCode);
stringBuilder.Append(", '");
stringBuilder.Append(employees.ReportsTo);
stringBuilder.Append("', '");
stringBuilder.Append(employees.JobTitle);
stringBuilder.Append("')");
comm = new MySqlCommand();
comm.Connection = conn;
comm.CommandText = stringBuilder.ToString();
// Memakai ExecuteNonQuery, return n data yang terkena dampak
int jmlDataTertambah = comm.ExecuteNonQuery();
MessageBox.Show(jmlDataTertambah.ToString() + " data berhasil disimpan");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
this.Close();
}
}
public partial class frmMain : Form
{
MySqlConnection conn = null;
public frmMain()
{
InitializeComponent();
}
private void mnuConnect_Click(object sender, EventArgs e)
{
if (mnuConnect.Text.CompareTo("Connect") == 0)
{
String connString = #"Server=127.0.0.1;Database=product_sales_company;Uid=root;Pwd=;";
try
{
conn = new MySqlConnection(connString);
conn.Open(); // Membuka koneksi
mnuEmployee.Enabled = true;
mnuConnect.Text = "Disconnect";
lblStatusKoneksi.Text = "Connected";
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
else
{
if (conn != null)
{
conn.Close(); // Menutup koneksi
conn.Dispose();
}
foreach (Form form in this.MdiChildren)
{
form.Close();
}
mnuEmployee.Enabled = false;
mnuConnect.Text = "Connect";
lblStatusKoneksi.Text = "Disconnected";
}
}
private void mnuExit_Click(object sender, EventArgs e)
{
if (conn != null)
{
conn.Close(); // Menutup koneksi
conn.Dispose();
}
Application.Exit();
}
private void mnuList_Click(object sender, EventArgs e)
{
// Cek apakah form yang memiliki jenis form yang sama (frmDaftarEmployee) sudah ada yang terbuka
foreach (Form form in this.MdiChildren)
{
if (form.GetType() == typeof(frmDaftarEmployee))
{
form.Activate(); // Membuat form yang ditunjuk menjadi aktif
return;
}
}
frmDaftarEmployee formDafarEmployee = new frmDaftarEmployee(conn);
formDafarEmployee.MdiParent = this;
formDafarEmployee.Show();
}
}
}
To create a database use Create command like this:
public void CreateDatabase(String createDb)
{
String connstr = ConfigurationManager.ConnectionStrings["Connstr"].ToString();
MySqlConnection cnn = new MySqlConnection(connstr);
try
{
cnn.Open();
object result = string.Empty;
MySqlCommand Command = new MySqlCommand();
Command = cnn.CreateCommand();
Command.CommandType = CommandType.Text;
Command.CommandText = createDb;
Command = new MySqlCommand(Query, cnn);
//result = (object)NpgCommand.ExecuteScalar();
Command.ExecuteNonQuery();
}
catch (Exception er)
{
String errorhere = er.Message;
if (cnn != null)
{
cnn.Close();
}
}
finally
{
if (cnn != null)
{
cnn.Close();
}
}
}
Then call the function on your form_load:
String createDb = "Create Database DBSample";
CreateDatabase(String createDb);
make sure you set the connection string at your app.config file.
It look like this:
<configuration>
<connectionStrings>
<add name="Connstr" connectionString="data source=localhost;initial catalog=dbname;user=usename;password=password; default command timeout=120" />
</connectionStrings>
</configuration>
good luck
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
the code works to a certain extent when I export the data to excel it works fine but if I go back into the application and add, delete or update any of the datagrid when I export the data again it doesn't export the changes. I have deleted the original csv file in case it was an overwriting problem but still get the same problem.
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 WindowsFormsApplication1
{
public partial class FormAccounts : Form
{
String constring = #"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\kenny\Documents\Visual Studio 2010\Projects\Cegees 181013\WindowsFormsApplication1\WindowsFormsApplication1\Accounts.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True";
//String cmdselect = #"select * Accounts";
String cmdupdate = #"update Accounts set date = #date, moneyin = #moneyin, retailin = #retailin, rent = #rent, stock = #stock, transport = #transport, misc = #misc, bills = #bills, comments = #comments where ID = #id";
String cmdinsert = #"insert into Accounts (date, moneyin, retailin, rent, stock, transport, misc, bills, comments) values (#date, #moneyin, #retailin, #rent, #stock, #transport, #misc, #bills, #comments )";
String cmddelete = #"delete from Accounts where ID =#ID";
public FormAccounts()
{
InitializeComponent();
}
private void FormAccounts_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'accountsDataSet.Accounts' table. You can move, or remove it, as needed.
this.accountsTableAdapter.Fill(this.accountsDataSet.Accounts);
}
private void btnAdd_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(constring);
SqlDataAdapter da = new SqlDataAdapter();
da.InsertCommand = new SqlCommand(cmdinsert, con);
try
{
da.InsertCommand.Parameters.Add("#date", SqlDbType.Date);
da.InsertCommand.Parameters["#date"].Value = dtpaccs.Value;
da.InsertCommand.Parameters.Add("#moneyin", SqlDbType.Decimal);
da.InsertCommand.Parameters["#moneyin"].Value = textmoneyin.Text ;
da.InsertCommand.Parameters.Add("#retailin", SqlDbType.Decimal);
da.InsertCommand.Parameters["#retailin"].Value = textretailin.Text;
da.InsertCommand.Parameters.Add("#rent", SqlDbType.Decimal);
da.InsertCommand.Parameters["#rent"].Value = textrent.Text;
da.InsertCommand.Parameters.Add("#stock", SqlDbType.Decimal);
da.InsertCommand.Parameters["#stock"].Value = textstock.Text;
da.InsertCommand.Parameters.Add("#transport", SqlDbType.Decimal);
da.InsertCommand.Parameters["#transport"].Value = texttransport.Text;
da.InsertCommand.Parameters.Add("#misc", SqlDbType.Decimal);
da.InsertCommand.Parameters["#misc"].Value = textmisc.Text;
da.InsertCommand.Parameters.Add("#bills", SqlDbType.Decimal);
da.InsertCommand.Parameters["#bills"].Value = textbills.Text;
da.InsertCommand.Parameters.Add("#comments", SqlDbType.VarChar);
da.InsertCommand.Parameters["#comments"].Value = textcomments.Text;
con.Open();
da.InsertCommand.ExecuteNonQuery();
MessageBox.Show("Data Added");
con.Close();
cleartexts();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
string date = dataGridView1.Rows[e.RowIndex].Cells[1].Value.ToString();
string id = dataGridView1.Rows[e.RowIndex].Cells[0].Value.ToString();
lbldate.Text = date;
lblID.Text = id;
dtpaccs.Value = Convert.ToDateTime(date);
textmoneyin.Text = dataGridView1.Rows[e.RowIndex].Cells[2].Value.ToString();
textretailin.Text = dataGridView1.Rows[e.RowIndex].Cells[3].Value.ToString();
textrent.Text = dataGridView1.Rows[e.RowIndex].Cells[4].Value.ToString();
textstock.Text = dataGridView1.Rows[e.RowIndex].Cells[5].Value.ToString();
texttransport.Text = dataGridView1.Rows[e.RowIndex].Cells[6].Value.ToString();
textmisc.Text = dataGridView1.Rows[e.RowIndex].Cells[7].Value.ToString();
textbills.Text = dataGridView1.Rows[e.RowIndex].Cells[8].Value.ToString();
textcomments.Text = dataGridView1.Rows[e.RowIndex].Cells[9].Value.ToString();
}
private void btnEdit_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(constring);
SqlDataAdapter da = new SqlDataAdapter();
da.UpdateCommand = new SqlCommand(cmdupdate, con);
try
{
da.UpdateCommand.Parameters.Add("#ID", SqlDbType.Int).Value = lblID.Text;
da.UpdateCommand.Parameters.Add("#date", SqlDbType.Date).Value = lbldate.Text;
da.UpdateCommand.Parameters.Add("#moneyin", SqlDbType.Decimal).Value = textmoneyin.Text;
da.UpdateCommand.Parameters.Add("#retailin", SqlDbType.Decimal).Value = textretailin.Text;
da.UpdateCommand.Parameters.Add("#rent", SqlDbType.Decimal).Value = textrent.Text;
da.UpdateCommand.Parameters.Add("#stock", SqlDbType.Decimal).Value = textstock.Text;
da.UpdateCommand.Parameters.Add("#transport", SqlDbType.Decimal).Value = texttransport.Text;
da.UpdateCommand.Parameters.Add("#misc", SqlDbType.Decimal).Value = textmisc.Text;
da.UpdateCommand.Parameters.Add("#bills", SqlDbType.Decimal).Value = textbills.Text;
da.UpdateCommand.Parameters.Add("#comments", SqlDbType.VarChar).Value = textcomments.Text;
con.Open();
da.UpdateCommand.ExecuteNonQuery();
MessageBox.Show("Accounts Updated");
con.Close();
cleartexts();
}
catch(Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
private void btnDelete_Click(object sender, EventArgs e)
{
var rindex = dataGridView1.SelectedCells[0].RowIndex;
SqlConnection con = new SqlConnection(constring);
SqlDataAdapter da = new SqlDataAdapter();
da.DeleteCommand = new SqlCommand(cmddelete, con);
try
{
DialogResult dr;
dr = MessageBox.Show("Are you sure you want to delete this record", "Confirmation", MessageBoxButtons.YesNo);
if (dr == DialogResult.Yes)
{
da.DeleteCommand.Parameters.Add("#ID", SqlDbType.Int).Value = accountsDataSet.Accounts[rindex].ID;
con.Open();
da.DeleteCommand.ExecuteNonQuery();
MessageBox.Show("Record Deleted");
con.Close();
cleartexts();
}
else
{
MessageBox.Show("Delete Cancelled");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
public void cleartexts()
{
//Clears textboxes
textmoneyin.Text = "";
textretailin.Text ="";
textrent.Text = "";
textstock.Text = "";
texttransport.Text = "";
textmisc.Text = "";
textbills.Text = "";
textcomments.Text = "";
}
private void exportToolStripMenuItem_Click(object sender, EventArgs e)
{
int cols;
string directory = #"C:\Users\kenny\Documents\Visual Studio 2010\Projects\Cegees 181013\WindowsFormsApplication1\WindowsFormsApplication1\Excel Exports";
string filename = string.Format("{0:dd-MM-yy}__{1}.csv", DateTime.Now, "Accounts");
string path = Path.Combine(directory, filename);
//open file
using (StreamWriter wr = File.CreateText(path))
{
//determine the number of cols and write to file
cols = dataGridView1.Columns.Count;
for (int i = 0; i < cols; i++)
{
wr.Write(dataGridView1.Columns[i].Name.ToString().ToUpper() + ",");
}
wr.WriteLine();
//write rows to excel
for (int i = 0; i < (dataGridView1.Rows.Count - 1); i++)
{
for (int j = 0; j < cols; j++)
{
if (dataGridView1.Rows[i].Cells[j].Value != null)
{
wr.Write(dataGridView1.Rows[i].Cells[j].Value + ",");
}
else
{
wr.Write(",");
}
}
wr.WriteLine();
}
wr.Close();
MessageBox.Show("Operation Complete " +path);
}
}
}
}
Found the problem. The application needs to be shut down and restarted for the new data to copy over. Is there a way to do that once the datagrid has been changed / updated?