Retrieve image from MySQL database and display on webpage using c# - c#

I am using asp.net with c# to build website, but now i come into a problem. I insert image with blob type into mysql database but i cannot retrieve it. There is no picturebox layout for web controls. I want to use image.imageURL to display this image. I searched a lot, some recommend use another aspx page, some recommend using ashx, but i cannot find a detailed solution. Here is what i have now:
protected void Button1_Click(object sender, EventArgs e)
{
String myname = Request.QueryString["Name"];
string myConnection = "server=127.0.0.1;uid=root;" + "pwd=81210ZLK;database=database;" + "Allow User Variables=True";
try
{
MySqlConnection myConn = new MySqlConnection(myConnection);
myConn.ConnectionString = myConnection;
MySqlCommand SelectCommand = new MySqlCommand();
string mySQL = "SELECT iddb1,fullname,age,gender,healthrecord,headpicture FROM database.db1 where fullname = #myname ";
SelectCommand.CommandText = mySQL;
SelectCommand.Parameters.AddWithValue("#myname", myname);
SelectCommand.Connection = myConn;
MySqlDataReader myReader;
myConn.Open();
myReader = SelectCommand.ExecuteReader();
while (myReader.Read())
{
Int16 ID = myReader.GetInt16(0);
string FName = myReader.GetString(1);
Int16 FAge = myReader.GetInt16(2);
string FGender = myReader.GetString(3);
string FRecord = myReader.GetString(4);
ShowID.Text = ID.ToString();
ShowName.Text = FName.ToString();
ShowAge.Text = FAge.ToString();
ShowGender.Text = FGender.ToString();
ShowRecord.Text = FRecord.ToString();
byte[] imgg = (byte[])(myReader["headpicture"]);
if (imgg == null)
Image1.ImageUrl = null;
else {
MemoryStream mstream = new MemoryStream(imgg);
// Image1.ImageURL = System.Drawing.Image.FromStream(mstream);
}
}
myConn.Close();
}
catch (Exception ex)
{
MessageBoxShow(this, ex.Message);
}
}
Here come with the problem and i marked it with \\

Try this ,
Image1.ImageURL = "data:image/jpeg;base64,"+Convert.ToBase64String(imgg);

Related

unable to cast object of type 'system.byte ' to type 'system.string' (combobox populate PictureBox)

and sorry for the inconvenience. I hope you can help me! I have this code, which by selecting a combobox populates a series of textboxes. Now I would like to make sure to add, in addition to the textbox, also a picturebox, but I get the error as per the title. How can I proceed? Here is the code. Thanks everyone for the help.
// STRINGA CHE PERMETTE DALLA COMBOBOX VIA DI DETERMINARE IL REFERENTE
private void cboVia_SelectedIndexChanged(object sender, EventArgs e)
{
string str = constring;
SqlConnection con2 = new SqlConnection(str);
string query = "SELECT Referenti.IDReferenti, Referenti.CognomeRF, Referenti.NomeRF, Referenti.ZonaRF, Referenti.LinkRF, Referenti.CodiceFotoRF, Referenti.TelefonoRF, Referenti.EmailRF, Referenti.ImageRF, Vie.Settore, Vie.Zona, Vie.Via FROM Referenti FULL OUTER JOIN Vie ON Referenti.ZonaRF = Vie.Zona where Via = '" + cboVia.Text + "'";
SqlCommand cmd = new SqlCommand(query, con2);
SqlDataReader dbr;
try
{
con2.Open();
dbr = cmd.ExecuteReader();
while (dbr.Read())
{
//string sID = (string)dbr["IDReferenti"].ToString();
string CognomeReferente = (string)dbr["CognomeRF"]; // name is string value
string NomeReferente = (string)dbr["NomeRF"];
string ZonaReferente = (string)dbr["ZonaRF"];
string EmailReferente = (string)dbr["EmailRF"];
string CodiceFotoReferente = (string)dbr["CodiceFotoRF"];
string imageRF = (string)dbr["ImageRF"];
//txtID.Text = sID;
txtCognomeReferente.Text = CognomeReferente;
txtnomeReferente.Text = NomeReferente;
txtEmailReferente.Text = EmailReferente;
txtZona.Text = ZonaReferente;
txtcodiceFotoReferente.Text = CodiceFotoReferente;
// PICTUREBOX
imageRFPictureBox.ImageLocation = imageRF;
//PICTUREBOX
}
}
catch (System.Exception ex)
{
MessageBox.Show(ex.Message.ToString(), "Errore");
}
}
// FINE STRINGA CHE PERMETTE ALLA COMBOBOX VIA DI DETERMINARE IL REFERENTE
#SeanSkelly thanks! Thanks to your advice maybe I found the solution!
byte[] imageRF = (byte[])dbr["ImageRF"];
if (imageRF == null)
{
imageRFPictureBox.Image = null;
}
else
{
MemoryStream mstream = new MemoryStream(imageRF);
imageRFPictureBox.Image = System.Drawing.Image.FromStream(mstream);
}
}
}
catch (System.Exception ex)
{
MessageBox.Show(ex.Message.ToString(), "Errore");
}

