How to show image in GridView form database linq - asp.net

i have a table with field named PIMAGE And i can't show this field.
gridview named:dgw-
my problem is that the gridview do not show the image
my code:
protected void Page_Load(object sender, EventArgs e)
{
StorDataContext stor = new StorDataContext();
var res = (from r in stor.Products
where r.PID!=13
select new {
name=r.PName,date=System.DateTime.Now.ToString(),company=r.Company,price=r.Price,quantity=r.Quantity,color=r.Color,size=r.Size,weight=r.PWeight,
PImage = r.PID});
GridView1.Visible = true;
GridView1.DataSource = res.ToList();
GridView1.DataBind();
}
and may ashx
public class ShowImg : IHttpHandler {
public void ProcessRequest(HttpContext context)
{
Int32 pid;
if (context.Request.QueryString["getID"] != null)
{
pid = Convert.ToInt32(context.Request.QueryString["getID"]);
context.Response.ContentType = "image/jpeg";
Stream strm = GetImage(pid);
byte[] buffer = new byte[4096];
int byteSeq = strm.Read(buffer, 0, 4096);
while (byteSeq > 0)
{
context.Response.OutputStream.Write(buffer, 0, byteSeq);
byteSeq = strm.Read(buffer, 0, 4096);
}
}
}
public Stream GetImage(int pid)
{
StorDataContext stor = new StorDataContext();
System.Data.Linq.Binary b = null;
byte[] ibyte = null;
Product product1 = stor.Products.First(p => p.PID == pid);
b = product1.PImage;
ibyte = b.ToArray();
return new MemoryStream((byte[])ibyte);
}
and aspx
<asp:TemplateField HeaderText="PImage">
<ItemTemplate>
<asp:Image ID="Image1" runat="server" ImageUrl='<%# "~/ShowImg.ashx?id=" + Eval("PImage") %>' />
</ItemTemplate>
</asp:TemplateField>
what's wrong?
use asp.net - sql server - linq

I'm assuming you mean you have an image field in the database.
There's lots of examples available on the net for this, here's one from the asp.net forums
The short version is, you would set the control
within the gridview to display the image. On the ImageField, you
would use the DataImageUrlField attribute to reference the name of the
field in the database that contains the binary image data. Also on
the ImageField, use the DataImageUrlFormatString to define a path
that, for example, points to an ASPX handler page and passes to it the
specific ID value from the DataImageUrlField.
The relevant line of code might look like this:
<asp:ImageField DataImageUrlField="MyImageID"
DataImageUrlFormatString="MyHandlerPage.aspx?theImageID={0}" /> A
complete example that uses this approach and shows you the code for
the handler page is at:
http://www.highoncoding.com/Articles/207_Displaying_Images_from_Database_in_GridView.aspx
or check out this one
public void ProcessRequest (HttpContext context) {
string connectionString = ConfigurationManager.ConnectionStrings["DBConnection"].ConnectionString;
SqlConnection conn = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "Select [Content] from Images where ID =#ID";
cmd.CommandType = CommandType.Text;
cmd.Connection = conn;
SqlParameter ImageID = new SqlParameter("#ID", SqlDbType.BigInt);
ImageID.Value = context.Request.QueryString["ID"];
cmd.Parameters.Add(ImageID);
conn.Open();
SqlDataReader dReader = cmd.ExecuteReader();
dReader.Read();
context.Response.BinaryWrite((byte[])dReader["Content"]);
dReader.Close();
conn.Close();
}
and the aspx code
<asp:GridView ID="GVImages" runat="server" AutoGenerateColumns="false" HeaderStyle-BackColor="CornflowerBlue" HeaderStyle-Font-Bold="true" HeaderStyle-ForeColor="White" CellPadding="5">
<Columns>
<asp:BoundField DataField="Name" HeaderText="Description" />
<asp:BoundField DataField="Type" HeaderText="Type" />
<asp:TemplateField HeaderText="Image">
<ItemTemplate>
<asp:Image ID="Image1" runat="server" Width="200px" Height="200px"
ImageUrl='<%# "ImageHandler.ashx?ID=" + Eval("ID")%>'/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
and your page_load in aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string connectionString = ConfigurationManager.ConnectionStrings["DBConnection"].ConnectionString;
DataTable dt = new DataTable();
SqlConnection conn = new SqlConnection(connectionString);
using (conn)
{
SqlDataAdapter ad = new SqlDataAdapter("SELECT * FROM Images", conn);
ad.Fill(dt);
}
GVImages.DataSource = dt;
GVImages.DataBind();
}
}
and finally your web.config
<configuration>
<connectionStrings>
<add name="DBConnection" connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=TESTDB;Trusted_Connection=yes;" providerName="System.Data.SqlClient"/>
<!--<add name="BONConnection" connectionString="Data Source=XXX.com;Initial Catalog=DBNAME;User Id=UserName;Password=YourPassword;" providerName="System.Data.SqlClient" />-->
</connectionStrings>
...................
...................

