0

I have been created student details using asp.net and c#.

I added image field recently, when i edit the details, and edit some of the fields without image filed(edit if necessary), and submit..It shows "please upload your image" in alert.

So i need to check if image is empty in images folder and also in file upload.

Here is my code:

code-behind:

protected void btnsub_Click(object sender, EventArgs e)
        {
            SqlConnection con = Connection.DBconnection();
            if (Textid.Text.Trim().Length > 0)
            {
                SqlCommand com = new SqlCommand("StoredProcedure3", con);
                com.CommandType = CommandType.StoredProcedure;
                com.Parameters.AddWithValue("@id", Textid.Text.Trim());
                com.Parameters.AddWithValue("@Name", Textusername.Text.Trim());
                com.Parameters.AddWithValue("@Class", Textclass.Text.Trim());
                com.Parameters.AddWithValue("@Section", Textsection.Text.Trim());
                com.Parameters.AddWithValue("@Address", Textaddress.Text.Trim());
                try
                {
                    string filename = string.Empty;
                    if (fileupload.PostedFile.FileName.Length > 0)
                    {
                        filename = Path.GetFileName(fileupload.PostedFile.FileName);
                        fileupload.SaveAs(Server.MapPath("~/Images/" + filename));
                    }
                    com.Parameters.AddWithValue("@Image",(filename.Length>0)? "Images/" + filename:string.Empty);
                    com.ExecuteNonQuery();                    
                }
                catch (Exception ex)
                {
                    btnsub.Text = ex.Message;
                }
                Response.Redirect("studententry.aspx");
            }
            else
            {
                SqlCommand com = new SqlCommand("StoredProcedure1", con);
                com.CommandType = CommandType.StoredProcedure;
                com.Parameters.AddWithValue("@Name", Textusername.Text.Trim());
                com.Parameters.AddWithValue("@Class", Textclass.Text.Trim());
                com.Parameters.AddWithValue("@Section", Textsection.Text.Trim());
                com.Parameters.AddWithValue("@Address", Textaddress.Text.Trim());
                try
                {
                    string filename = string.Empty;
                    if (fileupload.PostedFile.FileName.Length > 1)
                    {
                        filename = Path.GetFileName(fileupload.PostedFile.FileName);
                        fileupload.SaveAs(Server.MapPath("~/Images/" + filename));
                    }
                    com.Parameters.AddWithValue("@Image",(filename.Length>0)? "Images/" + filename:string.Empty);
                    com.ExecuteNonQuery();                    
                }
                catch (Exception ex)
                {
                    btnsub.Text = ex.Message;
                }
                Response.Redirect("studententry.aspx");
            }
        }
        protected void btnrst_Click(object sender, EventArgs e)
        {
            Textid.Text = string.Empty;
            Textusername.Text = string.Empty;
            Textclass.Text = string.Empty;
            Textsection.Text = string.Empty;
            Textaddress.Text = string.Empty;
        }
        protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            SqlConnection con = Connection.DBconnection();

            if (e.CommandName == "EditRow")
            {

                GridViewRow gr = (GridViewRow)((Button)e.CommandSource).NamingContainer;
                int index = gr.RowIndex; 
                hiddenfield.Value = index.ToString(); 
                Textid.Text = gr.Cells[0].Text;
                Textusername.Text = gr.Cells[1].Text;
                Textclass.Text = gr.Cells[2].Text;
                Textsection.Text = gr.Cells[3].Text;
                Textaddress.Text = gr.Cells[4].Text;
                Image1.ImageUrl = ((System.Web.UI.WebControls.Image)gr.Cells[5].Controls[0]).ImageUrl;               
            }
            else if (e.CommandName == "Deleterow")
            {
                SqlCommand com = new SqlCommand("StoredProcedure4", con);
                com.CommandType = CommandType.StoredProcedure;
                com.Parameters.AddWithValue("@ID", Convert.ToInt32(e.CommandArgument));
                var id = Int32.Parse(e.CommandArgument.ToString());                
                com.ExecuteNonQuery();
                Response.Redirect("studententry.aspx");
            }
        }
        protected void GridView1_SelectedIndexChanged(Object sender, EventArgs e)
        {
            int index = GridView1.SelectedIndex;
            hiddenfield.Value = index.ToString();
        }

