GridView da Yuklenen Resimleri Güncellemek
Merhaba arkadaslar bu makalemizde FileUpload ile GridView nesnesine resim ekliyoruz. Sonrasinda GridView da düzenleme yapmak istedigimiz satirdaki Edit linkine tikliyoruz.
Sekil 1
Düzenleme yapilacak resimin altinda olusan Choose File butonuna tikliyoruz. Yüklemek istedigimiz yeni resimi seçip ekliyoruz. Sonrasinda degisikliklerin kalici olmasini saglamak için Update linkine tikliyoruz.
Sayfamiza Solution Explorer da projeye sag tiklayip Add > Add New Item den Generic Handler ekliyoruz.
Sekil 2
Image güncellemeleri yaptiktan sonra asagidaki gibi ekran çiktimiz olacaktir.
Sekil 3
Default.aspx.cs
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class _Default : System.Web.UI.Page
{
int rowIndex;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
bindList();
}
}
SqlConnection con = new SqlConnection("Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\\Image.mdf;Integrated Security=True");
protected void bindList()
{
{
con.Open();
SqlCommand cmd = new SqlCommand("select * from Images", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
int i = ds.Tables[0].Rows.Count;
con.Close();
GridView1.DataSource = ds;
GridView1.DataBind();
}
}
// edit event. duzenleme olayi
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
bindList();
}
// update event. guncelleme olayi
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
//find img id of edit row. duzenleme yapilacak satirin id sini buluyoruz.
string id = GridView1.DataKeys[e.RowIndex].Value.ToString();
// find values for update. gunceleme icin degeri buluyoruz.
TextBox name = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txt_Name");
FileUpload FileUpload1 = (FileUpload)GridView1.Rows[e.RowIndex].FindControl("FileUpload1");
//resimlerin kaydedilecegi yolu tanimliyoruz.
string path = "/resim/";
if (FileUpload1.HasFile)
{
path += FileUpload1.FileName;
//save image in folder. resmi kaydediyoruz.
FileUpload1.SaveAs(MapPath(path));
}
else
{
// use previous user image if new image is not changed
//yeni resim degismediginde onceki kullanici resmini kullaniyoruz.
Image img = (Image)GridView1.Rows[e.RowIndex].FindControl("Image2");
path = img.ImageUrl;
}
int length = FileUpload1.PostedFile.ContentLength;
byte[] imgbyte = new byte[length];
HttpPostedFile imgfile = FileUpload1.PostedFile;
//binary verimizin ayarlarini yapiyoruz.
imgfile.InputStream.Read(imgbyte, 0, length);
string filename = Path.GetFileName(FileUpload1.PostedFile.FileName);
rowIndex = rowIndex+1;
string strSql = "UPDATE [Images] SET ImageName=@imgname, Image=@img WHERE ImageId=@id";
SqlCommand cmd = new SqlCommand(strSql, con);
cmd.Parameters.Add(new SqlParameter("@imgname", name.Text));
cmd.Parameters.Add(new SqlParameter("@img", imgbyte));
cmd.Parameters.Add(new SqlParameter("@id", id));
con.Open();
cmd.ExecuteNonQuery();
con.Close();
GridView1.EditIndex = -1;
bindList();
}
// cancel edit event. duzenlemeyi iptal etme olayi.
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
bindList();
}
string resimPath;
protected void btnUpload_Click(object sender, EventArgs e)
{
con.Open();
if (FileUpload2.HasFile)
{
FileUpload2.SaveAs(Server.MapPath("resim/" + FileUpload2.FileName));
string ad = TextBox1.Text;
string resim = FileUpload2.FileName;
SqlCommand cmd2 = new SqlCommand("select * from Images", con);
SqlDataAdapter da = new SqlDataAdapter(cmd2);
DataSet ds = new DataSet();
da.Fill(ds);
int i = ds.Tables[0].Rows.Count;
i +=i;
SqlCommand cmd = new SqlCommand("insert into Images(ImageId,ImageName,Image) values ('" + i + "','" + ad + "','" + resim + "')", con);
int sonuc = cmd.ExecuteNonQuery();
if (sonuc > 0)
{
Label2.Text = "Veritabanina kayit basariyla eklendi.";
}
else
{
Label2.Text = "Veritabanina kayit eklemede hata olustu.";
}
}
else
{
Label2.Text = "Kaydetme islemi için resim ekleyiniz.";
}
}
protected void Button1_Click(object sender, EventArgs e)
{
}
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
GridViewRow gvr = (GridViewRow)((Control)e.CommandSource).NamingContainer;
rowIndex = gvr.RowIndex;
Label2.Text = rowIndex.ToString();
}
}
Default.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<br />
<asp:FileUpload ID="FileUpload2" runat="server" />
<asp:Button ID="btnUpload" runat="server" Text="Yükle" OnClick="btnUpload_Click" />
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" />
<br />
<asp:Label ID="Label2" runat="server" Text="Label"></asp:Label>
<br />
<br />
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" AllowPaging="True"
OnRowCancelingEdit="GridView1_RowCancelingEdit" DataKeyNames="ImageId" CellPadding="4"
OnRowEditing="GridView1_RowEditing" OnRowUpdating="GridView1_RowUpdating" OnRowCommand="GridView1_RowCommand" ForeColor="#333333">
<Columns>
<asp:TemplateField HeaderStyle-Width="150px">
<ItemTemplate>
<asp:LinkButton ID="LkB1" runat="server" CommandName="Edit">Edit</asp:LinkButton>
</ItemTemplate>
<EditItemTemplate>
<asp:LinkButton ID="LkB2" runat="server" CommandName="Update">Update</asp:LinkButton>
<asp:LinkButton ID="LkB3" runat="server" CommandName="Cancel">Cancel</asp:LinkButton>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Name" HeaderStyle-Width="200px">
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Eval("ImageName") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txt_Name" runat="server" Text='<%# Eval("ImageName") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Image" HeaderStyle-Width="200px">
<ItemTemplate>
<asp:Image ID="Image1" runat="server" ImageUrl='<%# "ImageHandler.ashx?imageId="+ Eval("ImageId") %>' Height="150px" Width="150px" />
</ItemTemplate>
<EditItemTemplate>
<asp:Image ID="Image2" runat="server" ImageUrl='<%# "ImageHandler.ashx?imageId="+ Eval("ImageId") %>' Height="150px" Width="150px" />
<br />
<asp:FileUpload ID="FileUpload1" runat="server" />
</EditItemTemplate>
</asp:TemplateField>
</Columns>
<HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
</asp:GridView>
</div>
</form>
</body>
</html>
ImageHandler.ashx
<%@ WebHandler Language="C#" Class="ImageHandler" %>
using System;
using System.Web;
using System.Data.SqlClient;
public class ImageHandler : IHttpHandler {
public void ProcessRequest (HttpContext context) {
string imageid = context.Request.QueryString["imageId"];
SqlConnection con = new SqlConnection("Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\\Image.mdf;Integrated Security=True");
con.Open();
SqlCommand cmd = new SqlCommand("Select Image From Images Where ImageId=" + imageid, con);
SqlDataReader dr = cmd.ExecuteReader();
dr.Read();
context.Response.BinaryWrite((byte[])dr[0]);
con.Close();
context.Response.End();
}
public bool IsReusable {
get {
return false;
}
}
}
Bir makalenin daha sonuna geldik. Bir sonraki makalede görüsmek üzere. Bahadir SAHIN