Related

Problem with download files from databases through GridView

I have problem with files. I'm trying to download files from databases
through gridview, but after I download them, they are with wrong name and extensions. Their name are my web form name and their extensions are .aspx.
In the database they are saved in the correct format.
Here are my code-behind
public partial class data : System.Web.UI.Page
{
string cs = ConfigurationManager.ConnectionStrings["DecumentsConnectionString"].ConnectionString;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
FillData();
}
}
private void FillData()
{
DataTable dt = new DataTable();
using (SqlConnection cn = new SqlConnection(cs))
{
SqlCommand cmd = new SqlCommand("getDecuments", cn);
cmd.CommandType = CommandType.StoredProcedure;
cn.Open();
SqlDataReader reader = cmd.ExecuteReader();
dt.Load(reader);
if (dt.Rows.Count > 0)
{
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
}
protected void Button1_Click(object sender, EventArgs e)
{
FileInfo filename = new FileInfo(FileUpload1.FileName);
byte[] documentContent = FileUpload1.FileBytes;
string name = filename.Name;
string extnt = filename.Extension;
using (SqlConnection con = new SqlConnection(cs))
{
SqlCommand cmd = new SqlCommand("savedocument", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#name", name);
cmd.Parameters.AddWithValue("#Content", documentContent);
cmd.Parameters.AddWithValue("#extn",extnt);
con.Open();
cmd.ExecuteNonQuery();
}
}
private void Donwload(int id)
{
DataTable dt = new DataTable();
using (SqlConnection cn = new SqlConnection(cs))
{
SqlCommand cmd = new SqlCommand("getdocument", cn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#ID", id);
cn.Open();
SqlDataReader reader = cmd.ExecuteReader();
dt.Load(reader);
}
string name = dt.Rows[0]["name"].ToString();
byte[] document = (byte[])dt.Rows[0]["DocumentContent"];
Response.ClearContent();
Response.ContentType = "application/octetstream";
Response.AddHeader("Content-Dispisition", string.Format("attachment;filename={0}", name));
Response.AddHeader("Content-Lenght", document.Length.ToString());
Response.BinaryWrite(document);
Response.Flush();
Response.Close();
}
protected void OpenDocument(object sender, EventArgs e)
{
LinkButton lnk = (LinkButton)sender;
GridViewRow gr = (GridViewRow)lnk.NamingContainer;
int id = int.Parse(GridView1.DataKeys[gr.RowIndex].Value.ToString());
Donwload(id);
}
}
}
and my html
<form id="form1" runat="server">
<div>
<table>
<tr>
<td>
<asp:Label ID="Label1" runat="server" Text="Document"></asp:Label>
<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:Button ID="Button1" runat="server" Text="Save" OnClick="Button1_Click" />
<br />
</td>
</tr>
</table>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="ID">
<Columns>
<asp:TemplateField HeaderText="Documents">
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" OnClick="OpenDocument" runat="server" Text='<%# Eval("name") %>'></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<br />
</div>
</form>
img

how to calculate total price in gridview in ASP.NET

I have a gridview in ASP.NET,In that gridview there is one column of total price.I want to show to total price of all rows below the gridview and also if i will update or delete any row then it should update that total computed price.
Can anyone please help in this.
Thanks in advance.
The HTML Markup consists of an ASP.Net GridView. The ShowFooter property is set to true so that the GridView’s Footer Row is displayed.
Paging has been enabled for the GridView and OnPageIndexChanging event handler has been assigned.
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" AllowPaging="true"
OnPageIndexChanging="OnPageIndexChanging" ShowFooter="true">
<Columns>
<asp:BoundField DataField="OrderID" HeaderText="Order ID" ItemStyle-Width="60" />
<asp:BoundField DataField="ProductName" HeaderText="Product Name" ItemStyle-Width="210" />
<asp:BoundField DataField="Price" HeaderText="Price" ItemStyle-Width="60" DataFormatString="{0:N2}"
ItemStyle-HorizontalAlign="Right" />
</Columns>
</asp:GridView>
code behind.
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
this.BindGrid();
}
}
private void BindGrid()
{
string query = "SELECT TOP 30 OrderID,";
query += "(SELECT ProductName FROM Products WHERE ProductID = details.ProductId) ProductName,";
query += "(Quantity * UnitPrice) Price";
query += " FROM [Order Details] details";
query += " ORDER BY OrderID";
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand(query))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
//Calculate Sum and display in Footer Row
decimal total = dt.AsEnumerable().Sum(row => row.Field<decimal>("Price"));
GridView1.FooterRow.Cells[1].Text = "Total";
GridView1.FooterRow.Cells[1].HorizontalAlign = HorizontalAlign.Right;
GridView1.FooterRow.Cells[2].Text = total.ToString("N2");
}
}
}
}
}