aspx:

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">

    <center><div><h4>Student Registration</h4></div></center>
<div class="tblalign">
    <table style="width: 100%;">
    <tr>
    <td><asp:HiddenField ID="hiddenfield" runat="server" /> 
    <asp:TextBox ID="Textid" runat="server" Visible="false"></asp:TextBox>
    </td>

    </tr>
        <tr>
            <td>
                <asp:Label ID="Label1" runat="server" Text="Name"></asp:Label>

            </td>
            <td>
                &nbsp;
            </td>
            <td>
                <asp:TextBox ID="Textusername" runat="server"></asp:TextBox>

            </td>
        </tr>
        <tr>
            <td>
                <asp:Label ID="Label2" runat="server" Text="Class"></asp:Label>

            </td>
            <td>
                &nbsp;
            </td>
            <td>
                <asp:TextBox ID="Textclass" runat="server"></asp:TextBox>

            </td>
        </tr>
        <tr>
            <td>
                <asp:Label ID="Label3" runat="server" Text="Section"></asp:Label>

            </td>
            <td>
                &nbsp;
            </td>
            <td>
                <asp:TextBox ID="Textsection" runat="server"></asp:TextBox>
            </td>
        </tr>
        <tr>
        <td>
            <asp:Label ID="Label5" runat="server" Text="Address"></asp:Label>
        </td>

        <td>
            &nbsp;
        </td>
        <td>
            <asp:TextBox ID="Textaddress" runat="server"></asp:TextBox>
        </td>
        </tr>
        <tr>
            <td>
            <asp:Label ID="Label4" runat="server" Text="Image"></asp:Label>
            </td>
            <td>
            &nbsp;
        </td>
        <td>
            <asp:Image ID="Image1" runat="server" ControlStyle-Width="50" ControlStyle-Height = "50"  />

        </td>
        <td>
        <asp:FileUpload ID="fileupload" runat="server" />  
         </td>
        </tr>
        <tr>
        <td>
            <asp:Button ID="btnsub" runat="server" Text="Submit" OnClick="btnsub_Click" OnClientClick="return register();" />
            <asp:Button ID="btnrst" runat="server" Text="Reset" OnClick="btnrst_Click" />
        </td>
        <td>
        </td>            
        <td>            
        </td>
    </tr>

</table></div>
<br />
<br />
<center><div><h4>Student Records</h4></div></center><br /> <br />
    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" 
        DataKeyNames="ID" DataSourceID="SqlDataSource1" 
        OnRowCommand="GridView1_RowCommand" 
        EnablePersistedSelection="True" BackColor="White" 
        OnSelectedIndexChanged="GridView1_SelectedIndexChanged">
        <Columns>
            <asp:BoundField DataField="ID" HeaderText="ID" InsertVisible="False" 
                ReadOnly="True" SortExpression="ID" />
            <asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" />
            <asp:BoundField DataField="Class" HeaderText="Class" SortExpression="Class" />
            <asp:BoundField DataField="Section" HeaderText="Section" 
                SortExpression="Section" />
            <asp:BoundField DataField="Address" HeaderText="Address" 
                SortExpression="Address" />
                <asp:ImageField DataImageUrlField="Image" HeaderText="Image" ControlStyle-Width="50" ControlStyle-Height = "50">                
                </asp:ImageField> 
            <asp:TemplateField HeaderText="Edit">
               <ItemTemplate>
                 <asp:Button runat="server" ID="btnedit" Text="Edit" CommandName="EditRow"></asp:Button>                    
               </ItemTemplate>
                <ControlStyle BorderColor="#CCFF66" />
          </asp:TemplateField>
          <asp:TemplateField HeaderText="Delete">
          <ItemTemplate>
                 <asp:Button runat="server" ID="btndelete" Text="Delete" CommandArgument='<%# Eval("Id") %>' CommandName="Deleterow"></asp:Button>                    
               </ItemTemplate>
          </asp:TemplateField>            
        </Columns>
        <SelectedRowStyle BackColor="#FF66FF" />
    </asp:GridView>
        <asp:SqlDataSource ID="SqlDataSource1" runat="server" 
        ConnectionString="<%$ ConnectionStrings:ConnectionString %>" 
        SelectCommand="StoredProcedure2"          
        SelectCommandType="StoredProcedure">
            <DeleteParameters>
                <asp:Parameter Name="ID" />
                <asp:Parameter Name="Name" />
                <asp:Parameter Name="Class" />
                <asp:Parameter Name="Section" />
                <asp:Parameter Name="Image" />
            </DeleteParameters>
            <UpdateParameters>
                <asp:Parameter Name="ID" />
                <asp:Parameter Name="Name" />
                <asp:Parameter Name="Class" />
                <asp:Parameter Name="Section" />
                <asp:Parameter Name="Image" />
            </UpdateParameters>
    </asp:SqlDataSource>
