Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can i add image in a datatable?

How can i add image in a datatable ? I tried the following code,

Image img = new Image();
img.ImageUrl = "~/images/xx.png";
dr = dt.NewRow();
dr[column] = imgdw;

But it showing text System.Web.UI.WebControls.Image in gridview instead of image.

like image 822
Kavitha Avatar asked Mar 13 '13 08:03

Kavitha


People also ask

How to add image in DataTable?

DataTable table = new DataTable("ImageTable"); //Create a new DataTable instance. DataColumn column = new DataColumn("MyImage"); //Create the column. column. DataType = System.

How do you add data to a DataTable?

After you create a DataTable and define its structure using columns and constraints, you can add new rows of data to the table. To add a new row, declare a new variable as type DataRow. A new DataRow object is returned when you call the NewRow method.


2 Answers

try this code:

        DataTable dt = new DataTable();
        dt.Columns.Add("col1", typeof(byte[]));
        Image img = Image.FromFile(@"physical path to the file");
        DataRow dr = dt.NewRow();
        dr["col1"] = imageToByteArray(img);
        dt.Rows.Add(dr);

where imageToByteArray is

    public byte[] imageToByteArray(System.Drawing.Image imageIn)
    {
        MemoryStream ms = new MemoryStream();
        imageIn.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
        return ms.ToArray();
    }

so Idea is that don't try to store the Image directly, rather convert it to byte [] and then store it, so that, later you can refetch it and use it or assign it to a picture box like this:

 pictureBox1.Image = byteArrayToImage((byte[])dt.Rows[0]["col1"]);

where byteArrayToImage is:

    public Image byteArrayToImage(byte[] byteArrayIn)
    {
        MemoryStream ms = new MemoryStream(byteArrayIn);
        Image returnImage = Image.FromStream(ms);
        return returnImage;
    }
like image 126
Manish Mishra Avatar answered Oct 09 '22 05:10

Manish Mishra


Use this code:

DataTable table = new DataTable("ImageTable"); //Create a new DataTable instance.

DataColumn column = new DataColumn("MyImage"); //Create the column.
column.DataType = System.Type.GetType("System.Byte[]"); //Type byte[] to store image bytes.
column.AllowDBNull = true;
column.Caption = "My Image";

table.Columns.Add(column); //Add the column to the table.

Add new row to table:

DataRow row = table.NewRow();
row["MyImage"] = <Image byte array>;
tables.Rows.Add(row);

Check out the following Code project link(Image to byte[]):

Code Project

like image 40
Max Avatar answered Oct 09 '22 06:10

Max