Drawing image in listview - c#

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

Related

Load image from datagridview c#

Im trying to fill a DataGridView with the value coming from my database. There is one column that has a value of a BLOB or image. Now when I'm loading it to the DataGridView it shows an error: Parameter is not valid. Can someone help me about this?
Triggering the method
private void Form1_Load(object sender, EventArgs e)
{
//load company to datagrid
string company = "SELECT * from tbl_payroll_company";
payroll.FillDataGrid(company, payroll_company_datagrid);
}
Method for filling my datagrid
public void FillDataGrid(string query,DataGridView gridview)
{
dbcon.Initialize();
if (dbcon.OpenCon() == true)
{
dt = new DataTable();
adapter = new MySqlDataAdapter(query, dbcon.con);
adapter.Fill(dt);
gridview.DataSource = dt;
dbcon.con.Close();
}
}
Here's how i saved it
private void btnCompanyUpload_Click(object sender, EventArgs e)
{
OpenFileDialog CompanyFileDialog = new OpenFileDialog();
if(CompanyFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
Image logo = Bitmap.FromFile(CompanyFileDialog.FileName);
payroll_company_logo.Image = logo;
}
catch(Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}
private void btnCompanySave_Click(object sender, EventArgs e)
{
if(dbcon.OpenCon() == true)
{
MemoryStream stream = new MemoryStream();
if (payroll_company_logo.Image != null)
{
payroll_company_logo.Image.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);
}
byte[] logo = stream.ToArray();
string[] column_name = {"payroll_company_logo"};
string table = "tbl_payroll_company";
string[] column_value = {logo.ToString()};
dbcon.Insert(table,column_name,column_value);
}
}
public void Insert(string table,string[] columns,string[] values)
{
this.Initialize();
con.Open();
MySqlCommand cmd = new MySqlCommand("INSERT INTO " + table + "(" + string.Join(",", columns) + ") VALUES('" + string.Join("','", values) + "')", con);
int check = cmd.ExecuteNonQuery();
con.Close();
}
ERROR

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.

Ajax tabContainer using panel, one button outside of the tabContainer

