Monday, February 9, 2015

How to Update Image in GridView in Asp.Net.

Here we are binding a GridView in Asp.Net and C#.

Points Of Remember:

1. Place LinkButton Edit in ItemTemplate and LinkButton Update and Cancel in EditTamplate of GridView's column.
2. Fire GridView's RowEditing event for LinkButton Edit.
3. Fire GridView's RowUpdating event for LinkButton Update.
4. Fire GridView's RowCancelingEdit event for LinkButton Cancel.
5. Set CommandName propery of LinkButtons according to their respective event.
6. Set GridView's DataKeyNames Property to record ID (ID=Primary/Unique key of student table)
7. Create a UserImages folder to store user images.
8. Add namespace System.Data and System.Data.SqlClient in your C# page.
<!DOCTYPE html>
 
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>How to update image in GridView</title>
</head>
<body>
 <form id="form1" runat="server">
   <div>
    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" AllowPaging="True"
        OnRowCancelingEdit="GridView1_RowCancelingEdit" DataKeyNames="ID" CellPadding="4"
        OnRowEditing="GridView1_RowEditing" OnRowUpdating="GridView1_RowUpdating" 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("Name") %>'></asp:Label>
            </ItemTemplate>
            <EditItemTemplate>
                <asp:TextBox ID="txt_Name" runat="server" Text='<%# Eval("Name") %>'></asp:TextBox>
            </EditItemTemplate>
        </asp:TemplateField>
              
        <asp:TemplateField HeaderText="Image" HeaderStyle-Width="200px">
            <ItemTemplate>
                <asp:Image ID="Image1" runat="server" ImageUrl='<%# Eval("Image") %>'
                     Height="80px" Width="100px" />
            </ItemTemplate>
            <EditItemTemplate>
                <asp:Image ID="img_user" runat="server" ImageUrl='<%# Eval("Image") %>'
                     Height="80px" Width="100px" /><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>

C# Codes :

using System.Data;
using System.Data.SqlClient;
 
public partial class test_ImageUploding : System.Web.UI.Page
{
    // sql connection
    SqlConnection con = new SqlConnection(@"Data Source=RAVI-PC\SQL;Initial
                                           Catalog=db_Student;Integrated Security=True");
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BindGridView();
        }
    }
    //method for binding GridView
    protected void BindGridView()
    {
        DataTable dt = new DataTable();
        SqlDataAdapter da = new SqlDataAdapter("Select ID, Name,Branch,City,Image from tbl_student"
                                                                                                                 , con);
        con.Open();
        da.Fill(dt);
        con.Close();
 
        if (dt.Rows.Count > 0)
        {
            GridView1.DataSource = dt;
            GridView1.DataBind();
        }
    }
 
    // edit event
    protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
    {
        GridView1.EditIndex = e.NewEditIndex;
        BindGridView();
 
    }
    // update event
    protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        //find student id of edit row
        string id = GridView1.DataKeys[e.RowIndex].Value.ToString();
        // find values for update
        TextBox name = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txt_Name");
 
        FileUpload FileUpload1 = (FileUpload)GridView1.Rows[e.RowIndex].FindControl("FileUpload1");
 
        string path = "~/Images/UserImage/";
        if (FileUpload1.HasFile)
        {
            path += FileUpload1.FileName;
            //save image in folder
            FileUpload1.SaveAs(MapPath(path));
        }
        else
        {
            // use previous user image if new image is not changed
            Image img = (Image)GridView1.Rows[e.RowIndex].FindControl("img_user");
            path = img.ImageUrl;
        }
 
        SqlCommand cmd = new SqlCommand("update tbl_student set Name='" + name.Text + "',
                                                                                                image='"+path+"'  where ID=" + id + "", con);
        con.Open();
        cmd.ExecuteNonQuery();
        con.Close();
 
        GridView1.EditIndex = -1;
        BindGridView();
    }
    // cancel edit event
    protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
        GridView1.EditIndex = -1;
        BindGridView();
    }
}

View output :

demoimage



Now over to you:
"A blog is nothing without reader's feedback and comments. So please provide your valuable feedback so that i can make this blog better and If you like my work; you can appreciate by leaving your comments. Stay tuned and stay connected for more technical updates."

No comments:

Post a Comment