locked
file uploading RRS feed

  • Question

  • User-2020424237 posted

    hiii

       i had uploaded a file the values of that html file will stored into database

    example---html file contains list of name and ages such as raj,surya, and age--12,45 this values of that file will store in database when we upload that file into database

    Tuesday, February 7, 2012 4:02 AM

Answers

  • User436416516 posted

    Hi Achyuth,

    Click Here to view the sampe code

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, February 8, 2012 3:07 AM
  • User3866881 posted

    i want to upload a file and i want store  that values of that file into database am completely new to this field plz help me..

    In CodeProj we've offered you a sample of submitting an image into db,you can also refer this sample:

    Download

    Here's the sample codes:

    <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="CSASPNETImageEditUpload._Default" %>
    
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title>Personal Information</title>
    </head>
    <body>
        <form id="form1" runat="server">
        <div>
            <h2>
                OverView of Persons</h2>
            <asp:SqlDataSource ID="SqlDSPersonOverView" runat="server" ConnectionString="<%$ ConnectionStrings:db_PersonsConnectionString %>"
                SelectCommand="SELECT [Id], [PersonName] FROM [tb_personInfo]"></asp:SqlDataSource>
            <asp:GridView ID="gvPersonOverView" runat="server" CellPadding="4" EnableModelValidation="True"
                ForeColor="#333333" GridLines="None" Width="70%" AutoGenerateColumns="False"
                DataKeyNames="Id" DataSourceID="SqlDSPersonOverView" OnSelectedIndexChanged="gvPersonOverView_SelectedIndexChanged"
                AllowPaging="True" AllowSorting="True">
                <AlternatingRowStyle BackColor="White" ForeColor="#284775" />
                <Columns>
                    <asp:BoundField DataField="Id" HeaderText="Id" InsertVisible="False" ReadOnly="True"
                        SortExpression="Id" />
                    <asp:BoundField DataField="PersonName" HeaderText="PersonName" SortExpression="PersonName" />
                    <asp:CommandField ShowSelectButton="True" HeaderText="Click to see Details" SelectText="Details..." />
                </Columns>
                <EditRowStyle BackColor="#999999" />
                <EmptyDataTemplate>
                    No Data Available, Please Insert data with the help of the FormView...<br />
                </EmptyDataTemplate>
                <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
                <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
                <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
                <RowStyle BackColor="#F7F6F3" ForeColor="#333333" HorizontalAlign="Center" VerticalAlign="Middle" />
                <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
            </asp:GridView>
        </div>
        <h2>
            Person In Detail</h2>
        <asp:FormView ID="fvPersonDetails" runat="server" Width="50%" DataSourceID="SqlDSPersonDetails"
            EnableModelValidation="True" DataKeyNames="Id" DataMember="DefaultView" OnItemInserting="fvPersonDetails_ItemInserting"
            OnItemUpdating="fvPersonDetails_ItemUpdating" BackColor="#DEBA84" BorderColor="#DEBA84"
            BorderStyle="None" BorderWidth="1px" CellPadding="3" CellSpacing="2" GridLines="Both"
            OnItemUpdated="fvPersonDetails_ItemUpdated" OnItemDeleted="fvPersonDetails_ItemDeleted"
            OnItemDeleting="fvPersonDetails_ItemDeleting" OnItemInserted="fvPersonDetails_ItemInserted"
            OnModeChanging="fvPersonDetails_ModeChanging">
            <ItemTemplate>
                <table width="100%">
                    <tr>
                        <th>
                            Person Name:
                        </th>
                        <td colspan="2">
                            <%#Eval("PersonName") %>
                        </td>
                    </tr>
                    <tr>
                        <th>
                            Person Image:
                        </th>
                        <td colspan="2">
                            <img src='ImageHandler/ImageHandler.ashx?id=<%#Eval("Id") %>' width="200" alt=""
                                height="200" />
                        </td>
                    </tr>
                    <tr>
                        <td align="center">
                            <asp:LinkButton ID="lnkEdit" runat="server" CommandName="Edit" Text="Edit" />
                        </td>
                        <td align="center">
                            <asp:LinkButton ID="lnkDelete" runat="server" CommandName="Delete" Text="Delete"
                                OnClientClick="return confirm('Are you sure to delete it completely?');" />
                        </td>
                        <td align="center">
                            <asp:LinkButton ID="lnkNew" runat="server" CommandName="New" Text="New" />
                        </td>
                    </tr>
                </table>
            </ItemTemplate>
            <EditItemTemplate>
                <table width="100%">
                    <tr>
                        <th>
                            Person Name:
                        </th>
                        <td>
                            <asp:TextBox ID="txtName" runat="server" Text=' <%#Bind("PersonName") %>' MaxLength="20" />
                            <asp:RequiredFieldValidator ID="reqName" runat="server" ControlToValidate="txtName"
                                ErrorMessage="Name is required!">*</asp:RequiredFieldValidator>
                        </td>
                    </tr>
                    <tr>
                        <th>
                            Person Image:
                        </th>
                        <td>
                            <asp:FileUpload ID="fupEditImage" runat="server" />
                            <asp:CustomValidator ID="cmvImageType" runat="server" ControlToValidate="fupEditImage"
                                ErrorMessage="File is invalid!" OnServerValidate="CustomValidator1_ServerValidate"></asp:CustomValidator>
                        </td>
                    </tr>
                    <tr>
                        <td align="center">
                            <asp:LinkButton ID="lnkUpdate" runat="server" CommandName="Update" Text="Update" />
                        </td>
                        <td align="center">
                            <asp:LinkButton ID="lnkCancel" runat="server" CommandName="Cancel" Text="Cancel"
                                CausesValidation="False" />
                        </td>
                    </tr>
                </table>
            </EditItemTemplate>
            <EditRowStyle BackColor="#738A9C" Font-Bold="True" ForeColor="White" />
            <FooterStyle BackColor="#F7DFB5" ForeColor="#8C4510" />
            <HeaderStyle BackColor="#A55129" Font-Bold="True" ForeColor="White" />
            <InsertItemTemplate>
                <table width="100%">
                    <tr>
                        <th>
                            Person Name:
                        </th>
                        <td>
                            <asp:TextBox ID="txtName" runat="server" MaxLength="20" Text='<%#Bind("PersonName") %>'></asp:TextBox>
                            <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="txtName"
                                ErrorMessage="Name is required!">*</asp:RequiredFieldValidator>
                        </td>
                    </tr>
                    <tr>
                        <th>
                            Person Image:
                        </th>
                        <td>
                            <asp:FileUpload ID="fupInsertImage" runat="server" />
                            <asp:CustomValidator ID="cmvImageType" runat="server" ControlToValidate="fupInsertImage"
                                ErrorMessage="File is invalid!" OnServerValidate="CustomValidator1_ServerValidate"></asp:CustomValidator>
                        </td>
                    </tr>
                    <tr>
                        <td align="center">
                            <asp:LinkButton ID="lnkInsert" runat="server" CommandName="Insert" Text="Insert" />
                        </td>
                        <td align="center">
                            <asp:LinkButton ID="lnkInsertCancel" runat="server" CommandName="Cancel" Text="Cancel"
                                CausesValidation="False" />
                        </td>
                    </tr>
                </table>
            </InsertItemTemplate>
            <PagerStyle HorizontalAlign="Center" ForeColor="#8C4510" />
            <RowStyle BackColor="#FFF7E7" ForeColor="#8C4510" />
        </asp:FormView>
        <asp:SqlDataSource ID="SqlDSPersonDetails" runat="server" ConnectionString="<%$ ConnectionStrings:db_PersonsConnectionString %>"
            DeleteCommand="DELETE FROM tb_personInfo WHERE (Id = @Id)" InsertCommand="INSERT INTO tb_personInfo(PersonName, PersonImage, PersonImageType) VALUES (@PersonName, @PersonImage, @PersonImageType)"
            SelectCommand="SELECT [Id], [PersonName] FROM [tb_personInfo] where id=@id" UpdateCommand="UPDATE tb_personInfo SET PersonName = @PersonName, PersonImage = @PersonImage, PersonImageType = @PersonImageType WHERE (Id = @Id)">
            <DeleteParameters>
                <asp:Parameter Name="Id" Type="Int32" />
            </DeleteParameters>
            <InsertParameters>
                <asp:Parameter Name="PersonName" Type="String" />
                <asp:Parameter Name="PersonImage" DbType="Binary" ConvertEmptyStringToNull="true" />
                <asp:Parameter Name="PersonImageType" Type="String" ConvertEmptyStringToNull="true" />
            </InsertParameters>
            <UpdateParameters>
                <asp:Parameter Name="PersonName" Type="String" />
                <asp:Parameter Name="PersonImage" DbType="Binary" ConvertEmptyStringToNull="true" />
                <asp:Parameter Name="PersonImageType" Type="String" ConvertEmptyStringToNull="true" />
                <asp:Parameter Name="Id" Type="Int32" />
            </UpdateParameters>
            <SelectParameters>
                <asp:ControlParameter Name="id" Type="Int32" ControlID="gvPersonOverView" PropertyName="SelectedValue"
                    DefaultValue="0" />
            </SelectParameters>
        </asp:SqlDataSource>
        </form>
    </body>
    </html>
    /****************************** Module Header ******************************\ * Module Name: Default.aspx.cs * Project: CSASPNETImageEditUpload * Copyright (c) Microsoft Corporation * * The project shows up how to insert,edit or update an image and store * it into Sql database. * * This source is subject to the Microsoft Public License. * See http://www.microsoft.com/opensource/licenses.mspx#Ms-PL. * All other rights reserved. \***************************************************************************/
    
    using System.Collections.Generic;
    using System.Web.UI.WebControls;
    using System;
    using System.Data.SqlClient;
    using System.IO;
    
    
    namespace CSASPNETImageEditUpload
    {
        public partial class _Default : System.Web.UI.Page
        {
            // Static types of common images for checking.
            private static List<string> imgytpes = new List<string>()
            {
                ".BMP",".GIF",".JPG",".PNG"
            };
    
    
            /// <summary>
            /// Read all records into GridView.
            /// If has records, select the first record to be shown in the FormView
            /// as default; otherwise, change the formview to insert mode so as to let
            /// data to be inserted.
            /// </summary>
            protected void Page_Load(object sender, EventArgs e)
            {
                if (!IsPostBack)
                {
                    gvPersonOverView.DataBind();
    
                    if (gvPersonOverView.Rows.Count > 0)
                    {
                        gvPersonOverView.SelectedIndex = 0;
                        fvPersonDetails.ChangeMode(FormViewMode.ReadOnly);
                        fvPersonDetails.DefaultMode = FormViewMode.ReadOnly;
                    }
                    else
                    {
                        fvPersonDetails.ChangeMode(FormViewMode.Insert);
                        fvPersonDetails.DefaultMode = FormViewMode.Insert;
                    }
                }
            }
    
    
            /// <summary>
            /// Validate whether data satisfies the type of image.
            /// </summary>
            protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args)
            {
                if (args.Value != null && args.Value != "")
                {
                    args.IsValid = imgytpes.IndexOf(System.IO.Path.GetExtension(args.Value).ToUpper()) >= 0;
                }
            }
    
    
            /// <summary>
            /// After checking the validation of the image type,
            /// assign the image type and the image byte collection through
            /// the e.Values argument and do the insert.
            /// </summary>
            protected void fvPersonDetails_ItemInserting(object sender, FormViewInsertEventArgs e)
            {
                object obj = Session["insertstate"];
    
                if (obj == null || (bool)obj)
                {
                    CustomValidator cv = fvPersonDetails.FindControl("cmvImageType") as CustomValidator;
    
                    cv.Validate();
                    e.Cancel = !cv.IsValid;
    
                    FileUpload fup = (FileUpload)fvPersonDetails.FindControl("fupInsertImage");
    
                    if (cv.IsValid && fup.PostedFile.FileName.Trim() != "")
                    {
                        e.Values["PersonImage"] = File.ReadAllBytes(fup.PostedFile.FileName);
                        e.Values["PersonImageType"] = fup.PostedFile.ContentType;
                    }
    
                }
                else
                {
                    e.Cancel = true;
                    gvPersonOverView.DataBind();
                    fvPersonDetails.ChangeMode(FormViewMode.ReadOnly);
                    fvPersonDetails.DefaultMode = FormViewMode.ReadOnly;
                }
            }
    
    
            /// <summary>
            /// After checking the validation of the image type,
            /// assign the image type and the image byte collection through
            /// the e.Values argument and do the update.
            /// </summary>
            protected void fvPersonDetails_ItemUpdating(object sender, FormViewUpdateEventArgs e)
            {
                CustomValidator cv = fvPersonDetails.FindControl("cmvImageType") as CustomValidator;
    
                cv.Validate();
                e.Cancel = !cv.IsValid;
    
                FileUpload fup = (FileUpload)fvPersonDetails.FindControl("fupEditImage");
    
                if (cv.IsValid && fup.PostedFile.FileName.Trim() != "")
                {
                    e.NewValues["PersonImage"] = File.ReadAllBytes(fup.PostedFile.FileName);
                    e.NewValues["PersonImageType"] = fup.PostedFile.ContentType;
                }
            }
    
    
            /// <summary>
            /// After updated, re-databind data and select the first one as default.
            /// </summary>
            protected void fvPersonDetails_ItemUpdated(object sender, FormViewUpdatedEventArgs e)
            {
                gvPersonOverView.DataBind();
                gvPersonOverView.SelectedIndex = gvPersonOverView.SelectedRow.RowIndex;
            }
    
    
            /// <summary>
            /// After inserted successfully, re-databind data,select the first one as default,
            /// Change the FormView mode to ReadOnly (for viewing).
            /// </summary>
            protected void fvPersonDetails_ItemInserted(object sender, FormViewInsertedEventArgs e)
            {
                gvPersonOverView.DataBind();
                gvPersonOverView.SelectedIndex = gvPersonOverView.Rows.Count - 1;
                fvPersonDetails.ChangeMode(FormViewMode.ReadOnly);
                fvPersonDetails.DefaultMode = FormViewMode.ReadOnly;
            }
    
    
            /// <summary>
            /// After deleted successfully, re-databind data.
            /// </summary>
            protected void fvPersonDetails_ItemDeleted(object sender, FormViewDeletedEventArgs e)
            {
                gvPersonOverView.DataBind();
    
                // If still has records
                if (gvPersonOverView.Rows.Count > 0)
                {
                    // Take out the index of row to be deleted
                    int delindex = (int)ViewState["delindex"];
    
                    // If the first record is deleted,Move to its next record.
                    if (delindex == 0)
                    {
                        gvPersonOverView.SelectedIndex = 0;
                    }
    
                    // If the last record is deleted, Move to its previous one.
                    else if (delindex == gvPersonOverView.Rows.Count)
                    {
                        gvPersonOverView.SelectedIndex = gvPersonOverView.Rows.Count - 1;
                    }
    
                    // Otherwise, move to the next record after itself is deleted.
                    else
                    {
                        gvPersonOverView.SelectedIndex = delindex;
                    }
    
                }
    
                // If has no records, change to insert mode for insering new records.
                else
                {
                    fvPersonDetails.ChangeMode(FormViewMode.Insert);
                    fvPersonDetails.DefaultMode = FormViewMode.Insert;
                }
            }
    
    
            /// <summary>
            /// To show detail image and information in the FormView when GridView's
            /// SelectedRowIndex Changed.
            /// </summary>
            protected void gvPersonOverView_SelectedIndexChanged(object sender, EventArgs e)
            {
                fvPersonDetails.ChangeMode(FormViewMode.ReadOnly);
                fvPersonDetails.DefaultMode = FormViewMode.ReadOnly;
            }
    
    
            /// <summary>
            /// Keep the row index into ViewState for the usage of Item_Deleted.
            /// </summary>
            protected void fvPersonDetails_ItemDeleting(object sender, FormViewDeleteEventArgs e)
            {
                ViewState["delindex"] = gvPersonOverView.SelectedIndex;
            }
    
    
            /// <summary>
            /// Keep the insertState into Session to avoid the duplicated inserting
            /// after refreshing page.
            /// </summary>
            protected void fvPersonDetails_ModeChanging(object sender, FormViewModeEventArgs e)
            {
                Session["insertstate"] = (e.NewMode == FormViewMode.Insert);
    
            }
        }
    }
    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, February 8, 2012 8:16 PM

