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.
Related
I need to add all image of my books in SQL Server database to the imagelist and show them on listview, but when I run the program, it shows the first image and repeats it on another images but the id of the images is changing I don't know what the problem is.
Image of the program
Image of the program
And this is the code:
MySqlConnection msc = new MySqlConnection("server=localhost;database=listv;uid=root;");
MySqlCommand cmd = new MySqlCommand("select id,image from books");
msc.Open();
listView1.Clear();
ImageList images = new ImageList();
images.ColorDepth = ColorDepth.Depth32Bit;
listView1.LargeImageList = images;
listView1.LargeImageList.ImageSize = new System.Drawing.Size(255, 255);
cmd.Connection = msc;
MySqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
byte[] imagebyte = (byte[])(dr["image"]);
MemoryStream image_stream = new MemoryStream(imagebyte);
image_stream.Write(imagebyte, 0, imagebyte.Length);
images.Images.Add(dr["image"].ToString(), new Bitmap(image_stream));
image_stream.Close();
ListViewItem listItem = new ListViewItem();
listItem.Text = dr["id"].ToString();
listItem.ImageKey = dr["image"].ToString();
listView1.Items.Add(listItem);
}
I want to add small image to existing row i listView. ListView is connected to SQLite DB.
When select some row in listView and click on button "Zakoncz" there is added to SQLite DataBase value "1" to column "CzyZaznaczone" and when here is value "1" listView should add image to selected row.
My image is in resources, can I use that or only from file?
Now my code adds a value to the database but does not add an image.
Here is the code:
SQLiteConnection con = new SQLiteConnection("data source=baza.db");
SQLiteDataAdapter ada = new SQLiteDataAdapter("select * from Przypominacz", con);
SQLiteCommand cmd = con.CreateCommand();
var index = this.listView1.SelectedIndices[0];
string zaznaczone = this.listView1.Items[index].SubItems[0].Text;
con.Open();
cmd.CommandText = "UPDATE Przypominacz SET CzyZakonczone=1 WHERE Nazwa='"+ zaznaczone + "'";
cmd.ExecuteNonQuery();
//dodanie ikonki do zakonczonego zadania
bool result = false;
string sql = "SELECT * FROM Przypominacz WHERE CzyZaznaczone='1'";
SQLiteDataReader reader = cmd.ExecuteReader();
if (reader.Read())
{
result = true;
}
reader.Close();
bool rezultat = result;
if(rezultat==true)
{
for (int i = listView1.SelectedItems.Count - 1; i >= 0; i--)
{
ImageList imageList = new ImageList();
imageList.Images.Add(Image.FromFile("D:\\C#\\Przypominacz2 — kopia (4)\\przypominacz\\przypominacz\\Resources\\checked.png"));
listView1.SmallImageList = imageList;
var listViewItem = listView1.Items.Add("Item with image");
}
}
Now looks:
Without img
But should looks like this:
With img
You are adding new ListViewItem to existing list instead of changing selected one(s). You can do it like this:
if(rezultat)
{
ImageList imageList = new ImageList();
imageList.Images.Add(Image.FromFile("D:\\C#\\Przypominacz2 — kopia (4)\\przypominacz\\przypominacz\\Resources\\checked.png"));
listView1.SmallImageList = imageList;
for (int i = 0; i < listView1.Items.Count; i++ )
{
if (listView1.Items[i].Selected)
listView1.Items[i].ImageIndex = 0;
}
}
To add image to ImageList from resources, take a look at this question
I am using DevExpress GalleryControl in my library program.
But the problem is I want to sort items in GalleryControl and I dont know how can I do that, I believe that GalleryControl doesn't have a built in feature for sorting items(not really sure tho).
So my program is connected in database(SQL).
So here I want to happen, I want to sort it by alphabetically or by author or by department , to do that I want it to create group for gallery control and the group will contains the item that belong to it.
Can you help me with it?
Check for what I've done:
public void LoadBooks(object state)
{
GalleryItemGroup group = new GalleryItemGroup();
galleryControl1.Gallery.Groups.Add(group);
group.Items.Clear();
group.Caption = "All books";
group.CaptionAlignment = GalleryItemGroupCaptionAlignment.Center;
MySqlConnection connection = null;
try
{
connection = new MySqlConnection(MyConnectionString);
connection.Open();
MySqlCommand cmd = connection.CreateCommand();
//This is arrange by alphabetically but I want to create gallery groups for each letters and the group will contain every items that belongs to it.
cmd.CommandText = "Select * from booktable ORDER BY booktitle";
MySqlDataAdapter adap = new MySqlDataAdapter(cmd);
DataTable ds = new DataTable();
adap.Fill(ds);
Invoke(new Action(() =>
{
for (int i = 0; i < ds.Rows.Count; i++)
{
byte[] byteBLOBData = (byte[])ds.Rows[i]["bookphoto"];
var stream = new MemoryStream(byteBLOBData);
Image bookimages = Image.FromStream(stream);
string author = ds.Rows[i]["bookauthor"].ToString();
string title = ds.Rows[i]["booktitle"].ToString();
group.Items.Add(new GalleryItem(bookimages, title, author));
group.Items[i].HoverImage = group.Items[i].Image;
}
}));
}
finally
{
if (connection != null && connection.State == ConnectionState.Open)
{
connection.Close();
}
}
}
By default, it was sorted by book id which is my primary key in SQL.
Please somebody help me , I'll appreciate any help.
By the way I am new here in Stackoverflow. It's nice to be here.
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
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.