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.
DataTable table = new DataTable("ImageTable"); //Create a new DataTable instance. DataColumn column = new DataColumn("MyImage"); //Create the column. column. DataType = System.
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.
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;
    }
                        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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With