Reputation: 113
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.
Upvotes: 5
Views: 50623
Reputation: 20364
If the purpose is to display an image within a GridView, then personally I wouldn't store the actual image within a DataTable, only the image path. Storing the Image would only bloat the DataTable unnecessarily. Obviously this is only if your image is stored on the FileSystem and not in a DataBase.
To display the image within the GridView use a TemplateField
e.g.
dr = dt.NewRow();
dr[column] = "~/images/xx.png";
<asp:TemplateField>
<ItemTemplate>
<img src='<%#Eval("NameOfColumn")%>' />
</ItemTemplate>
</asp:TemplateField>
This would also work well when you are storing the Image path in a Database rather than storing the raw image.
Upvotes: 2
Reputation: 12375
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;
}
Upvotes: 7
Reputation: 13338
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[]):
Upvotes: 2