I'm creating Admin Panel using Ajax tab container which has 5 tapPanels and in that each tapPanel, I have one Panel from standard tool. And in that each Panel, I have GridView to show added data. And finally, I have one Add button outside of the Ajax tabContainer. I'll post the design if it allows. The problem is, I don't know the coding for tabContainer. I've created 10 methods so I can call it when Add button clicks.
Here is my code which is not working.
namespace Admin_Panel
{
public partial class add : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Session["Page"] = "ADD";
}
protected void btnAddCat_Click(object sender, EventArgs e)
{
AjaxControlToolkit.TabContainer container = (AjaxControlToolkit.TabContainer)TabConAddInfo;
AjaxControlToolkit.TabPanel tcTabPanel = new AjaxControlToolkit.TabPanel();
if (tcTabPanel.HeaderText == "Splash")
{
addSplash();
lblMsgAdd.Text = "Added successfully";
}
else if (tcTabPanel.HeaderText == "Main Category")
{
addMainCat();
lblMsgAdd.Text = "Added successfully";
}
else if (tcTabPanel.HeaderText == "Sub Category")
{
addSubCat();
lblMsgAdd.Text = "Added successfully";
}
else if (tcTabPanel.HeaderText == "Business Contact")
{
addBusinessContact();
lblMsgAdd.Text = "Added successfully";
}
else if (tcTabPanel.HeaderText == "Person Contact")
{
addPersonContact();
lblMsgAdd.Text = "Added successfully";
}
}
Int32 fileLength = 0;
string connStr = WebConfigurationManager.ConnectionStrings["connection"].ConnectionString;
private void addSplash()
{
HttpPostedFile uploadFile = FileLogo.PostedFile;
fileLength = uploadFile.ContentLength;
if (fileLength == 0)
{
string filePath = Server.MapPath(#"\style\img\no-photo-icon.jpg");
string fileName = Path.GetFileName(filePath);
FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
fileLength = (Int32)fs.Length;
Byte[] fileByteArr = new Byte[fileLength];
fs.Read(fileByteArr, 0, fileLength);
SqlConnection conn = new SqlConnection(connStr);
SqlCommand cmd = new SqlCommand("insert into SPLASH (VersionNumber, SplashLabel,LoginID) values (#VersionNumber,#SplashLabel,#LoginID)", conn);
cmd.Parameters.AddWithValue("#VersionNumber", txtVnum.Value);
cmd.Parameters.AddWithValue("#SplashLabel", txtSpLabel.Value);
cmd.Parameters.AddWithValue("#LoginID", txtYourID.Value);
cmd.Parameters.AddWithValue("#ImageData", fileByteArr);
cmd.Parameters.AddWithValue("#ImageContentType", "image/jpg");
cmd.Parameters.AddWithValue("#ImageSize", fileLength);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
conn.Dispose();
cmd.Dispose();
}
else
{
Byte[] fileByteArray = new Byte[fileLength];
Stream streamObject = uploadFile.InputStream;
streamObject.Read(fileByteArray, 0, fileLength);
SqlConnection conn = new SqlConnection(connStr);
SqlCommand cmd = new SqlCommand("insert into SPLASH (VersionNumber, SplashLabel,LoginID) values (#VersionNumber,#SplashLabel,#LoginID)", conn);
cmd.Parameters.AddWithValue("#VersionNumber", txtVnum.Value);
cmd.Parameters.AddWithValue("#SplashLabel", txtSpLabel.Value);
cmd.Parameters.AddWithValue("#LoginID", txtYourID.Value);
cmd.Parameters.AddWithValue("#ImageData", fileByteArray);
cmd.Parameters.AddWithValue("#ImageContentType", "image/jpg");
cmd.Parameters.AddWithValue("#ImageSize", fileLength);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
conn.Dispose();
cmd.Dispose();
}
}
private void showSplash()
{
SqlConnection conn = new SqlConnection(connStr);
SqlCommand cmd = new SqlCommand("select * from SPLASH", conn);
conn.Open();
SqlDataReader rdr = cmd.ExecuteReader();
System.Data.DataTable dt = new System.Data.DataTable();
dt.Load(rdr);
GridViewAddSplash.DataSource = dt;
GridViewAddSplash.DataBind();
conn.Close();
conn.Dispose();
cmd.Dispose();
}
private void addMainCat()
{
}
private void showMainCat()
{
}
private void addSubCat()
{
}
private void showSubCat()
{
}
private void addBusinessContact()
{
}
private void showBusinessContact()
{
}
private void addPersonContact()
{
}
private void showPersonContact()
{
}
}
}
My other related question, How to create ActiveTabChanged for Ajax tabContainer
Active_TabChanged
int CurrentTab = TabConAddInfo.ActiveTabIndex;
switch (CurrentTab)
{
case 0:
addSplash();
lblMsgAdd.Text = "Added successfully";
break;
}
etc. You would include that in your btn click event. Obviously I don't know if your TabIndex of zero is the right one to call addSplash() - just call the correct function for each tab.
As for the change of tab - are you talking about raising a javascript function?
OnClientActiveTabChanged="yourfunction";

How do i get my picture to show up to picturebox1 when i click my datagridview row in c#