</asp:Content>

OUTPUT

I think in editrow command, i need to check the condition. Actually i'm new to .net.

So can anyone help me to fix this problem.

Any help would be highly appreciated.

Thanks,

pcs
  • 1,864
  • 4
  • 25
  • 49
  • 1
    Possible duplicate of [How to check if a file exists in a folder?](http://stackoverflow.com/questions/7385251/how-to-check-if-a-file-exists-in-a-folder) – Atish Kumar Dipongkor Nov 16 '15 at 06:27
  • Also possible dupliate of [How to check if a specific file exists in directory or any of its subdirectories](http://stackoverflow.com/a/3994498/242) – Dhaust Nov 16 '15 at 06:46
  • Don't save the image on the hard drive. Instead save them as binary files in the sql server and then you can just check if the nullable ImageId has value or not when posted back, if not then read the posted image if there is one and save. – Janne Matikainen Nov 16 '15 at 06:51
  • @JanneMatikainen: I saved images in both sql server database as binary and also saved in the hard drive(I need). thanks – pcs Nov 16 '15 at 06:55

2 Answers2

1

To check for specific files use File.Exists(path), which will return a boolean value indicating whether the file at path exists.

System.IO.File.Exists(path)

As your code is synchronous, it is possible to check whether the image is loaded immediately after uploading an image to the folder. For example:

try
  {
     string filename = string.Empty;
     if (fileupload.PostedFile.FileName.Length > 0)
        {
           filename = Path.GetFileName(fileupload.PostedFile.FileName);
           fileupload.SaveAs(Server.MapPath("~/Images/" + filename));
        }     
     string imgAddress = Path.GetFileName(fileupload.PostedFile.FileName);   
     //check whether your image is created:
     bool isExist=System.IO.File.Exists(imgAddress);
     com.Parameters.AddWithValue("@Image",(filename.Length>0)? "Images/" + filename:string.Empty);
     com.ExecuteNonQuery();                    
  }
catch (Exception ex)
{
   btnsub.Text = ex.Message;
}
StepUp
  • 36,391
  • 15
  • 88
  • 148
  • thanks for your answer, may i know, where i can check in my code? – pcs Nov 16 '15 at 06:29
  • If i edit the details, and only editing text and click submit, it shows upload your image in alert. – pcs Nov 16 '15 at 06:46
  • may i know, where i can your code in my file? thanks – pcs Nov 16 '15 at 06:49
  • is it an exception 'Upload your image'? set breakpoint at the row bool isExist and see isExist equals true or false – StepUp Nov 16 '15 at 06:57
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/95211/discussion-between-stepup-and-rani). – StepUp Nov 16 '15 at 07:01
  • go to chat http://chat.stackoverflow.com/rooms/95211/discussion-between-stepup-and-rani – StepUp Nov 16 '15 at 07:01
0
filename = Path.GetFileName(fileupload.PostedFile.FileName);
var fullPath="~/Images/" + filename;


if (System.IO.File.Exists(Server.MapPath(fullPath)))
{
    // file exist
}
else
{
   // file not exist
}
Parminder
  • 1
  • 1