All replies

  • User436416516 posted

    Hi Achyuth,

    using file upload control you can upload any file from client machine to server, then convert that to bytes,then save it as image ( or varbinarry , etc )column in DB.

                //save document image..
                    FileStream fs = new FileStream(<<Filepath>>, FileMode.Open, FileAccess.Read);
                    BinaryReader br = new BinaryReader(fs);
                    Byte[] bytes = br.ReadBytes((Int32)fs.Length);
                    br.Close();

    replace <<Filepath>> by your path.

    save the bytes into ur DB.

    Tuesday, February 7, 2012 4:13 AM
  • User-2020424237 posted

    i want to upload a file and i want store  that values of that file into database am completely new to this field plz help me..

    Tuesday, February 7, 2012 5:01 AM
  • User436416516 posted

    Hi Achyuth,

    Click Here to view the sampe code

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, February 8, 2012 3:07 AM
  • User3866881 posted

    i want to upload a file and i want store  that values of that file into database am completely new to this field plz help me..

    In CodeProj we've offered you a sample of submitting an image into db,you can also refer this sample:

    Download

    Here's the sample codes:

    <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="CSASPNETImageEditUpload._Default" %>
    
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title>Personal Information</title>
    </head>
    <body>
        <form id="form1" runat="server">
        <div>
            <h2>
                OverView of Persons</h2>
            <asp:SqlDataSource ID="SqlDSPersonOverView" runat="server" ConnectionString="<%$ ConnectionStrings:db_PersonsConnectionString %>"
                SelectCommand="SELECT [Id], [PersonName] FROM [tb_personInfo]"></asp:SqlDataSource>
            <asp:GridView ID="gvPersonOverView" runat="server" CellPadding="4" EnableModelValidation="True"
                ForeColor="#333333" GridLines="None" Width="70%" AutoGenerateColumns="False"
                DataKeyNames="Id" DataSourceID="SqlDSPersonOverView" OnSelectedIndexChanged="gvPersonOverView_SelectedIndexChanged"
                AllowPaging="True" AllowSorting="True">
                <AlternatingRowStyle BackColor="White" ForeColor="#284775" />
                <Columns>
                    <asp:BoundField DataField="Id" HeaderText="Id" InsertVisible="False" ReadOnly="True"
                        SortExpression="Id" />
                    <asp:BoundField DataField="PersonName" HeaderText="PersonName" SortExpression="PersonName" />
                    <asp:CommandField ShowSelectButton="True" HeaderText="Click to see Details" SelectText="Details..." />
                </Columns>
                <EditRowStyle BackColor="#999999" />
                <EmptyDataTemplate>
                    No Data Available, Please Insert data with the help of the FormView...<br />
                </EmptyDataTemplate>
                <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
                <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
                <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
                <RowStyle BackColor="#F7F6F3" ForeColor="#333333" HorizontalAlign="Center" VerticalAlign="Middle" />
                <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
            </asp:GridView>
        </div>
        <h2>
            Person In Detail</h2>
        <asp:FormView ID="fvPersonDetails" runat="server" Width="50%" DataSourceID="SqlDSPersonDetails"
            EnableModelValidation="True" DataKeyNames="Id" DataMember="DefaultView" OnItemInserting="fvPersonDetails_ItemInserting"
            OnItemUpdating="fvPersonDetails_ItemUpdating" BackColor="#DEBA84" BorderColor="#DEBA84"
            BorderStyle="None" BorderWidth="1px" CellPadding="3" CellSpacing="2" GridLines="Both"
            OnItemUpdated="fvPersonDetails_ItemUpdated" OnItemDeleted="fvPersonDetails_ItemDeleted"
            OnItemDeleting="fvPersonDetails_ItemDeleting" OnItemInserted="fvPersonDetails_ItemInserted"
            OnModeChanging="fvPersonDetails_ModeChanging">
            <ItemTemplate>
                <table width="100%">
                    <tr>
                        <th>
                            Person Name:
                        </th>
                        <td colspan="2">
                            <%#Eval("PersonName") %>
                        </td>
                    </tr>
                    <tr>
                        <th>
                            Person Image:
                        </th>
                        <td colspan="2">
                            <img src='ImageHandler/ImageHandler.ashx?id=<%#Eval("Id") %>' width="200" alt=""
                                height="200" />
                        </td>
                    </tr>
                    <tr>
                        <td align="center">
                            <asp:LinkButton ID="lnkEdit" runat="server" CommandName="Edit" Text="Edit" />
                        </td>
                        <td align="center">
                            <asp:LinkButton ID="lnkDelete" runat="server" CommandName="Delete" Text="Delete"
                                OnClientClick="return confirm('Are you sure to delete it completely?');" />
                        </td>
                        <td align="center">
                            <asp:LinkButton ID="lnkNew" runat="server" CommandName="New" Text="New" />
                        </td>
                    </tr>
                </table>
            </ItemTemplate>
            <EditItemTemplate>
                <table width="100%">
                    <tr>
                        <th>
                            Person Name:
                        </th>
                        <td>
                            <asp:TextBox ID="txtName" runat="server" Text=' <%#Bind("PersonName") %>' MaxLength="20" />
                            <asp:RequiredFieldValidator ID="reqName" runat="server" ControlToValidate="txtName"
                                ErrorMessage="Name is required!">*</asp:RequiredFieldValidator>
                        </td>
                    </tr>
                    <tr>
                        <th>
                            Person Image:
                        </th>
                        <td>
                            <asp:FileUpload ID="fupEditImage" runat="server" />
                            <asp:CustomValidator ID="cmvImageType" runat="server" ControlToValidate="fupEditImage"
                                ErrorMessage="File is invalid!" OnServerValidate="CustomValidator1_ServerValidate"></asp:CustomValidator>
                        </td>
                    </tr>
                    <tr>
                        <td align="center">
                            <asp:LinkButton ID="lnkUpdate" runat="server" CommandName="Update" Text="Update" />
                        </td>
                        <td align="center">
                            <asp:LinkButton ID="lnkCancel" runat="server" CommandName="Cancel" Text="Cancel"
                                CausesValidation="False" />
                        </td>
                    </tr>
                </table>
            </EditItemTemplate>
            <EditRowStyle BackColor="#738A9C" Font-Bold="True" ForeColor="White" />
            <FooterStyle BackColor="#F7DFB5" ForeColor="#8C4510" />
            <HeaderStyle BackColor="#A55129" Font-Bold="True" ForeColor="White" />
            <InsertItemTemplate>
                <table width="100%">
                    <tr>
                        <th>
                            Person Name:
                        </th>
                        <td>
                            <asp:TextBox ID="txtName" runat="server" MaxLength="20" Text='<%#Bind("PersonName") %>'></asp:TextBox>
                            <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="txtName"
                                ErrorMessage="Name is required!">*</asp:RequiredFieldValidator>
                        </td>
                    </tr>
                    <tr>
                        <th>
                            Person Image:
                        </th>
                        <td>
                            <asp:FileUpload ID="fupInsertImage" runat="server" />
                            <asp:CustomValidator ID="cmvImageType" runat="server" ControlToValidate="fupInsertImage"
                                ErrorMessage="File is invalid!" OnServerValidate="CustomValidator1_ServerValidate"></asp:CustomValidator>
                        </td>
                    </tr>
                    <tr>
                        <td align="center">
                            <asp:LinkButton ID="lnkInsert" runat="server" CommandName="Insert" Text="Insert" />
                        </td>
                        <td align="center">
                            <asp:LinkButton ID="lnkInsertCancel" runat="server" CommandName="Cancel" Text="Cancel"
                                CausesValidation="False" />
                        </td>
                    </tr>
                </table>
            </InsertItemTemplate>
            <PagerStyle HorizontalAlign="Center" ForeColor="#8C4510" />
            <RowStyle BackColor="#FFF7E7" ForeColor="#8C4510" />
        </asp:FormView>
        <asp:SqlDataSource ID="SqlDSPersonDetails" runat="server" ConnectionString="<%$ ConnectionStrings:db_PersonsConnectionString %>"
            DeleteCommand="DELETE FROM tb_personInfo WHERE (Id = @Id)" InsertCommand="INSERT INTO tb_personInfo(PersonName, PersonImage, PersonImageType) VALUES (@PersonName, @PersonImage, @PersonImageType)"
            SelectCommand="SELECT [Id], [PersonName] FROM [tb_personInfo] where id=@id" UpdateCommand="UPDATE tb_personInfo SET PersonName = @PersonName, PersonImage = @PersonImage, PersonImageType = @PersonImageType WHERE (Id = @Id)">
            <DeleteParameters>
                <asp:Parameter Name="Id" Type="Int32" />
            </DeleteParameters>
            <InsertParameters>
                <asp:Parameter Name="PersonName" Type="String" />
                <asp:Parameter Name="PersonImage" DbType="Binary" ConvertEmptyStringToNull="true" />
                <asp:Parameter Name="PersonImageType" Type="String" ConvertEmptyStringToNull="true" />
            </InsertParameters>
            <UpdateParameters>
                <asp:Parameter Name="PersonName" Type="String" />
                <asp:Parameter Name="PersonImage" DbType="Binary" ConvertEmptyStringToNull="true" />
                <asp:Parameter Name="PersonImageType" Type="String" ConvertEmptyStringToNull="true" />
                <asp:Parameter Name="Id" Type="Int32" />
            </UpdateParameters>
            <SelectParameters>
                <asp:ControlParameter Name="id" Type="Int32" ControlID="gvPersonOverView" PropertyName="SelectedValue"
                    DefaultValue="0" />
            </SelectParameters>
        </asp:SqlDataSource>
        </form>
    </body>
    </html>
    /****************************** Module Header ******************************\ * Module Name: Default.aspx.cs * Project: CSASPNETImageEditUpload * Copyright (c) Microsoft Corporation * * The project shows up how to insert,edit or update an image and store * it into Sql database. * * This source is subject to the Microsoft Public License. * See http://www.microsoft.com/opensource/licenses.mspx#Ms-PL. * All other rights reserved. \***************************************************************************/
    
    using System.Collections.Generic;
    using System.Web.UI.WebControls;
    using System;
    using System.Data.SqlClient;
    using System.IO;
    
    
    namespace CSASPNETImageEditUpload
    {
        public partial class _Default : System.Web.UI.Page
        {
            // Static types of common images for checking.
            private static List<string> imgytpes = new List<string>()
            {
                ".BMP",".GIF",".JPG",".PNG"
            };
    
    
            /// <summary>
            /// Read all records into GridView.
            /// If has records, select the first record to be shown in the FormView
            /// as default; otherwise, change the formview to insert mode so as to let
            /// data to be inserted.
            /// </summary>
            protected void Page_Load(object sender, EventArgs e)
            {
                if (!IsPostBack)
                {
                    gvPersonOverView.DataBind();
    
                    if (gvPersonOverView.Rows.Count > 0)
                    {
                        gvPersonOverView.SelectedIndex = 0;
                        fvPersonDetails.ChangeMode(FormViewMode.ReadOnly);
                        fvPersonDetails.DefaultMode = FormViewMode.ReadOnly;
                    }
                    else
                    {
                        fvPersonDetails.ChangeMode(FormViewMode.Insert);
                        fvPersonDetails.DefaultMode = FormViewMode.Insert;
                    }
                }
            }
    
    
            /// <summary>
            /// Validate whether data satisfies the type of image.
            /// </summary>
            protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args)
            {
                if (args.Value != null && args.Value != "")
                {
                    args.IsValid = imgytpes.IndexOf(System.IO.Path.GetExtension(args.Value).ToUpper()) >= 0;
                }
            }
    
    
            /// <summary>
            /// After checking the validation of the image type,
            /// assign the image type and the image byte collection through
            /// the e.Values argument and do the insert.
            /// </summary>
            protected void fvPersonDetails_ItemInserting(object sender, FormViewInsertEventArgs e)
            {
                object obj = Session["insertstate"];
    
                if (obj == null || (bool)obj)
                {
                    CustomValidator cv = fvPersonDetails.FindControl("cmvImageType") as CustomValidator;
    
                    cv.Validate();
                    e.Cancel = !cv.IsValid;
    
                    FileUpload fup = (FileUpload)fvPersonDetails.FindControl("fupInsertImage");
    
                    if (cv.IsValid && fup.PostedFile.FileName.Trim() != "")
                    {
                        e.Values["PersonImage"] = File.ReadAllBytes(fup.PostedFile.FileName);
                        e.Values["PersonImageType"] = fup.PostedFile.ContentType;
                    }
    
                }
                else
                {
                    e.Cancel = true;
                    gvPersonOverView.DataBind();
                    fvPersonDetails.ChangeMode(FormViewMode.ReadOnly);
                    fvPersonDetails.DefaultMode = FormViewMode.ReadOnly;
                }
            }
    
    
            /// <summary>
            /// After checking the validation of the image type,
            /// assign the image type and the image byte collection through
            /// the e.Values argument and do the update.
            /// </summary>
            protected void fvPersonDetails_ItemUpdating(object sender, FormViewUpdateEventArgs e)
            {
                CustomValidator cv = fvPersonDetails.FindControl("cmvImageType") as CustomValidator;
    
                cv.Validate();
                e.Cancel = !cv.IsValid;
    
                FileUpload fup = (FileUpload)fvPersonDetails.FindControl("fupEditImage");
    
                if (cv.IsValid && fup.PostedFile.FileName.Trim() != "")
                {
                    e.NewValues["PersonImage"] = File.ReadAllBytes(fup.PostedFile.FileName);
                    e.NewValues["PersonImageType"] = fup.PostedFile.ContentType;
                }
            }
    
    
            /// <summary>
            /// After updated, re-databind data and select the first one as default.
            /// </summary>
            protected void fvPersonDetails_ItemUpdated(object sender, FormViewUpdatedEventArgs e)
            {
                gvPersonOverView.DataBind();
                gvPersonOverView.SelectedIndex = gvPersonOverView.SelectedRow.RowIndex;
            }
    
    
            /// <summary>
            /// After inserted successfully, re-databind data,select the first one as default,
            /// Change the FormView mode to ReadOnly (for viewing).
            /// </summary>
            protected void fvPersonDetails_ItemInserted(object sender, FormViewInsertedEventArgs e)
            {
                gvPersonOverView.DataBind();
                gvPersonOverView.SelectedIndex = gvPersonOverView.Rows.Count - 1;
                fvPersonDetails.ChangeMode(FormViewMode.ReadOnly);
                fvPersonDetails.DefaultMode = FormViewMode.ReadOnly;
            }
    
    
            /// <summary>
            /// After deleted successfully, re-databind data.
            /// </summary>
            protected void fvPersonDetails_ItemDeleted(object sender, FormViewDeletedEventArgs e)
            {
                gvPersonOverView.DataBind();
    
                // If still has records
                if (gvPersonOverView.Rows.Count > 0)
                {
                    // Take out the index of row to be deleted
                    int delindex = (int)ViewState["delindex"];
    
                    // If the first record is deleted,Move to its next record.
                    if (delindex == 0)
                    {
                        gvPersonOverView.SelectedIndex = 0;
                    }
    
                    // If the last record is deleted, Move to its previous one.
                    else if (delindex == gvPersonOverView.Rows.Count)
                    {
                        gvPersonOverView.SelectedIndex = gvPersonOverView.Rows.Count - 1;
                    }
    
                    // Otherwise, move to the next record after itself is deleted.
                    else
                    {
                        gvPersonOverView.SelectedIndex = delindex;
                    }
    
                }
    
                // If has no records, change to insert mode for insering new records.
                else
                {
                    fvPersonDetails.ChangeMode(FormViewMode.Insert);
                    fvPersonDetails.DefaultMode = FormViewMode.Insert;
                }
            }
    
    
            /// <summary>
            /// To show detail image and information in the FormView when GridView's
            /// SelectedRowIndex Changed.
            /// </summary>
            protected void gvPersonOverView_SelectedIndexChanged(object sender, EventArgs e)
            {
                fvPersonDetails.ChangeMode(FormViewMode.ReadOnly);
                fvPersonDetails.DefaultMode = FormViewMode.ReadOnly;
            }
    
    
            /// <summary>
            /// Keep the row index into ViewState for the usage of Item_Deleted.
            /// </summary>
            protected void fvPersonDetails_ItemDeleting(object sender, FormViewDeleteEventArgs e)
            {
                ViewState["delindex"] = gvPersonOverView.SelectedIndex;
            }
    
    
            /// <summary>
            /// Keep the insertState into Session to avoid the duplicated inserting
            /// after refreshing page.
            /// </summary>
            protected void fvPersonDetails_ModeChanging(object sender, FormViewModeEventArgs e)
            {
                Session["insertstate"] = (e.NewMode == FormViewMode.Insert);
    
            }
        }
    }
    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, February 8, 2012 8:16 PM