Gridview fields values does not change on update

I have a gridview and i want to modify some fields on gridview.This fields value not change when i click on Update button.I tried use Postback control but this problem keep going.How can i solve this problem?
ASPX code
<asp:GridView ID="gview" runat="server" AutoGenerateColumns="False" EnableModelValidation="True" GridLines="Horizontal" OnRowDataBound="gview_RowDataBound" OnRowEditing="gview_RowEditing" OnRowUpdating="gview_RowUpdating" OnRowCancelingEdit="gview_RowCancelingEdit">
<Columns>
<asp:BoundField DataField="SubCategoryId" HeaderText="ID" InsertVisible="False" ReadOnly="True"
SortExpression="SubCategoryId" />
<asp:TemplateField HeaderText="Category">
<ItemTemplate>
<asp:Label ID="lblCategory" runat="server"></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="ddlCategory" DataValueField="CategoryId" DataTextField="CategoryName" runat="server" />
</EditItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="CategoryName" HeaderText="Category Name" SortExpression="CategoryName" />
<asp:CommandField ButtonType="Link" EditText="Edit" HeaderText="Edit"
ShowEditButton="True" ShowHeader="False" CancelText="Cancel" UpdateText="Update" />
</Columns>
</asp:GridView>
C# code
protected void gview_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
Label lbl = e.Row.FindControl("lblCategory") as Label;
DropDownList ddl = e.Row.FindControl("ddlCategory") as DropDownList;
if ((e.Row.RowState & DataControlRowState.Edit) > 0)
{
ddl.DataSource = LoadCategories();
ddl.DataBind();
}
if (lbl != null)
{
lbl.Text = GetCategoryName(Convert.ToInt32(gview.DataKeys[e.Row.RowIndex][0]));
}
}
}
protected void gview_RowEditing(object sender, GridViewEditEventArgs e)
{
gview.EditIndex = e.NewEditIndex;
SubCategoryLoad();
}
protected void gview_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
int categoryId, subCategoryId;
string categoryName;
DropDownList ddl = (DropDownList)gview.Rows[e.RowIndex].FindControl("ddlCategory");
subCategoryId = int.Parse(gview.Rows[e.RowIndex].Cells[0].Text);
categoryId = int.Parse(ddl.SelectedValue);
categoryName = gview.Rows[e.RowIndex].Cells[2].Text;
gview.EditIndex = -1;
UpdateSubCategory(subCategoryId,categoryName,categoryId);
SubCategoryLoad();
}
public void SubCategoryLoad()
{
using (SqlConnection conn = new SqlConnection(DataBase.Conn))
{
conn.Open();
string query = "SELECT * FROM dbo.SubCategories";
using (SqlDataAdapter da = new SqlDataAdapter(query, conn))
{
DataTable dt = new DataTable();
da.Fill(dt);
gview.DataSource = dt;
gview.DataBind();
}
}
}
public int UpdateSubCategory(int subCategoryId, string categoryName, int categoryId)
{
using (SqlConnection conn = new SqlConnection(DataBase.Conn))
{
conn.Open();
string query = "UPDATE dbo.SubCategories SET CategoryId = #categoryId, CategoryName = #categoryName WHERE SubCategoryId = #id";
using (SqlCommand cmd = new SqlCommand(query, conn))
{
cmd.Parameters.AddWithValue("#id", subCategoryId);
cmd.Parameters.AddWithValue("#categoryName", categoryName);
cmd.Parameters.AddWithValue("#categoryId", categoryId);
return (int)cmd.ExecuteNonQuery();
}
}
}
Please check have you bind gridview inside
if(!page.ispostback)
{
}
You must update the data to the actual datasource and rebind it.
If you have updated the values then you shall rebind the GridView again with updated values
mGridView.DataSource = {YOUR DATA SOURCE};
mGridView.DataBind();
EDIT 1:
Does this method being called break there check that
have you set update as
commandText ="Update"