c# Using Two MysqlReaders

I want to retrive data from two differentables in my mysql data base so i created one connection and two readers, The second reader is not returning any results but the first reader is.
public List<BlogContentItemClass> BCITLIST = new List<BlogContentItemClass>();
// GET: api/BlogContents
[HttpGet]
public List<BlogContentItemClass> Get(string id)
{
string sqlstring = "server=; port= ; user id =;Password=;Database=;";
MySqlConnection conn = new MySqlConnection(sqlstring);
try
{
conn.Open();
}
catch (MySqlException ex)
{
throw ex;
}
string Query = "SELECT * FROM test.blogtable where `id` = '" + id + "' ";
MySqlCommand cmd = new MySqlCommand(Query, conn);
MySqlDataReader MSQLRD = cmd.ExecuteReader();
BlogContentItemClass BCIT = new BlogContentItemClass();
Label BLOGID = new Label();
if (MSQLRD.HasRows)
{
while (MSQLRD.Read())
{
string TC = (MSQLRD["Topic"].ToString());
string CT = (MSQLRD["Category"].ToString());
string SM = (MSQLRD["Summary"].ToString());
string BID = (MSQLRD["id"].ToString());
BCIT.TopicSaved1 = TC;
BCIT.CategoriesSaved1 = CT;
BCIT.SummarySaved1 = SM;
BLOGID.Text = BID;
BCIT.TotalBodyStackLayout1.Add("Hello");
}
}
BCITLIST.Add(BCIT);
MSQLRD.Close();
string Query1 = "SELECT * FROM test.blogbodytable where `BlogID` = '" + BLOGID.Text + "' ";
MySqlCommand cmd1 = new MySqlCommand(Query1, conn);
MySqlDataReader MSQLRD1 = cmd1.ExecuteReader();
if (MSQLRD1.HasRows)
{
while (MSQLRD1.Read())
{
string BLOGBODY ;
BLOGBODY = (MSQLRD1["BlogBody"].ToString());
BCIT.TotalBodyStackLayout1.Add(BLOGBODY);
}
}
BCITLIST.Add(BCIT);
conn.Close();
return BCITLIST;
}
from my code the line BCIT.TotalBodyStackLayout1.Add("Hello"); in the first reader does add "hello" to the BCIT.TotalBodyStacklayout1, but the line BCIT.TotalBodyStackLayout1.Add( BLOGBODY); does not work, what am i doing wrong?
Can you be more specific what you mean by 'BCIT.TotalBodyStackLayout1.Add(BLOGBODY);' does not work. Are you getting any exception? or if BLOGBODY coming empty? There are few primitive troubleshooting steps you can perform to nail-down the issue
confirm what BLOGID.Text you are getting from your previous query and corresponding data is available in test.blogbodytable for that id.
if (MSQLRD1.HasRows) is resolving to true
Were you able to get inside while (MSQLRD1.Read())

Save and Retrieve an Image c# WPF Sql

