I have been trying to figure out how to save image into database with both null and image values. For my code it saves the image but if the image is missing it does not save a null value.
public string STDNAME { get; set; }
public string Image { get; set; }
DateTime Date1 = DateTime.Now;
This the code that I used to save the data
public string imagepath { get; set; }
public bool Insert(StudentC c)
{
bool isSuccess = false;
SqlConnection conn = new SqlConnection(myconnstring);
try
{
byte[] imageBT = null;
FileStream fstream = new FileStream(this.Image, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fstream);
imageBT = br.ReadBytes((int)fstream.Length);
string sql = "INSERT INTO STUDENT (STDNAME,imagepath,Image,Date) VALUES (#STDNAME,#imagepath,#Image,#Date)";
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Parameters.AddWithValue("#STDNAME", c.STDNAME);
cmd.Parameters.AddWithValue("#imagepath", c.imagepath);
cmd.Parameters.AddWithValue("#Image", imageBT);
cmd.Parameters.AddWithValue("#Date", Date1);
conn.Open();
int rows = cmd.ExecuteNonQuery();
if (rows > 0)
{
isSuccess = true;
}
else
{
isSuccess = false;
}
}
catch (Exception ex)
{
Console.WriteLine("\nMessage ---\n{0}", ex.Message);
}
finally
{
conn.Close();
}
return isSuccess;
}
This code is for browsing the image
//browse image
private void button6_Click(object sender, EventArgs e)
{
OpenFileDialog f = new OpenFileDialog();
f.Filter = "All Files|*.*|JPEGs|*.jpg|Bitmaps|*.bmp|GIFs|*.gif";
f.FilterIndex = 2;
if (f.ShowDialog() == DialogResult.OK)
{
pictureBox2.Image = Image.FromFile(f.FileName);
pictureBox2.SizeMode = PictureBoxSizeMode.StretchImage;
pictureBox2.BorderStyle = BorderStyle.Fixed3D;
textBox7.Text = f.SafeFileName.ToString();
string picPath = f.FileName.ToString();
textBox7.Text = picPath;
pictureBox2.ImageLocation = picPath;
}
}
This is the code to supplies the values to store
private void button5_Click(object sender, EventArgs e)
{
c.STDNAME = textBox2.Text;
c.Image = textBox7.Text;
c.imagepath = textBox7.Text;
bool success = c.Insert(c);
if (success == true)
{
MessageBox.Show("Data has been saved");
//Clear();
}
else
{
// label4.Text = "Data Has not been saved";
MessageBox.Show("Data has not been saved");
}
}
For adding adding null to the image column, make sure you specify the type (e.g. VarBinary) as the example below. In addition, make sure the image column accepts null.
cmd.Parameters.Add("#Image", SqlDbType.VarBinary).Value = DBNull.Value;
Moreover, the following approach may lead to the exception further below:
cmd.Parameters.AddWithValue("#Image", DBNull.Value);
--- Exception ---
System.Data.SqlClient.SqlException (0x80131904): Implicit conversion from data type nvarchar to varbinary(max) is not allowed. Use the CONVERT function to run this query.
**Very Simple Solution
C# Text
query = "insert into Customer (CustomerCode,LdegerCode,CustomerPicture) values ('0001','9999',NULL)"
Sql query Text
insert into Customer (CustomerCode,LdegerCode,CustomerPicture) values ('0001','9999',NULL)
if You use DBNull.Value its save Empty String in Column
Related
I have inserted an image on the 1st form namely Add_Staff and want to get that image on the 2nd form namely Staff_Detail's data gridview. how I can pass reference of add_staff images to staff_detail form's data gridview. Here is the code.
Insertion Code: -
private void BTNSTAFF_Click(object sender, EventArgs e)
{
if (staffid.Text == "")
{
if (teachername.Text == "" || saddress.Text == "" || semail.Text == "" || contact.Text == "" || jobspeciality.Text == "")
{
MessageBox.Show("All Fields Required");
}
else
{
Image pimg = pictureBox1.Image;
ImageConverter converter = new ImageConverter();
var ImageConvert = converter.ConvertTo(pimg, typeof(byte[]));
conn.Open();
//Values Inserted into Course
SqlCommand cmd = new SqlCommand("insert into staff values (#a,#b,#c,#d,#e,#g)", conn);
cmd.Parameters.AddWithValue("#a", teachername.Text);
cmd.Parameters.AddWithValue("#b", saddress.Text);
cmd.Parameters.AddWithValue("#c", semail.Text);
cmd.Parameters.AddWithValue("#d", contact.Text);
cmd.Parameters.AddWithValue("#e", jobspeciality.Text);
cmd.Parameters.AddWithValue("#g", ImageConvert);
cmd.ExecuteNonQuery();
MessageBox.Show("Data Inserted");
frm1.RefreshGrid();
conn.Close();
Staff_Clear();
this.Hide();
}
}}
Staff Detail Code for View Deatil: -
public partial class Staff_Detail : Form
{
SqlConnection conn = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\mudas\source\repos\WindowsFormsApp1\WindowsFormsApp1\WindowsFormsApp1\Database1.mdf;Integrated Security=True");
public static string column_id = "";
public static string column_name = "";
public static string column_address = "";
public static string column_email = "";
public static string column_contact = "";
public static string column_job = "";
public Staff_Detail()
{
InitializeComponent();
View();
}
public void View()
{
try
{
dataGridView4.Rows.Clear();
// if (conn.State != ConnectionState.Open)
conn.Open();
SqlCommand cmd = new SqlCommand("Select * From staff", conn);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
String column_getid = dr["id"].ToString();
String column_getname = dr["name"].ToString();
String column_getaddress = dr["address"].ToString();
String column_getemail = dr["email"].ToString();
String column_getcontact = dr["contact"].ToString();
String column_getjob = dr["job"].ToString();
dataGridView4.Rows.Add(column_getid, column_getname, column_getaddress, column_getemail, column_getcontact, column_getjob, "Edit/Delet");
}
conn.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
private void dataGridView4_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
int rowIndex = dataGridView4.CurrentCell.RowIndex;
String Column_id = dataGridView4.Rows[rowIndex].Cells[0].Value.ToString();
String Column_name = dataGridView4.Rows[rowIndex].Cells[1].Value.ToString();
String Column_address = dataGridView4.Rows[rowIndex].Cells[2].Value.ToString();
String Column_email = dataGridView4.Rows[rowIndex].Cells[3].Value.ToString();
String Column_contact = dataGridView4.Rows[rowIndex].Cells[4].Value.ToString();
String Column_job = dataGridView4.Rows[rowIndex].Cells[5].Value.ToString();
column_id = Column_id;
column_name = Column_name;
column_address = Column_address;
column_email = Column_email;
column_contact = Column_contact;
column_job = Column_job;
Add_Staff ad = new Add_Staff(this);
ad.Show();
ad.BringToFront();
}
}
I have project from my lecture to make application that save biodata (Student ID, Name, Departement, etc.) into database. And also I want to save picture profile into database MySQL.
Here's the function to save all data (except picture):
public bool isSignUp (String nim, String nama, String jenisKelamin, String prodi, String angkatan, String pass, String verifPass )
{
if (nim==null || nama==null || jenisKelamin==null || prodi==null || angkatan==null
|| pass==null || verifPass==null)
{
return false;
}
else if(pass.Equals(verifPass)==false)
{
return false;
}
else
{
String query = "insert into dbmahasiswa VALUES (#NIM, #Nama, #JenisKelamin, #ProgramStudi, #Angkatan, #Password)";
try
{
connect.Open();
MySqlCommand cmd = new MySqlCommand(query, connect);
cmd.Parameters.AddWithValue("#NIM", nim);
cmd.Parameters.AddWithValue("#Nama", nama);
cmd.Parameters.AddWithValue("#JenisKelamin", jenisKelamin);
cmd.Parameters.AddWithValue("#ProgramStudi", prodi);
cmd.Parameters.AddWithValue("#Angkatan", angkatan);
cmd.Parameters.AddWithValue("#Password", pass);
cmd.ExecuteNonQuery();
}
catch (Exception e)
{
MessageBox.Show(e.Message, "Warning");
return false;
}
finally
{
connect.Close();
}
return true;
}
}
How to add function to insert picture (that will be profile picture) in this method?
Something like:
string filename = Path.GetFileName(imageToSave.FileName);
string fileExtension = Path.GetExtension(filename);
int fileSize = imageToSave.ContentLength;
if (fileExtension.ToLower() == ".jpg" ) /*you could add a check for what type of image you want to be allowed to save*/
{
Stream stream = postedFile.InputStream;
BinaryReader binaryReader = new BinaryReader(stream);
Byte[] bytes = binaryReader.ReadBytes((int)stream.Length);
SqlParameter paramImageData = new SqlParameter()
{
ParameterName = "#ImageData",
Value = bytes
};
cmd.ExecuteNonQuery();
}
When I'm trying to retrieve my image by combo box there show the massage . Parameter not valid
I was try many way but problem is same ..
Every time I run the code below, I get same massage.
private void cBoxSearch_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
con = ConnectionController.GetInstance().GetConnection();
con.Open();
com = new SQLiteCommand("SELECT * FROM Stock WHERE ProductName = '" + cBoxSearch.Text + "' ", con);
myReader = com.ExecuteReader();
product prod = new product();
while (myReader.Read())
{
prod.proid = myReader[0].ToString();
prod.prodname = myReader[1].ToString();
prod.proMdl = myReader[2].ToString();
prod.serialN = myReader[3].ToString();
prod.byibgPr = myReader[4].ToString();
prod.sellPr = myReader[5].ToString();
prod.quantity = myReader[6].ToString();
tbxProductID.Text = prod.proid;
tbxName.Text =prod.prodname;
tbxModel.Text = prod.proMdl;
tbxserial.Text = prod.serialN;
tbxbyingprice.Text = prod.byibgPr;
tbxSellingprice.Text = prod.sellPr;
tbxQuantity.Text = prod.quantity;
prod.imgg = (byte[])(myReader[7] );
if (prod.imgg == null)
{
pBX.Image = null;
}
else
{
MemoryStream mstrm = new MemoryStream(prod.imgg);
Bitmap bmp = new Bitmap(mstrm);
}
}
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
com.Cancel();
con.Close();
}
Try to consult this question:
convert binary to bitmap using memory stream
Also, it might depend on DBType of the 8th column of the query.
This is my insert statement. Records are not inserting but no errors showing also. Please help
protected void btn_Add_Click(object sender, EventArgs e)
{
if (btn_Add.Text == "Submit")
{
string Height = txtHeight.Text;
string TopDia = Convert.ToString(txtTopDiaMeter.Text);
string BottomDia = Convert.ToString(txtBottomDiaMeter.Text);
string ShaftThick = Convert.ToString(txtShaftThick.Text);
string BlackWt = Convert.ToString(txtBlackWeight.Text);
string TotManHrPerPole = Convert.ToString(txtTotManHrPoleData.Text);
string Plate_Length = Convert.ToString(txtPlateLength.Text);
string PLATE_DIA = Convert.ToString(txtPlateDia.Text);
string PLATE_THICKNESS = Convert.ToString(txtPlateThick.Text);
System.Collections.Hashtable ht = (System.Collections.Hashtable)Session["UserDetails"];
Int64 UsrId = (Int64)ht["UserID"];
string CreatedBy = Convert.ToString(UsrId);
string FoundBoltId = Convert.ToString(ddlFoundationBolt.SelectedValue);
string PoleTypeId = Convert.ToString(ddlPoltype.SelectedValue);
string ProductTypeID = Convert.ToString(ddlPdtType.SelectedValue);
string Status = chkActive.Checked ? "True" : "False";
string filename = Path.GetFileName(fileuploadimages.PostedFile.FileName);
fileuploadimages.SaveAs(Server.MapPath("~/Images/Pole Data/" + filename));
try
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["valmont"].ToString());
con.Open();
SqlCommand cmd = new SqlCommand("Insert into DEF_POLE_DATA_MST(Height,TopDia,BottomDia,ShaftThick,BlackWt,TotManHrPerPole,Plate_Length,PLATE_DIA,PLATE_THICKNESS,CreatedBy,FoundBoltId,PoleTypeID,ProductTypeID,Status,ImagePath) values(#Height,#TopDia,#BottomDia,#ShaftThick,#BlackWt,#TotManHrPerPole,#Plate_Length,#PLATE_DIA,#PLATE_THICKNESS,#CreatedBy,#FoundBoltId,#PoleTypeId,#ProductTypeID,#Status,#ImagePath)", con);
cmd.Parameters.AddWithValue("#Height", Height);
cmd.Parameters.AddWithValue("#TopDia", TopDia);
cmd.Parameters.AddWithValue("#BottomDia", BottomDia);
cmd.Parameters.AddWithValue("#ShaftThick", ShaftThick);
cmd.Parameters.AddWithValue("#BlackWt", BlackWt);
cmd.Parameters.AddWithValue("#TotManHrPerPole", TotManHrPerPole);
cmd.Parameters.AddWithValue("#Plate_Length", Plate_Length);
cmd.Parameters.AddWithValue("#PLATE_DIA", PLATE_DIA);
cmd.Parameters.AddWithValue("#PLATE_THICKNESS", PLATE_THICKNESS);
cmd.Parameters.AddWithValue("#CreatedBy", CreatedBy);
cmd.Parameters.AddWithValue("#FoundBoltId", FoundBoltId);
cmd.Parameters.AddWithValue("#PoleTypeId", PoleTypeId);
cmd.Parameters.AddWithValue("#ProductTypeID", ProductTypeID);
cmd.Parameters.AddWithValue("#Status", Status);
cmd.Parameters.AddWithValue("#ImagePath", "~/Images/Pole Data/" + filename);
cmd.ExecuteNonQuery();
con.Close();
BindGrid();
Accordian.SelectedIndex = 1;
JQUERYDisplay.ShowAlertMessage("Record Inserted Successfully");
CleraFields();
}
catch (Exception ex)
{
JQUERYDisplay.ShowAlertMessage(ex.Message);
}
finally
{
}
}
Here's the table:
I had this message
Input string was not in a correct format
when inserting values into the database. When I checked I have DDL but I did not select value from it so this message appeared, although I make this column in the database to allow NULL value.
protected void BT_submit_Click(object sender, ImageClickEventArgs e)
{
string File = "~/CvFiles/" + FU_CV.FileName;
if (FU_CV.FileBytes.Length > 4194304)
{
modalpopup.Show();
}
else
{
app.AddApplicant(txt_Mname.Text, Convert.ToInt32(DDL_Dept.SelectedValue));
}
}
private void loadDepts()
{
DDL_Dept.DataSource = d.GetAll();
DDL_Dept.Items.Clear();
DDL_Dept.AppendDataBoundItems = true;
DDL_Dept.Items.Insert(0, new ListItem("-All-", "NULL"));
DDL_Dept.DataValueField = "id";
DDL_Dept.DataTextField = "name";
DDL_Dept.DataBind();
}
public bool AddApplicant(string MiddleName, int Dept_ID)
{
SqlCommand cmd = new SqlCommand("SP_Insert_IntoApplicantforuser");
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#MiddleName", MiddleName);
cmd.Parameters.AddWithValue("#Dept_ID", Dept_ID);
System.Data.SqlClient.SqlParameter paramter1 = cmd.Parameters.Add("#AppID", SqlDbType.Int);
paramter1.Direction = ParameterDirection.Output;
bool rowaffected;
rowaffected = DBHelper.Instance().Insert(cmd);
if (rowaffected == false)
{
AppID = (int)paramter1.Value;
}
return rowaffected;
}
You should check, if DDL_Dept.SelectedValue is a string representation of int. Use int.TryParse method:
if (FU_CV.FileBytes.Length > 4194304)
{
modalpopup.Show();
}
else
{
int dept;
if (int.TryParse(DDL_Dept.SelectedValue, out dept))
app.AddApplicant(txt_Mname.Text, dept);
else
app.AddApplicant(txt_Mname.Text, -1); //or whatever there should be for you
}