I am really new to C#, so I have a lot of problems. I have a Windows Form with a SQL Database and I want to see the picture that I have saved with the rest of the data in the PictureBox and TextBoxes when I select for example user 1 in the DataGridVie. I know what my problem is but not how to fix it.
void Load_table()
{
try
{
string myConnectionstring = "datasource=localhost;port=3306; username=root;password=root";
MySqlConnection myConnection = new MySqlConnection(myConnectionstring);
MySqlCommand myCommand = new MySqlCommand("SELECT idBenutzerdaten, name, vorname, straße, hausnr, plz, wohnort, telenr, personr, schlossnr, picture FROM testdb.benutzerdaten;", myConnection);
MySqlDataAdapter myDataAdapter = new MySqlDataAdapter();
myDataAdapter.SelectCommand = myCommand;
myDataTable = new DataTable();
myDataAdapter.Fill(myDataTable);
BindingSource mySource = new BindingSource();
mySource.DataSource = myDataTable;
dataGridView.DataSource = mySource;
myDataAdapter.Update(myDataTable);
}
catch (Exception fehler)
{
MessageBox.Show("Es gibt ein Problem mit der Datenbank\n" + fehler.Message, "Datenbankfehler ", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
This is the code to get the Data from the Database to the DataGridView. When I want to get the saved image as well, I get an error. I know that I have to change the column to an image column or something like that, but nothing I found so far worked out for me.
private void dataGridView_SelectionChanged(object sender, EventArgs e)
{
panel.Enabled = false;
DataGridViewCell cell = null;
foreach (DataGridViewCell selectedCell in dataGridView.SelectedCells)
{
cell = selectedCell;
break;
}
if (cell != null)
{
DataGridViewRow row = cell.OwningRow;
tbx_id.Text = row.Cells[0].Value.ToString();
tbx_name.Text = row.Cells[1].Value.ToString();
tbx_vorname.Text = row.Cells[2].Value.ToString();
tbx_strasse.Text = row.Cells[3].Value.ToString();
tbx_hausnr.Text = row.Cells[4].Value.ToString();
tbx_plz.Text = row.Cells[5].Value.ToString();
tbx_wohnort.Text = row.Cells[6].Value.ToString();
tbx_telenr.Text = row.Cells[7].Value.ToString();
tbx_perso.Text = row.Cells[8].Value.ToString();
tbx_schlossnr.Text = row.Cells[9].Value.ToString();
}
}
The event from the datagridview. Not sure what and how to add here. But must be something like
imagebox.image = row.Cell[10].Value.Image();
I guess the problem is that the rows of the datagridview come 1 to 1 from the database, and I should create them manually, but then I got even more errors.
Any help will be appreciated. Thanks.
Are you using blob to store the images? just cast it
imagebox.image = byteArrayToImage(row.Cell[10].Value));
public Image byteArrayToImage(byte[] byteArrayIn)
{
MemoryStream ms = new MemoryStream(byteArrayIn);
Image returnImage = Image.FromStream(ms);
return returnImage;
}
I believe Your Problem is that you are not casting to get the propertype
try this :
imagebox.image = ((DataGridViewImageColumn)row.Cell[10]).Image();
// or try this :
imagebox.image = (Image)row.Cell[10].Value;
if you don't have any other problem with your code those should work with you
Related
Below this code is where i try to retrieve the image to my database and try to save it to another database. In the first image you will see the error that i encountered during the run time when i click that ok button. In the second image you will see that i already inserted the data with my retrieve image but i encountered that error (I see that the image is inserted but i don't know if that is the correct one)
In my employee_product table i have the "Image" column = image datatype
(This table is where i retrieve my image)
In my product_result table I have the same column and same datatype
(This table is where i inserted the retrieved image)
What i want to happen is to retrieve that image and when click the ok button it will save to my database also it will show to my datagridview
//My Code for Adding the image to my employee_product
private void btn_add_Click(object sender, EventArgs e)
{
using (var con = SQLConnection.GetConnection())
{
try
{
var ms = new MemoryStream();
pictureBox1.Image.Save(ms, ImageFormat.Jpeg);
byte[] PhotoByte = ms.ToArray();
if (string.IsNullOrEmpty(cbox_supplier.Text) || string.IsNullOrEmpty(txt_code.Text) || string.IsNullOrEmpty(txt_item.Text) || string.IsNullOrEmpty(txt_quantity.Text) || string.IsNullOrEmpty(txt_cost.Text))
{
MetroMessageBox.Show(this, "Please input the Required Fields", "System Message:", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
else
{
var selectCommand = new SqlCommand("Insert into employee_product (Image, Supplier, Codeitem, Itemdescription, Date, Quantity, Unitcost) Values (#Image, #Supplier, #Codeitem, #Itemdescription, #Date, #Quantity, #Unitcost)", con);
selectCommand.Parameters.AddWithValue("#Image", PhotoByte);
selectCommand.Parameters.AddWithValue("#Supplier", cbox_supplier.Text);
selectCommand.Parameters.AddWithValue("#Codeitem", txt_code.Text.Trim());
selectCommand.Parameters.AddWithValue("#Itemdescription", txt_item.Text.Trim());
selectCommand.Parameters.AddWithValue("#Date", date);
selectCommand.Parameters.AddWithValue("#Quantity", txt_quantity.Text.Trim());
selectCommand.Parameters.AddWithValue("#Unitcost", txt_cost.Text.Trim());
selectCommand.ExecuteNonQuery();
MessageBox.Show("Added successfully", "SIMS", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1);
txt_path.Clear();
pictureBox1.Image = null;
cbox_supplier.Items.Clear();
txt_code.Clear();
txt_item.Clear();
txt_quantity.Clear();
txt_cost.Clear();
_view.AddingProduct();
}
}
catch (Exception)
{
MessageBox.Show("Input image");
}
}
}
byte[] data;
public void display()
{
using (var con = SQLConnection.GetConnection())
{
SqlCommand selectTable = new SqlCommand("Select * from product_result ; ", con);
SqlDataAdapter sda = new SqlDataAdapter();
sda.SelectCommand = selectTable;
dbdataset = new DataTable();
sda.Fill(dbdataset);
BindingSource bSource = new BindingSource();
bSource.DataSource = dbdataset;
_view.ListProduct.DataSource = bSource;
sda.Update(dbdataset);
}
}
private void btn_ok_Click(object sender, EventArgs e)
{
using (var con = SQLConnection.GetConnection())
{
var selects = new SqlCommand("Select * from employee_product where Codeitem =#Codeitem ", con);
selects.Parameters.Add("#Codeitem", SqlDbType.VarChar).Value = _view.txt_code.Text;
SqlDataReader reader;
reader = selects.ExecuteReader();
while (reader.Read())
{
data = (byte[])reader["Image"];
}
reader.Close();
var selectCommand = new SqlCommand("Insert into product_result (Image, Code, Name, Price, Discount, Quantity) Values (#Image, #Code, #Name, #Price, #Discount, #Quantity)", con);
selectCommand.Parameters.AddWithValue("#Image", data);
selectCommand.Parameters.AddWithValue("#Code", _view.txt_code.Text);
selectCommand.Parameters.AddWithValue("#Name", _view.txt_name.Text.Trim());
selectCommand.Parameters.AddWithValue("#Price", _view.txt_price.Text.Trim());
selectCommand.Parameters.AddWithValue("#Discount", txt_discount.Text.Trim());
selectCommand.Parameters.AddWithValue("#Quantity", txt_quantity.Text.Trim());
selectCommand.ExecuteNonQuery();
var select = new SqlCommand("Update employee_product set quantity = quantity - #Quantity where Codeitem= #Codeitem",con);
select.Parameters.AddWithValue("#Codeitem", _view.txt_code.Text);
select.Parameters.AddWithValue("#Quantity", txt_quantity.Text);
select.ExecuteNonQuery();
this.Close();
display();
}
}
You will see in this picture that image has a code. If user input another code it will get another image
You can save the image of the PictureBox to db like this....
MemoryStream getimagestream = new MemoryStream();
pictureBox1.Image.Save(getimagestream, _pb_photo.Image.RawFormat);
byte[] Imagedata = getimagestream.GetBuffer();
You can receive the image from db to picture box like this.
var ImagedataReceive = (byte[])reader["Image"];
var stream = new MemoryStream(ImagedataReceive);
pictureBox1.Image = Image.FromStream(stream);
You will need to provide a cell formatting method that puts the data into an image object the data gridview can use.
private void dgv_CellFormatting(object sender,
DataGridViewCellFormattingEventArgs e)
{
if (dgv.Columns[e.ColumnIndex].Name == "Image")
{
if (e.Value != null)
{
... convert byte[] to image...
}
}
}
I'm trying to make this catalog app that display images with its "title" and "category" but I can't seem to display the image because of an error
on the line that says
images.Images.Add(row["id"].ToString(), new Bitmap(image_stream));
This is the whole of my code. I need the solution so i can print the image with its corresponding details in a list view. Thank you.
namespace WindowsFormsApplication2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
comboBox1.Items.Add("Books");
comboBox1.Items.Add("Games");
comboBox1.Items.Add("Music");
}
SqlConnection connection = new SqlConnection("Data Source=DESKTOP-4T5BLQ6\\SQLEXPRESS;Initial Catalog=CatalogDB;Integrated Security=True");
SqlCommand command = new SqlCommand();
SqlDataAdapter dataAdapter = new SqlDataAdapter();
SqlDataReader dataReader;
DataTable dataTable = new DataTable();
MemoryStream stream1;
byte[] photo_array;
private void Form1_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
connection.Open();
int i = 0;
MemoryStream stream = new MemoryStream();
command.CommandText = "insert into EntryTable(Title,Category,Image) values('" + textBox1.Text + "','" + comboBox1.Text + "','" + pictureBox1.Image + "')";
pictureBox1.Image.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);
byte[] pic = stream.ToArray();
if (i > 0)
{
MessageBox.Show("Saved new item in index" + i);
}
connection.Close();
MessageBox.Show("Made New Entry");
showData();
clear();
}
void clear()
{
textBox1.Clear();
pictureBox1.Image = null;
comboBox1.SelectedIndex = -1;
}
private void button2_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = "Images only. |*.jpg; *jpeg; *.png; *.gif; *.bmp;";
DialogResult result = ofd.ShowDialog();
if (result == DialogResult.OK)
{
pictureBox1.Image = Image.FromFile(ofd.FileName);
}
}
private void showData()
{
connection.Open();
listView1.Clear();
ImageList images = new ImageList();
images.ColorDepth = ColorDepth.Depth32Bit;
listView1.LargeImageList = images;
listView1.LargeImageList.ImageSize = new System.Drawing.Size(100 , 100);
command.Connection = connection;
command.CommandText = "SELECT * FROM EntryTable";
dataAdapter.SelectCommand = command;
dataTable.Clear();
dataAdapter.Fill(dataTable);
foreach (DataRow row in dataTable.Rows)
{
var image_buffer = (byte[])(row["Image"]);
MemoryStream image_stream = new MemoryStream(image_buffer, true);
image_stream.Write(image_buffer, 0, image_buffer.Length);
images.Images.Add(row["id"].ToString(), new Bitmap(image_stream));
image_stream.Close();
ListViewItem listItem = new ListViewItem();
listItem.Text = row["Title"].ToString();
listItem.ImageKey = row["Image"].ToString();
listView1.Items.Add(listItem);
listView1.Items.Add(row["Category"].ToString());
listView1.Items.Add(row["Title"].ToString());
}
connection.Close();
}
}
}
Xoriel,
You need to be more specific about what you are asking on SO. Your original post only indicates that you have and error and that it is holding up your app development (welcome to coding). You don't even tell us what error you are getting.
Now you ask how to implement a try catch? You should do a bit of research on your own. As far as try catch, you can start Here.
Your code indicates a lack of understanding about how windows winforms are instantiated and their sequence of events. To me, this indicates that you will have further problems after this one is fixed, so I will add a try catch to your code. It will write the exception to your console.
foreach (DataRow row in dataTable.Rows)
{
var image_buffer = (byte[])(row["Image"]);
MemoryStream image_stream = new MemoryStream(image_buffer, true);
image_stream.Write(image_buffer, 0, image_buffer.Length);
try
{
images.Images.Add(row["id"].ToString(), new Bitmap(image_stream));
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
image_stream.Close();
ListViewItem listItem = new ListViewItem();
listItem.Text = row["Title"].ToString();
listItem.ImageKey = row["Image"].ToString();
listView1.Items.Add(listItem);
listView1.Items.Add(row["Category"].ToString());
listView1.Items.Add(row["Title"].ToString());
}
Your true issue is the format in which you are storing the image to the database and the way in which you are retrieving it.
Regards,
Marc
I couldn't display the images from my database in Listview although I can retrieve some data like my the title of it.
Check out my code:
public void LoadBooks()
{
MySqlConnection connection = new MySqlConnection(MyConnectionString);
connection.Open();
try
{
listView1.Clear();
ImageList myImageList1 = new ImageList();
myImageList1.ImageSize = new System.Drawing.Size(80, 80);
listView1.LargeImageList = myImageList1;
MySqlCommand cmd = connection.CreateCommand();
cmd.CommandText = "Select * from booktable";
MySqlDataAdapter adap = new MySqlDataAdapter(cmd);
DataTable ds = new DataTable();
adap.Fill(ds);
foreach (DataRow dr in ds.Rows)
{
byte[] byteBLOBData = (byte[])dr["bookphoto"];
var stream = new MemoryStream(byteBLOBData);
Image bookimages= Image.FromStream(stream);
myImageList1.Images.Add(bookimages);
ListViewItem lsvparent = new ListViewItem();
lsvparent.Text = dr["booktitle"].ToString();
listView1.Items.Add(lsvparent);
}
}
catch (Exception)
{
throw;
}
finally
{
if (connection.State == ConnectionState.Open)
{
connection.Close();
}
}
}
Although the size of the image is showing in the Listview but there is any image just a blank image.
Hope you help me . Thank you
I don't see where you set the IamgeIndex that points to the ImageList.
It is a property of the ListViewItem and you can set it when adding it or at any time later on.
This will set it to the latest image in the list:
listView1.Items.Add(lsvparent, myImageList1.Image.Count - 1);
To change it later you can use:
listView1.Items[23].ImageIndex = 42;
or, if you have nice names:
listView1.Items[lsvparent].ImageIndex = 0;
Note that any ImageList is restricted to one Size, a maximum of 256x256 pixels and one bit depth fo all images!
It is a good idea to load a default image as the first one into the ImageList i.e. at index = 0 so you have a common one to fall back to.
The first one is funtion that i call. second one is the code to show the data that has already been stored in database. Now when i input the license number from the txtno and select the License number from combobox cbonumber and press the btnsearch, there is no record found message is shown even though the licensenumber and numbertype exists is database
function
public DataTable CheckExistingLicenseNo(string LicenseNumber, string Numbertype)
{
SqlConnection con = new SqlConnection("Data Source=(LocalDB)\\MSSQLLocalDB; Integrated Security=True; Initial Catalog=tprojectDB;");
string sql = "select *from tblDDDDDriver where LicenseNumber=#LicenseNumber and Numbertype=#Numbertype";
SqlCommand cmd = new SqlCommand(sql, con);
cmd.Parameters.AddWithValue("#LicenseNumber", LicenseNumber);
cmd.Parameters.AddWithValue("#Numbertype", Numbertype);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable db = new DataTable();
da.Fill(db);
return db; ;
}
code in btnsearch
private void btnsearch_Click(object sender, EventArgs e)
{
DataTable db = dc.CheckExistingLicenseNo(txtno.Text,cbonumbertype.Text);
if (db.Rows.Count > 0)
{
if (cbonumbertype.Text == "LicenseNumber")
{
txtlicenseno.Text = db.Rows[0]["LicenseNumber"].ToString();
txtlicensecategory.Text = db.Rows[0]["LicenseCategory"].ToString();
txtissuedate.Text = db.Rows[0]["IssueDate"].ToString();
txtrenewdate.Text = db.Rows[0]["RenewDate"].ToString();
txtfullname.Text = db.Rows[0]["FullName"].ToString();
txtdob.Text = db.Rows[0]["DOB"].ToString();
txtaddress.Text = db.Rows[0]["Address"].ToString();
string gender = db.Rows[0]["Gender"].ToString();
if (gender == "Male")
{
txtgender.Text = " MALE";
}
else
{
txtgender.Text = "FEMALE";
}
txtvehicleno.Text = db.Rows[0]["VehicleNumber"].ToString();
txthealthstaus.Text = db.Rows[0]["HealthStatus"].ToString();
txtdrivertype.Text = db.Rows[0]["DriverType"].ToString();
Image img;
byte[] bytimg = (byte[])db.Rows[0]["Image"];
//convert byte of imagedate to Image format
using (MemoryStream ms = new MemoryStream(bytimg, 0, bytimg.Length))
{
ms.Write(bytimg, 0, bytimg.Length);
img = Image.FromStream(ms, true);
pictureBox1.Image = img;
}
}
DataTable dd = dc.GetMaxDeathNo(Convert.ToDecimal(txtlicensenumber.Text));
if (dd.Rows.Count > 0)
{
txtdeathaccidentno.Text = dd.Rows[0]["DeathNumber"].ToString();
}
DataTable dM = dc.GetMaxMajorNo(Convert.ToDecimal(txtlicensenumber.Text));
if (dM.Rows.Count > 0)
{
txtmajoraccidentno.Text = dM.Rows[0]["MajorNumber"].ToString();
}
DataTable dm = dc.GetMaxMinorNo(Convert.ToDecimal(txtlicensenumber.Text));
if (dm.Rows.Count > 0)
{
txtminoraccidentno.Text = dm.Rows[0]["MinorNumber"].ToString();
}
DataTable dtrb = dc.GetTrafficRuleBroken(Convert.ToDecimal(txtlicensenumber.Text));
{
dataGridView1.DataSource = dtrb;
}
}
else
{
MessageBox.Show("No RECORD IS FOUND");
}
}
}
The only thing I suspect can be causing an issue is the value of cbonumbertype.Text. Change to cbonumbertype.SelectedValue and see if that wont help.
Change
DataTable db = dc.CheckExistingLicenseNo(txtno.Text,cbonumbertype.Text);
To
DataTable db = dc.CheckExistingLicenseNo(txtno.Text,cbonumbertype.SelectedValue);
I suspect that Bayeni's solution is the right one. You are possibly entering the ComboBox SelectedItem.Text value instead of the SelectedItem.Value value.
The easiest way to check this is to add a breakpoint to this line:
DataTable db = dc.CheckExistingLicenseNo(txtno.Text,cbonumbertype.Text);
In Visual Studio, select Debug > Start Debugging and check if the value in cbonumbertype.Text is the one that you expect to see.
I have created a table in which there is one column of type varbinary(max) to store the files.
What I want to do is that I want to show a pictureBox if that column is not null nad I have written this code:
private void ViewSentMailDet_Load(object sender, EventArgs e)
{
picturebox.Visible = false;
string con_string = #"Data Source=(local);Initial Catalog=fyp;Integrated Security=true";
SqlConnection con = new SqlConnection(con_string);
string qry = "select file from sentmail where msg_id='"+id of a particular row+"'";
SqlDataAdapter ad = new SqlDataAdapter(qry, con);
DataTable dt = new DataTable();
ad.Fill(dt);
foreach (DataRow dr in dt.Rows)
{
if (dr["file"] != null)
picturebox.Visible = true;
}
}
But still its showing the pictureBox on load event of this page even if the file column is null.
Furthermore I want to download this particular file from the table to a disc when the user clicks on the pictureBox.
One of the major rules of using any kind of database is never return data you don't need. With this in mind you should exclude rows with no image using the query rather than checking after the fact.
So:
"select file from sentmail where msg_id='"+id of a particular row+"' and file is not null"
Rather than:
if (dr["file"] != DBNull.Value)
{
picturebox.Visible = true;
}
Giving us:
private void ViewSentMailDet_Load(object sender, EventArgs e)
{
picturebox.Visible = false;
string con_string = #"Data Source=(local);Initial Catalog=fyp;Integrated Security=true";
SqlConnection con = new SqlConnection(con_string);
string qry = "select file from sentmail where msg_id='"+id of a particular row+"' and file is not null";
SqlDataAdapter ad = new SqlDataAdapter(qry, con);
DataTable dt = new DataTable();
ad.Fill(dt);
foreach (DataRow dr in dt.Rows)
{
using (var ms = new MemoryStream((byte[])dr["file"]))
picturebox.Image = Image.FromStream(ms);
picturebox.Visible = true;
}
}
if (dr["file"] != DBNull.Value)
{
picturebox.Visible = true;
}
To check if the column contains binary data or null, you can use
if(!dr.IsNull("attach"))
{
attachment.Visible = true;
}
Get image bytes
Byte[] bytes = (Byte[])dr["attach"];
Convert image bytes to image
Image image = null;
using (var ms = new MemoryStream(bytes))
image = Image.FromStream(ms);
Show the picture on the picturebox
picturebox.Image = image;
To save the image, on picturebox.Click event handler
picturebox.Image.Save(#"drive:/path/to/save/image.bmp");
Glad to help! Please remember to accept the answer if you found it helpful.