bind image from database to datalist

I am binding image to datalist.
My imagename is in database, i am taking it and wants to bind it to datalist.
I have tried following:
<asp:DataList ID="dlImages" runat="server">
<ItemTemplate>
<asp:ImageButton ID="ImageButton1" Height="200px" Width="200px"
ImageUrl='<%# Bind ("PageName","D:\Sagar\Kinston\WebSite\ScreenMasterImages\{0}") %>' runat="server" />
</ItemTemplate>
</asp:DataList>
on pageload i have bounded it as:
ds = gc.GetDataToListBinder("select DISTINCT PageOrderID,PageName from ScreenMaster order by PageOrderID")
dlImages.DataSource = ds.Tables(0)
dlImages.DataBind()
In above code ds is my dataset and gc.GetDataToListBinder(query) returns dataset.
But images are not getting displayed.
What can be the mistake?
EDIT1:
<asp:ImageButton ID="ImageButton1" Height="200px" Width="200px" ImageUrl='<%#Server.HtmlDecode(Eval("PageName","D:\Sagar\Kinston\WebSite\ScreenMasterImages\{0}.jpg")) %>' runat="server" />
Take a minute and read this:
http://www.codeproject.com/Articles/142013/There-is-something-about-Paths-for-Asp-net-beginne
I think this will help you alot.
EDIT:
For the space problem, take a look:
Why does HttpUtility.UrlEncode(HttpUtility.UrlDecode("%20")) return + instead of %20?
Basically:
ImageUrl='<%# Server.HtmlDecode(Bind("MyImage")) %>'
But i recommend that you store your image name without space in db.
EDIT2:
ImageUrl='<%# Eval("MyImage") %>'
ImageUrl='<%# Server.HtmlDecode(Eval("MyImage")) %>'
<asp:DataList ID="DataList1" runat="server" RepeatColumns="3"
RepeatDirection="Horizontal" CellPadding="2"
CellSpacing="2"
UseAccessibleHeader="True" >
<ItemTemplate>
<asp:ImageButton Width="120" Height="120" ID="Image1" ImageUrl='<%# Eval("Imgpath", "") %>' runat="server" />
</asp:Datalist>
.CS
SqlConnection con;
SqlCommand cmd;
string strCon = "Connection String";
SqlDataAdapter da;
protected void AlldataImg()
{
DataTable dt = new DataTable();
string strQuery = "select code,imgpath from SA_Stock order by Code";
cmd = new SqlCommand(strQuery);
con = new SqlConnection(strCon);
da = new SqlDataAdapter();
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
try
{
con.Open();
da.SelectCommand = cmd;
da.Fill(dt);
DataList1.DataSource = dt;
DataList1.DataBind();
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
finally
{
con.Close();
da.Dispose();
con.Dispose();
}
}
protected void Page_Load(object sender, EventArgs e)
{
AlldataImg();
}
Put Image Path in database too so that image will appear..
protected void DataListPosts_ItemDataBound(object sender, DataListItemEventArgs e)
{
try
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
DataRowView dr = (DataRowView)e.Item.DataItem;
Image ImageData = (Image)e.Item.FindControl("ImageData");
if (dr.Row[4].ToString() != "NA")
{
ImageData.Visible = true;
ImageData.ImageUrl = #"ImgPost/" + dr.Row["ImgPath"].ToString();
}
else
ImageData.Visible = false;
}
}
catch (Exception)
{ }
}
its a old topic but i think it can be usefull for anyone
firstly get your data from string
string sqlget = "select Photo from Promoter";
and get it to database dsget
then do that
dsget.Tables[0].Columns.Add("Photopath", typeof(string));
for (int i = 0; i < dsget.Tables[0].Rows.Count; i++)
{
if (dsget.Tables[0].Rows[i]["Photo"].ToString() != null && dsget.Tables[0].Rows[i]["Photo"].ToString() != "")
{
var data = (Byte[])(dsget.Tables[0].Rows[i]["Photo"]);
var stream = new MemoryStream(data);
System.IO.BinaryReader br = new System.IO.BinaryReader(stream);
FileBytes = br.ReadBytes((Int32)stream.Length);
string base64String = Convert.ToBase64String(FileBytes, 0, FileBytes.Length);
dsget.Tables[0].Rows[i]["Photopath"] = "data:image/png;base64," + base64String;
}
}
DataList1.DataSource = dsget.Tables[0];
DataList1.DataBind();
in asp file write the following thing