I'm new here and I've also searched about my problem, but I could manage to solve it.
I would like to save and retrieve images to/from Database(SQL) in C# WPF.
I have to make a project about storing a recipe. A recipe contains a table in the Database with the columns: Id, Name, Image, Content.The Information has to be saved and then the name of the recipe(currently done) and images(here is the problem) has to be displayed in a Grid, (so far i don't need to work with the "content" column from the database. That comes later).
I think that I have succeeded in the saving of image to the database, but I am not completely sure. If the saving of the image to the DB is correct, I need a function to retrieve it.
I would be happy for some help. Many Thanks!
D.Tsvet
Thats a sample of the future end result. The image has to be under the name
// Add recipe Window
DataSet ds;
string strName, imageName;
byte[] data;
string FileName;
public partial class add_Recipe : Window
{
DataSet ds;
string strName, imageName;
byte[] data;
string FileName;
public add_Recipe()
{
InitializeComponent();
}
// Upload a picture from your device
private void browseButton_Click(object sender, RoutedEventArgs e)
{
OpenFileDialog op = new OpenFileDialog();
op.Title = "Select a picture";
op.Filter = "All supported graphics|*.jpg;*.jpeg;*.png|" +
"JPEG (*.jpg;*.jpeg)|*.jpg;*.jpeg|" +
"Portable Network Graphic (*.png)|*.png";
if (op.ShowDialog() == true)
{
FileName = op.FileName.ToString();
image_box.Source = new BitmapImage(new Uri(op.FileName));
}
string dbConnectionString = #"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\guiProjekte\Stands\Projekt_GUI_200418\Projekt_GUI_20042018\Projekt_GUI_160418\Projekt_GUI\1234\1234\Database.mdf;Integrated Security=True;";
private void saveRecipe_Button(object sender, RoutedEventArgs e)
{
FileStream fs;
BinaryReader br;
byte[] ImageData;
fs = new FileStream(FileName, FileMode.Open, FileAccess.Read);
br = new BinaryReader(fs);
ImageData = br.ReadBytes((int)fs.Length);
br.Close();
fs.Close();
SqlConnection con = new SqlConnection(dbConnectionString);
con.Open();
if (con.State == System.Data.ConnectionState.Open)
{
string q = "insert into recipes(Name,Image,Content)values('" + textBox_newRecipe.Text.ToString() + "','" + ImageData + "','" + content_box.Text.ToString() + "')";
SqlCommand cmd = new SqlCommand(q, con);
cmd.ExecuteNonQuery();
MessageBox.Show("Connection made Successfuly..!");
this.Close();
myRecipes_Window obj_myRecipes_Window = new myRecipes_Window();
obj_myRecipes_Window.Show();
//Retrieve Recipe Window:
public void FillRecipes()
{
int column = 0;
int row = 0;
SqlConnection con = new SqlConnection(dbConnectionString);
con.Open();
String sqlSelectQuery = "SELECT * FROM recipes";
SqlCommand cmd = new SqlCommand(sqlSelectQuery, con);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
if(column < 3)
{
TextBlock nameTxt = new TextBlock();
nameTxt.Text = (dr["Name"].ToString());
nameTxt.FontSize = 20;
nameTxt.FontWeight = FontWeights.Bold;
Grid.SetColumn(nameTxt, column);
Grid.SetRow(nameTxt, row);
grid_Recipes.Children.Add(nameTxt);
column++;
}
else
{
column = 0;
row++;
TextBlock nameTxt = new TextBlock();
nameTxt.Text = (dr["Name"].ToString());
nameTxt.FontSize = 20;
nameTxt.FontWeight = FontWeights.Bold;
Grid.SetColumn(nameTxt, column);
Grid.SetRow(nameTxt, row);
grid_Recipes.Children.Add(nameTxt);
column++;
}
}
}
I made some changes about my post. I'm sorry for the previous unclearness.

calling 2 methods from onclick c#

Ive been trying to pass 2 SQL queries by clicking the button once and so this is what ive been trying to do as shown below but its not working....please help... thanks in advance
so this the code in front
<asp:Button ID="btnWedRecInsert" runat="server" Text="Insert" OnClick="btnWedRecInsert_Click1; btnWedRecInsert_Click2;" />
The code behind is below
protected void btnWedRecInsert_Click1(object sender, EventArgs e)
{
string Function = ddlFunction.Text;
string FunctionDate = txtFunctionDate.Text;
string FunctionTime = ddlFunctionTime.Text;
string groomName = txtGroomName.Text;
string groomFatherName = txtGroomFatherName.Text;
string groomAge = txtGroomAge.Text;
string groomPhone = txtGroomPhone.Text;
string groomAddress = txtGroomAddress.Text;
string brideName = txtBrideName.Text;
string brideFatherName = txtBrideFatherName.Text;
string brideAge = txtBrideAge.Text;
string bridePhone = txtBridePhone.Text;
string brideAddress = txtBrideAddress.Text;
string registerName = txtRegisterName.Text;
string registerPhone = txtRegisterPhone.Text;
string registerAddress = txtRegisterAddress.Text;
string referenceName = txtReferenceName.Text;
string referencePhone = txtReferencePhone.Text;
string referenceAddress = txtReferenceAddress.Text;
string connString = ConfigurationManager.ConnectionStrings["MandapamDatabase"].ConnectionString;
OleDbConnection connection = new OleDbConnection(connString);
string insertQuery = "INSERT INTO wedding(RegisteredDate, Function, FunctionDate, FunctionTime, groomName, groomFatherName, groomAge, groomPhone, groomAddress, brideName, brideFatherName, brideAge, bridePhone, brideAddress, registerName, registerPhone, registerAddress, referenceName, referencePhone, referenceAddress) VALUES( #Date, #Function, #FunctionDate, #FunctionTime, #groomName, #groomFatherName, #groomAge, #groomPhone, #groomAddress, #brideName, #brideFatherName, #brideAge, #bridePhone, #brideAddress, #registerName, #registerPhone, #registerAddress, #referenceName, #referencePhone, #referenceAddress) ";
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
command.CommandText = insertQuery;
command.CommandType = CommandType.Text;
command.Parameters.AddWithValue("#Date", DateTime.Now.Date);
command.Parameters.AddWithValue("#Function", Function);
command.Parameters.AddWithValue("#FunctionDate", FunctionDate);
command.Parameters.AddWithValue("#FunctionTime", FunctionTime);
command.Parameters.AddWithValue("#groomName", groomName);
command.Parameters.AddWithValue("#groomFatherName", groomFatherName);
command.Parameters.AddWithValue("#groomAge", groomAge);
command.Parameters.AddWithValue("#groomPhone", groomPhone);
command.Parameters.AddWithValue("#groomAddress", groomAddress);
command.Parameters.AddWithValue("#brideName", brideName);
command.Parameters.AddWithValue("#brideFatherName", brideFatherName);
command.Parameters.AddWithValue("#brideAge", brideAge);
command.Parameters.AddWithValue("#bridePhone", bridePhone);
command.Parameters.AddWithValue("#brideAddress", brideAddress);
command.Parameters.AddWithValue("#registerName", registerName);
command.Parameters.AddWithValue("#registerPhone", registerPhone);
command.Parameters.AddWithValue("#registerAddress", registerAddress);
command.Parameters.AddWithValue("#referenceName", referenceName);
command.Parameters.AddWithValue("#referencePhone", referencePhone);
command.Parameters.AddWithValue("#referenceAddress", referenceAddress);
try
{
connection.Open();
command.ExecuteNonQuery();
lblMessage.Text = "Record inserted successfully";
}
catch (Exception ex)
{
lblMessage.Text = "Unable to insert record";
}
finally
{
connection.Close();
}
}
protected void btnWedRecInsert_Click2(object sender, EventArgs e)
{
string Function = ddlReception.Text;
string FunctionDate = txtReceptionDate.Text;
string FunctionTime = ddlReceptionTime.Text;
string groomName = txtGroomName.Text;
string groomFatherName = txtGroomFatherName.Text;
string groomAge = txtGroomAge.Text;
string groomPhone = txtGroomPhone.Text;
string groomAddress = txtGroomAddress.Text;
string brideName = txtBrideName.Text;
string brideFatherName = txtBrideFatherName.Text;
string brideAge = txtBrideAge.Text;
string bridePhone = txtBridePhone.Text;
string brideAddress = txtBrideAddress.Text;
string registerName = txtRegisterName.Text;
string registerPhone = txtRegisterPhone.Text;
string registerAddress = txtRegisterAddress.Text;
string referenceName = txtReferenceName.Text;
string referencePhone = txtReferencePhone.Text;
string referenceAddress = txtReferenceAddress.Text;
string connString = ConfigurationManager.ConnectionStrings["MandapamDatabase"].ConnectionString;
OleDbConnection connection = new OleDbConnection(connString);
string insertQuery = "INSERT INTO wedding(RegisteredDate, Function, ReceptionTime, FunctionDate, FunctionTime, groomName, groomFatherName, groomAge, groomPhone, groomAddress, brideName, brideFatherName, brideAge, bridePhone, brideAddress, registerName, registerPhone, registerAddress, referenceName, referencePhone, referenceAddress) VALUES( #Date, #Function, #FunctionDate, #FunctionTime, #groomName, #groomFatherName, #groomAge, #groomPhone, #groomAddress, #brideName, #brideFatherName, #brideAge, #bridePhone, #brideAddress, #registerName, #registerPhone, #registerAddress, #referenceName, #referencePhone, #referenceAddress) ";
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
command.CommandText = insertQuery;
command.CommandType = CommandType.Text;
command.Parameters.AddWithValue("#Date", DateTime.Now.Date);
command.Parameters.AddWithValue("#Function", Function);
command.Parameters.AddWithValue("#FunctionDate", FunctionDate);
command.Parameters.AddWithValue("#FunctionTime", FunctionTime);
command.Parameters.AddWithValue("#groomName", groomName);
command.Parameters.AddWithValue("#groomFatherName", groomFatherName);
command.Parameters.AddWithValue("#groomAge", groomAge);
command.Parameters.AddWithValue("#groomPhone", groomPhone);
command.Parameters.AddWithValue("#groomAddress", groomAddress);
command.Parameters.AddWithValue("#brideName", brideName);
command.Parameters.AddWithValue("#brideFatherName", brideFatherName);
command.Parameters.AddWithValue("#brideAge", brideAge);
command.Parameters.AddWithValue("#bridePhone", bridePhone);
command.Parameters.AddWithValue("#brideAddress", brideAddress);
command.Parameters.AddWithValue("#registerName", registerName);
command.Parameters.AddWithValue("#registerPhone", registerPhone);
command.Parameters.AddWithValue("#registerAddress", registerAddress);
command.Parameters.AddWithValue("#referenceName", referenceName);
command.Parameters.AddWithValue("#referencePhone", referencePhone);
command.Parameters.AddWithValue("#referenceAddress", referenceAddress);
try
{
connection.Open();
command.ExecuteNonQuery();
lblMessage.Text = "Record inserted successfully";
}
catch (Exception ex)
{
lblMessage.Text = "Unable to insert record";
}
finally
{
connection.Close();
}
}
You should change your markup to:
<asp:Button ID="btnWedRecInsert" runat="server" Text="Insert" OnClick="btnWedRecInsert_Click" />
And change your codebehind to:
protected void btnWedRecInsert_Click(object sender, EventArgs e)
{
btnWedRecInsert_Click1();
btnWedRecInsert_Click2();
}
and for readability maybe you should change the name of the insert functions to
insertWedding1();
insertWedding2();
As of now I can't see any difference between the two insertfunctions. mayby you will change theese later but they're quite similar. How about making a function out of them with parameters so you don't have to write so much code : ) eg.
insertWedding(object paramWedding1);
insertWedding(object paramWedding2);
Change the onClick event to btn_{NameOfYourButton}Click and then have
public void btn_{NameOfYourButton}Click() {
btnWedRecInsert_Click1();
btnWedRecInsert_Click2();
}

Trying to save an image to Access: "Syntax error in INSERT INTO"

I hope someone can help me with this I am trying to save an image from a picturebox to an access database, I have set the data type of the field to "OLEDB" and am using the following code, the error message I am getting states there is a Syntax error in the INSERT INTO string, I am very new to doing anything beyond storing text values and dates in a database from C#, if anyone can help it would be appreciated.
private void btnSave_Click(object sender, EventArgs e)
{
string strCon = Properties.Settings.Default.Database1ConnectionString;
Conn = new OleDbConnection(strCon);
DateTime dateLastSvc = Convert.ToDateTime(txtLastService.Text);
DateTime datePAT = Convert.ToDateTime(txtPatTest.Text);
DateTime dateSvcCal = Convert.ToDateTime(lblNextSvcCalc.Text);
MemoryStream ms = new MemoryStream();
pbxEquipmentImage.Image.Save(ms, ImageFormat.Png);
byte[] pbxAray = ms.GetBuffer();
Comm = new OleDbCommand();
Comm.CommandType = CommandType.Text;
Comm.CommandText = "INSERT INTO Equipment(SerialNumber, DeviceName, LotNo, Critical, ISO, ServiceInterval, LastService, PAT, Location, Supplier, ServiceProvider, Comments, NextService, Image, FilePath) VALUES (#Serial, #Device,#Lot, #Critical, #ISO, #SvcInt, #LastSvc, #PAT, #Location, #Supplier, #SvcProv, #Comments, #NextSvc, #photo, #Link)";
//Comm = new OleDbCommand(strSql, Conn);
//ms.Position = 0;
//ms.Read(pbxAray, 0, pbxAray.Length);
//pbxAray = ms.ToArray();
Comm.Parameters.AddWithValue("#Serial", txtSerialNumber.Text);
Comm.Parameters.AddWithValue("#Device", txtDeviceName.Text);
Comm.Parameters.AddWithValue("#Lot", txtLotNumber.Text);
Comm.Parameters.AddWithValue("#Critical", cbxCritical.Text);
Comm.Parameters.AddWithValue("#ISO", cbxISOcert.Text);
Comm.Parameters.AddWithValue("#SvcInt", txtServiceInterval.Text);
Comm.Parameters.AddWithValue("#LastSvc", dateLastSvc);
Comm.Parameters.AddWithValue("#PAT", datePAT);
Comm.Parameters.AddWithValue("#Location", cbxLocation.Text);
Comm.Parameters.AddWithValue("#Supplier", cbxSupplier.Text);
Comm.Parameters.AddWithValue("#SvcProv", cbxServiceProvider.Text);
Comm.Parameters.AddWithValue("#Comments", txtComments.Text);
Comm.Parameters.AddWithValue("#NextSvc", lblNextSvcCalc.Text);
Comm.Parameters.AddWithValue("#photo", pbxAray);
Comm.Parameters.AddWithValue("#Link", linkFilePath.Text);
Conn.Open();
try
{
Comm.ExecuteNonQuery();
MessageBox.Show("The record has been added to the database");
Conn.Close();
}
catch (OleDbException ex)
{
MessageBox.Show("Could not save the information due to: " + ex.Message);
Conn.Close();
}
finally
{
txtSerialNumber.Clear();
txtDeviceName.Clear();
txtLotNumber.Clear();
cbxCritical.Text = "Please Select";
cbxISOcert.Text = "Please Select";
txtServiceInterval.Clear();
txtLastService.Text = null;
txtPatTest.Text = null;
cbxLocation.Text = "Please Select";
cbxSupplier.Text = "Please Select";
cbxServiceProvider.Text = "Please Select";
txtComments.Clear();
lblNextSvcCalc.Text = null;
pbxEquipmentImage.Image = null;
linkFilePath.Text = null;
}
}
IMAGE is a reserved word in Access SQL, so in order to reference that field in your table you need to enclose the field name in square brackets. That is, in your CommandText you need to replace
... NextService, Image, FilePath ...
with
... NextService, [Image], FilePath ...
.
p.s. - I think you also want to replace
Comm.Parameters.AddWithValue("#NextSvc", lblNextSvcCalc.Text);
with
Comm.Parameters.AddWithValue("#NextSvc", dateSvcCal);

Categories

Resources