string constring = "server=localhost;uid=root;" + "pwd=12345;database=products;";
string query = "SELECT prd_items_image FROM products.prd_items where prd_items_id=5";
MySqlConnection condatabase = new MySqlConnection(constring);
MySqlCommand cmddatabase = new MySqlCommand(query, condatabase);
MySqlDataReader myreader;
try
{
condatabase.Open();
myreader = cmddatabase.ExecuteReader();
while (myreader.Read())
{
byte[] imgg = (byte[])(myreader["prd_items_image"]);
if (imgg == null)
box.Image = null;
else
{
MemoryStream mstream = new MemoryStream(imgg);
box.Image = System.Drawing.Image.FromStream(mstream);
}
}
I am getting error at if condition,
box.Image=null andbox.Image = System.Drawing.Image.FromStream(mstream);
In these two cases, I am getting error at Image.
So please check it once. If you have any other code ,provide me if required.
Related
I want to fetch an image from the database and show it in my react-native app.where I did go wrong?
public IActionResult DownloadFile(int id)
{
DataTable table = new DataTable();
string query = #"select image from mydb.courses where id=#id";
string sqlDataSource = _configuration.GetConnectionString("UsersAppCon");
MySqlDataReader myReader;
using (MySqlConnection mycon = new MySqlConnection(sqlDataSource))
{
mycon.Open();
using (MySqlCommand myCommand = new MySqlCommand(query, mycon))
{
myReader = myCommand.ExecuteReader();
table.Load(myReader);
var fs = new FileStream(myReader, FileMode.Open);
return File(fs, "application/octet-stream");
myReader.Close();
mycon.Close();
}
}
}
I fixed it.
[HttpGet("{id}")]
public IActionResult DownloadFile(int id)
{
string pathImage = "";
DataTable table = new DataTable();
string query = #"select image from mydb.courses where id=#id";
string sqlDataSource = _configuration.GetConnectionString("UsersAppCon");
MySqlDataReader myReader;
using (MySqlConnection mycon = new MySqlConnection(sqlDataSource))
{
mycon.Open();
using (MySqlCommand myCommand = new MySqlCommand(query, mycon))
{
myCommand.Parameters.AddWithValue("#id", id);
pathImage = (string)myCommand.ExecuteScalar();
mycon.Close();
}
}
var path = #$"{pathImage}";
var fs = new FileStream(path, FileMode.Open);
return File(fs, "image/jpeg");
}
I have a problem with a ComboBox, its items are being duplicated. How can I prevent this situation? Here is some images:
Here is my code sample used to populate it:
string SelectQuery = "SELECT Part , Model FROM ctautoparts.nissanpart , ctautoparts.nissan ;";
MySqlConnection sqlConn = new MySqlConnection(myConnectionString);
MySqlCommand cmdDatabase = new MySqlCommand(SelectQuery, sqlConn);
MySqlDataReader myReader;
try
{
sqlConn.Open();
myReader = cmdDatabase.ExecuteReader();
// int model = myReader.GetOrdinal("model");
//int model1 = myReader.GetOrdinal("part");
while (myReader.Read())
{
// string namethestore = myReader.IsDBNull(model)
// ? string.Empty
// : myReader.GetString("model");
// this.carmodel.Text = namethestore;
// string namethestore1 = myReader.IsDBNull(model)
// ? string.Empty
// : myReader.GetString("parts");
/// this.carpart.Text = namethestore1;
carmodel.Items.Add(myReader["Model"].ToString());
carpart.Items.Add(myReader["Part"].ToString());
}
}
catch (Exception msg)
{
MessageBox.Show(msg.Message);
}
Add distinct to your select query, so that the duplicates will be removed
It looks your query is returning duplicated lines. I'd suggest executing them separatedely:
try
{
// POPULATE MODELS
string modelsQuery = "SELECT Model FROM ctautoparts.nissan;";
using (MySqlConnection sqlConn = new MySqlConnection(myConnectionString))
{
using (MySqlCommand cmdDatabase = new MySqlCommand(modelsQuery, sqlConn))
{
sqlConn.Open();
MySqlDataReader myReader = cmdDatabase.ExecuteReader();
// int model = myReader.GetOrdinal("model");
//int model1 = myReader.GetOrdinal("part");
while (myReader.Read())
{
carmodel.Items.Add(myReader["Model"].ToString());
}
}
}
// POPULATE PARTS
string partsQuery = "SELECT Part FROM ctautoparts.nissanpart;";
using (MySqlConnection sqlConn = new MySqlConnection(myConnectionString))
{
using (MySqlCommand cmdDatabase = new MySqlCommand(partsQuery, sqlConn))
{
sqlConn.Open();
MySqlDataReader myReader = cmdDatabase.ExecuteReader();
// int model = myReader.GetOrdinal("model");
//int model1 = myReader.GetOrdinal("part");
while (myReader.Read())
{
carpart.Items.Add(myReader["Part"].ToString());
}
}
}
}
catch (Exception msg)
{
MessageBox.Show(msg.Message);
}
I try to create messeneger for my company where We have DNS (every pc has static ip and name of PC). All works by insert,select(mysql). I want to send group message where I choose name of PC and IP address
here is code for computer information
{
IPHostEntry he;
string myip = "";
he = Dns.GetHostEntry(Dns.GetHostName());
foreach (IPAddress ip in he.AddressList)
{
if (ip.AddressFamily == AddressFamily.InterNetwork)
{
myip = ip.ToString();
}
}
label1.Text = myip;
}
string pc = System.Environment.MachineName;
here I want to select group (skupina) of computers and insert to the messages (nrp)
using (MySqlConnection cnn = new MySqlConnection("Server=10.7.18.35;Database=OitDB;Uid=martin;Pwd=;"))
{
MySqlDataAdapter da = new MySqlDataAdapter("SELECT namepc FROM skupina where nazovskup= 'mojask' ", cnn);
DataSet ds = new DataSet();
da.Fill(ds, "skupina");
List<string> skName = new List<string>();
foreach (DataRow row in ds.Tables["skupina"].Rows)
{
skName.Add(row["namepc"].ToString());
string constring = "Server=10.7.18.35;Database=OitDB;Uid=martin;Pwd=;";
var Query = "INSERT INTO OitDB.skup(uzivatel)VALUES(#name)";
MySqlConnection conDatabase = new MySqlConnection(constring);
MySqlCommand cmdDatabase = new MySqlCommand(Query, conDatabase);
cmdDatabase.Parameters.Add("#name", MySqlDbType.VarChar).Value = string.Join("",skName.ToArray());
MySqlDataReader myReader;
try
{
conDatabase.Open();
myReader = cmdDatabase.ExecuteReader();
MessageBox.Show("Správa odoslaná!");
while (myReader.Read())
{
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}
but now I have result in mysql like:
row1-message1-pc1
row2-message1-pc1,pc2
row3-message1-pc1,pc2,pc3
and I want to:
row1-message1-pc1
row2-message1-pc2
row3-message1-pc3
Have you any idea?
this is functional code
using (MySqlConnection cnn = new MySqlConnection("Server=;Database=OitDB;Uid=martin;Pwd=;"))
{
MySqlDataAdapter da = new MySqlDataAdapter("SELECT namepc FROM skupina where nazovskup= 'mojask' ", cnn);
DataSet ds = new DataSet();
da.Fill(ds, "skupina");
List<string> skName = new List<string>();
foreach (DataRow row in ds.Tables["skupina"].Rows)
{
skName.Add(row["namepc"].ToString());
string constring = "Server=;Database=OitDB;Uid=martin;Pwd=;";
var Query = "INSERT INTO OitDB.nrp(id,pc,ip,komu,datum,predmet,sprava,skupina)VALUES(#id,#pc,#ip,#komu,#cas,#predmet,#sprava,#name)";
MySqlConnection conDatabase = new MySqlConnection(constring);
MySqlCommand cmdDatabase = new MySqlCommand(Query, conDatabase);
cmdDatabase.Parameters.AddWithValue("#id", idtxt.Text);
cmdDatabase.Parameters.AddWithValue("#pc", pc);
cmdDatabase.Parameters.AddWithValue("#ip", label1.Text);
cmdDatabase.Parameters.AddWithValue("#komu", comboBox1.Text);
cmdDatabase.Parameters.AddWithValue("#cas", cas);
cmdDatabase.Parameters.AddWithValue("#predmet", textBox1.Text);
cmdDatabase.Parameters.AddWithValue("#sprava", pisat.Text);
cmdDatabase.Parameters.Add("#name", MySqlDbType.VarChar).Value = row["namepc"];
MySqlDataReader myReader;
try
{
conDatabase.Open();
myReader = cmdDatabase.ExecuteReader();
MessageBox.Show("Správa odoslaná!");
while (myReader.Read())
{
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
string query = "SELECT * FROM inv.product;";
MySqlConnection conDataBase = new MySqlConnection(constring);
MySqlCommand cmdDatabase = new MySqlCommand(query, conDataBase);
MySqlDataReader myReader;
try
{
conDataBase.Open();
myReader = cmdDatabase.ExecuteReader();
while (myReader.Read())
{
string sprodID = myReader.GetString("productID");
cmbdel.Items.Add(sprodID);
}
}
Create a function of you existing code like this,
private void BindCombo()
{
cmbdel.Items.Clear(); // Clear the combobox items here
// And bind again...
string query = "SELECT * FROM inv.product;";
MySqlConnection conDataBase = new MySqlConnection(constring);
MySqlCommand cmdDatabase = new MySqlCommand(query, conDataBase);
MySqlDataReader myReader;
try
{
conDataBase.Open();
myReader = cmdDatabase.ExecuteReader();
while (myReader.Read())
{
string sprodID = myReader.GetString("productID");
cmbdel.Items.Add(sprodID);
}
}
}
Now you can call this method everytime when you delete the item.
Hope it works, thanks.
You can do either of the following to remove an item from the combo box.
cmbdel.Items.RemoveAt(index);
cmbdel.Items.Remove(Value);
Before assigning new set of values,make sure that you call cmbdel.Items.Clear(). It will clear all the items from the combo box.
I am doing a 3 tier application to retrieve image from sql server which i stored image to binary data in sql, and the problem is i can't retrieve my image from the sql server.
here is my code in DataAccessLayer
public List<Volunteer> VolunteerTRetrieve()
{
List<Volunteer> vList = new List<Volunteer>();
byte[] volunteerProfilePicture;
string volunteerName, volunteerNRIC, volunteerAddress, volunteerEmail, volunteerContact;
string queryStr = "SELECT * FROM TVolunteer Order By VolunteerName";
SqlConnection conn = new SqlConnection(DBconnStr);
SqlCommand cmd = new SqlCommand(queryStr, conn);
conn.Open();
SqlDataReader dr = cmd.ExecuteReader();
while ((dr.Read()))
{
volunteerName = dr["VolunteerName"].ToString();
volunteerNRIC = dr["VolunteerNRIC"].ToString();
volunteerAddress = dr["VolunteerAddress"].ToString();
volunteerEmail = dr["VolunteerEmail"].ToString();
volunteerContact = dr["VolunteerContact"].ToString();
volunteerProfilePicture = (byte[])dr["VolunteerProfilePicture"];
vList.Add(new Volunteer(volunteerName, volunteerNRIC, volunteerAddress, volunteerEmail, volunteerContact, volunteerProfilePicture));
}
conn.Close();
dr.Dispose();
return vList;
}
in BusinessLogicLayer
public List<Volunteer> RetrieveAllBVolunteer()
{
Volunteer v = new Volunteer();
List<Volunteer> vList = new List<Volunteer>();
vList = v.VolunteerBRetrieve();
return vList;
}
and in PresentationLayer
List<Volunteer> allVolunteer = new List<Volunteer>();
allVolunteer = vBLL.RetrieveAllTVolunteer();
dl_tvolunteer.DataSource = allVolunteer;
dl_tvolunteer.DataBind();
I have also an image handler class
public class ShowImage : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
string connStr = System.Configuration.ConfigurationManager.ConnectionStrings["DBconnStr"].ConnectionString;
SqlConnection conn = new SqlConnection(connStr);
conn.Open();
string queryStr = "SELECT VolunteerProfilePicture FROM TVolunteer WHERE VolunteerNRIC = #NRIC";
SqlCommand cmd = new SqlCommand(queryStr, conn);
cmd.Parameters.Add("#NRIC", SqlDbType.VarChar).Value =
context.Request.QueryString["VolunteerNRIC"];
cmd.Prepare();
SqlDataReader dr = cmd.ExecuteReader();
dr.Read();
context.Response.BinaryWrite((byte[])dr["VolunteerProfilePicture"]);
}
Please help, Thankyou!
If you are returning one image you could the following
1. place a PictureBox control on the asp.net webpage
2. define the sql connections //not sure why you are using cmd.prepare
byte[] sqlImage = (byte[])cmd.ExecuteScalar();
MemoryStream memStream = new MemoryStream();
memStream.Write(sqlImage, 0, sqlImage.Length);
Bitmap bit = new Bitmap(memStream);
or if you want to do it a different way
try
{
con = new SqlConnection(constr);
cmd = new SqlCommand("select photopath,Photo from employees where employeeid=14", con);
con.Open();
dr = cmd.ExecuteReader();
while(dr.Read())
{
if (!dr.IsDBNull(1))
{
byte[] photo = (byte[])dr[1];
MemoryStream ms = new MemoryStream(photo);
pictureBox1.Image = Image.FromStream(ms);
}
}
}
catch (Exception ex)
{
dr.Close();
cmd.Dispose();
con.Close();
Response.Write(ex.Message);
}