Pls modify this code for retrieving the image from sqldatabase

I am still suffering from retrieving an image from a SQL database. This is my final solution for inserting and retrieving an image from database. Here is all my code:
GUI part:
<div>
<asp:Label ID="lblImage" runat="server" Text="Image"></asp:Label>
<asp:FileUpload ID="imageUpload" runat="server" />
<br />
<asp:Label ID="lblFilename" runat="server" Text="Filename"></asp:Label>
<asp:TextBox ID="txtFilename" runat="server"></asp:TextBox>
<br />
<br />
<asp:Button ID="BtnSave" runat="server" Text="SAVE" onclick="BtnSave_Click" />
<br />
<br />
<br />
<asp:Image ID="Image1" runat="server" />
</div>
And under the Button click event i have written the following code:
protected void BtnSave_Click(object sender, EventArgs e)
{
string uploadFileName = string.Empty;
byte[] imageBytes = null;
if (imageUpload != null && imageUpload.HasFile)
{
uploadFileName = imageUpload.FileName;
imageBytes = imageUpload.FileBytes;
}
string str = ConfigurationManager.ConnectionStrings["ImageConnectionString"].ConnectionString;
SqlConnection con = new SqlConnection(str);
SqlCommand com = new SqlCommand("INSERT INTO REPORT_TABLE (IMAGEFIELD,IMAGENAME) VALUES (#image,#filename)", con);
com.Parameters.Add("#image", SqlDbType.Image, imageBytes.Length).Value = imageBytes;
com.Parameters.Add("#filename", SqlDbType.VarChar, 50).Value = uploadFileName;
con.Open();
com.ExecuteNonQuery();
con.Close();
SqlConnection conn = new SqlConnection(str);
string sql = "SELECT * FROM [REPORT_TABLE]";
SqlDataAdapter da = new SqlDataAdapter(sql, conn);
DataSet ds = new DataSet();
da.Fill(ds);
DataRow dr = ds.Tables[0].Rows[0];
Byte[] b = (Byte[])dr["IMAGEFIELD"];
MemoryStream ms = new MemoryStream(b);
**this.pictureBox1.Image = Image.FromStream(ms)**; //(This code is for a Windows application but I want to retrieve an image from a web application) so what should be written instead of the highlighted code? In imagecontrol, image id is Image1.
}
you can server image like this:
.....
Image img= Image.FromStream(ms);
Response.Clear();
Response.ContentType = "image/jpeg";
img.Save(Response.OutputStream, ImageFormat.Jpeg);
}
but this will not put image in the <asp:Image ID="Image1" runat="server" /> because it needs image url not the image object :(
what you can do is setup a separate page to serve image and pass it image id or other unique identifier associated with image to show it in the <asp:Image ID="Image1" runat="server" />. simply add new page to your solution say ImageServer.aspx and in page_load write following:
protected void Page_Load(object sender, EventArgs e)
{
if(Request.QueryString.HasValues())
{
var id=Request.QueryString["id"];
if(!string.IsEmptyOrNull(id))
{
SqlConnection conn = new SqlConnection(str);
//CHANGE SELECT TO GET ONLY IMAGE WITH PASSED ID
string sql = "SELECT * FROM [REPORT_TABLE]";
SqlDataAdapter da = new SqlDataAdapter(sql, conn);
DataSet ds = new DataSet();
da.Fill(ds);
DataRow dr = ds.Tables[0].Rows[0];
Byte[] b = (Byte[])dr["IMAGEFIELD"];
MemoryStream ms = new MemoryStream(b);
Response.Clear();
Response.ContentType = "image/jpeg";
var img=system.Drawing.Image.FromStream(ms);
img.Save((Response.OutputStream, ImageFormat.Jpeg);
Response.Flush();
return;
}
//HERE YOU MAY RETURN DEFAULT OR ERROR IMAGE
}
}
Now change you button click in upload page as follows:
protected void BtnSave_Click(object sender, EventArgs e)
{
....
//SAVE IMAGE TO DB AND GET IMAGE ID (TO IDENTIFY THIS IMAGE)
image.ImageUrl = "YOUR_SERVER\ImageServer.aspx?id=" + IMAGE_ID;
}

Resources