I have a this program that if a user clicks a row in the datagridview:
private void ListView_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{
try
{
if (!ListView.Rows[e.RowIndex].IsNewRow)
{
idnum.Text = ListView.Rows[e.RowIndex].Cells[0].Value.ToString();
CmbPosition.Text = ListView.Rows[e.RowIndex].Cells[1].Value.ToString();
TxtFirstName.Text = ListView.Rows[e.RowIndex].Cells[2].Value.ToString();
TxtMiddleName.Text = ListView.Rows[e.RowIndex].Cells[3].Value.ToString();
TxtLastName.Text = ListView.Rows[e.RowIndex].Cells[4].Value.ToString();
CmbYearLevel.Text = ListView.Rows[e.RowIndex].Cells[5].Value.ToString();
CmbCourse.Text = ListView.Rows[e.RowIndex].Cells[6].Value.ToString();
TxtSchoolYear.Text = ListView.Rows[e.RowIndex].Cells[7].Value.ToString();
TxtFilePath.Text = ListView.Rows[e.RowIndex].Cells[8].Value.ToString();
BtnAdd.Enabled = false;
}
else
{
ClearData();
}
}
catch
{
}
}
and to read the database so it can get the path and show up the image that i saved in the database to picturebox1 whenever a user clicked a row in the datagridview.
public void TabindexChanged()
{
MemoryStream ms = new MemoryStream();
cmd = new SqlCommand("SELECT * FROM DBAdmin WHERE imgPath='" + _dg + "'", sc);
sc.Open();
SqlDataReader dr;
try
{
dr = cmd.ExecuteReader();
if (dr.Read())
{
byte[] picarr = (byte[])dr["imgImage"];
ms = new MemoryStream(picarr);
ms.Seek(0, SeekOrigin.Begin);
_pb.Image = Image.FromStream(ms);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
sc.Close();
}
}
but it seems that it wont get the imgPath from the database..
does not show up any picture in the picturebox1 whenever a row is selected.
Thanks in advance.

Convert from binary data to an image control in ASP.NET

I have binary data of an image in my database, and I want to display it in an image control in ASP.NET. How? If it is impossible, please find another way to save it in the database and display it in an image control.
Create a regular HTML img element like so:
<img runat="server" id="image" />
And in code behind do this:
image.src = "data:image/png;base64," + Convert.ToBase64String(imageBytes);
Where imageBytes is a byte[].
You are done. The image will be displayed.
Most likely the image is being stored as a byte array in the database. If so, then you can use this:
public static System.Drawing.Image ByteArrayToImage(byte[] bArray)
{
if (bArray == null)
return null;
System.Drawing.Image newImage;
try
{
using (MemoryStream ms = new MemoryStream(bArray, 0, bArray.Length))
{
ms.Write(bArray, 0, bArray.Length);
newImage = System.Drawing.Image.FromStream(ms, true);
}
}
catch (Exception ex)
{
newImage = null;
//Log an error here
}
return newImage;
}
public Byte[] Ret_image(Int32 id)
{
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "select * from tbimage where imageid=#id";
cmd.Connection = con;
cmd.Parameters.Add("#id", SqlDbType.Int).Value = id;
SqlDataReader dr = cmd.ExecuteReader();
dr.Read();
Byte[] ar = (Byte[])(dr[1]);
dr.Close();
cmd.Dispose();
return ar;
}
protected void Button2_Click(object sender, EventArgs e)
{
Byte[] ar = Ret_image(Convert.ToInt32(TextBox2.Text));
String st = Server.MapPath("abc.jpg");
FileStream fs = new FileStream(st, FileMode.Create, FileAccess.Write);
fs.Write(ar, 0, ar.Length);
fs.Close();
Image1.ImageUrl = "abc.jpg";
}
Use this event for the button click to retrieve image and call the Ret_Image method here.
In a generic handler (.ashx):
public class ImageHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
if(!string.IsNullOrEmpty(context.Request.QueryString["ImageId"]))
{
try
{
string ImageId = context.Request.QueryString["ImageId"].ToString();
ImageDataModel idm = new ImageDataModel();
byte[] ImageData = idm.getImageData(ImageId);
context.Response.ContentType = "image/JPEG";
context.Response.OutputStream.Write(ImageData, 0, ImageData.Length);
}
catch(Exception ex){}
}
}
}
SqlConnection con = new SqlConnection();
string _path;
Using SYstem.IO;
Using System.Data.SQLClient;
//convert Image to binary and save in DB
private void button1_Click(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
_path = openFileDialog1.FileName;
InsertInSQL(_path);
}
}
private void InsertInSQL(string _path)
{
con.ConnectionString = Pic.Properties.Settings.Default.ConnectionS;
string strQ = "insert into dbo.PicTBL(Pic)values(#p)";
SqlCommand command = new SqlCommand(strQ,con);
command.Parameters.AddWithValue("#p",ImageToBinary(_path));
con.Open();
command.ExecuteNonQuery();
con.Close();
}
public static byte[] ImageToBinary(string _path)
{
FileStream fS = new FileStream(_path, FileMode.Open, FileAccess.Read);
byte[] b = new byte[fS.Length];
fS.Read(b, 0, (int)fS.Length);
fS.Close();
return b;
}
//Convert Binary to imge and save in a folder
private void button1_Click_1(object sender, EventArgs e)
{
DataTable dt = Rimage();
foreach (DataRow row in dt.Rows)
{
byte[] b = (byte[])row["Pic"];
Image img = BinaryToImage(b);
img.Save("D:\\NewFolder\\" + row["ID"].ToString() + ".jpg");
}
}
private Image BinaryToImage(byte[] b)
{
if (b == null)
return null;
MemoryStream memStream = new MemoryStream();
memStream.Write(b, 0, b.Length);
return Image.FromStream(memStream);
}
private DataTable Rimage()
{
con.ConnectionString = Pic.Properties.Settings.Default.ConnectionS;
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "select * from dbo.PicTBL";
cmd.Connection = con;
SqlDataAdapter adp = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
con.Open();
adp.Fill(dt);
return dt;
}

Categories

Resources