We help IT Professionals succeed at work.

GRIDVIEW UPLOAD

BOEING39
BOEING39 asked
on
463 Views
Last Modified: 2012-02-23
I have attached the code behind for 'GRIDVIEW UPLOAD".   This code works fine for "JPEG" files only.   Need assistance with code to upload the following extensions:   .xlsx, .doc and .pdf formats......


using System;
using System.IO;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
  protected void Button1_Click(object sender, EventArgs e)
  {
    Label1.Visible = true;
    if (FileUpload1.HasFile)
      if (System.IO.Path.GetExtension(FileUpload1.FileName).ToLower() == ".jpg")
    {
      SqlConnection conn =
        new SqlConnection(SqlDataSource1.ConnectionString);
      SqlCommand cmd =
        new SqlCommand
          ("INSERT INTO tblUploads (Filename) VALUES (@Filename); " +
           "SELECT @FileID = SCOPE_IDENTITY();",
           conn);
      cmd.Parameters.Add
        ("@Filename", SqlDbType.NVarChar, 50).Value = FileUpload1.FileName;
      cmd.Parameters.Add("@FileID", SqlDbType.Int, 4);
      cmd.Parameters["@FileID"].Direction = ParameterDirection.Output;
      conn.Open();
      cmd.ExecuteNonQuery();
      FileUpload1.SaveAs
        (Server.MapPath("~/Uploads/" + cmd.Parameters["@FileID"].Value.ToString()
          + ".jpg"));
      GridView1.DataBind();
      Label1.Visible = false;
    }
  }
  protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
  {
    GridViewRow row = GridView1.SelectedRow;
    Image1.ImageUrl = "~/uploads/" + row.Cells[1].Text + ".jpg";
    Image1.AlternateText = "Original filename: " + row.Cells[2].Text;
  }
}
Comment
Watch Question

Navneet.Net Full Stack Developer

Commented:
Hi!

What's the issue you are facing?

Author

Commented:
I need to know how to setup the extensions in the behind code to upload extensions other than "JPEG"
Kamal KhaleefaInformation Security Specialist

Commented:
hi
just change this code
if (System.IO.Path.GetExtension(FileUpload1.FileName).ToLower() == ".jpg")

to sth like this

if (System.IO.Path.GetExtension(FileUpload1.FileName).ToLower() == ".jpg" or System.IO.Path.GetExtension(FileUpload1.FileName).ToLower() == ".xlxs" .....)

just add or to check other extensions

Author

Commented:
This code doesn't work...  Get assignment call error...  Also code behind has two other references to "JPG"    one under "value to string" the other under"image url"


    if (System.IO.Path.GetExtension(FileUpload1.FileName).ToLower() == ".jpg")

    {
      SqlConnection conn =
        new SqlConnection(SqlDataSource1.ConnectionString);
      SqlCommand cmd =
        new SqlCommand
          ("INSERT INTO tblUploads (Filename) VALUES (@Filename); " +
           "SELECT @FileID = SCOPE_IDENTITY();",
           conn);
      cmd.Parameters.Add
        ("@Filename", SqlDbType.NVarChar, 50).Value = FileUpload1.FileName;
      cmd.Parameters.Add("@FileID", SqlDbType.Int, 4);
      cmd.Parameters["@FileID"].Direction = ParameterDirection.Output;
      conn.Open();
      cmd.ExecuteNonQuery();
      FileUpload1.SaveAs
        (Server.MapPath("~/Uploads/" + cmd.Parameters["@FileID"].Value.ToString()
          + ".jpg"));
  GridView1.DataBind();
      Label1.Visible = false;
    }
  }
  protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
  {
    GridViewRow row = GridView1.SelectedRow;
    Image1.ImageUrl = "~/uploads/" + row.Cells[1].Text + ".jpg";
    Image1.AlternateText = "Original filename: " + row.Cells[2].Text;
  }
}

Commented:
Something like this may get you where you want to go:

    //added method CheckExt to check file types specified
    if (CheckExt(System.IO.Path.GetExtension(FileUpload1.FileName)))
    {
      SqlConnection conn = new SqlConnection(SqlDataSource1.ConnectionString);
      SqlCommand cmd = new SqlCommand("INSERT INTO tblUploads (Filename) VALUES (@Filename); " + "SELECT @FileID = SCOPE_IDENTITY();", conn);
      cmd.Parameters.Add("@Filename", SqlDbType.NVarChar, 50).Value = FileUpload1.FileName;
      cmd.Parameters.Add("@FileID", SqlDbType.Int, 4);
      cmd.Parameters["@FileID"].Direction = ParameterDirection.Output;
      conn.Open();
      cmd.ExecuteNonQuery();
      //changed to use current file extention, you also could have potentially saved the ext in the db table as an option
      FileUpload1.SaveAs(Server.MapPath("~/Uploads/" + cmd.Parameters["@FileID"].Value.ToString() + System.IO.Path.GetExtension(FileUpload1.FileName)));
      GridView1.DataBind();
      Label1.Visible = false;
    }


  protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
  {
    //Not knowing what is in the rows/cells I think I can still make an educated guess
    GridViewRow row = GridView1.SelectedRow;
    Image1.ImageUrl = "~/uploads/" + row.Cells[1].Text + System.IO.Path.GetExtension(row.Cells[2].Text);
    Image1.AlternateText = "Original filename: " + row.Cells[2].Text;
  }


  /// <summary>
  /// Checks file extension for allowed file types
  /// </summary>
  /// <param name="ext"></param>
  /// <returns>true if file extension allowed, else false</returns>
  private bool CheckExt(string ext)
  {
      bool rValue = false;
      if (ext.ToLower() == ".pdf") return true;
      if (ext.ToLower() == ".jpg") return true;
      if (ext.ToLower() == ".xlsx") return true;
      if (ext.ToLower() == ".doc") return true;
      return rValue;
  }

PS: I posted a response on your other question. Better late than never.

Author

Commented:
The adjustments work great.     However, the default page is set to hold images ie "JPEG".
Doesn't display other extensions properly (Shows Box X'd out).   I am using imageID container or frame to the right of the gridview to show the document when I execute "View".  JPEG file shows fine.    Any suggestions on this?   I have attached the files again for your review.  Again I can't tell you how much I appreciate you working with me on this...  I was thinking maybe an iframe display to the right may work well????

<asp:Image ID="Image1" runat="server" style="float:right;"/>

I want to get this one worked out prior to moving on to your Christmas code...:)
Default.aspx
Default.aspx.cs
Uploads.mdf

Commented:
I'm not ignoring this but I will have to take this to another machine to look at it, as this one is older and doesn't have the resources to look more fully into the matter. I'll try to setup your .mdf there and see if I can more fully understand your issue.

At 1st glance it seems you just need 4 "placeholder" images. One for each type of image. You need to place that image inside an anchor with an href pointing to the actual image in the upload folder so when it is clicked on it opens the file (whatever type it is).

This is not tested but it should be close. I'll take a stronger look when I can get your .mdb in place:

<asp:HyperLink ID="Hyp1" runat=server style="float:right;"><asp:Image ID="Image1" runat="server" /></asp:HyperLink>

 protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
  {
    GridViewRow row = GridView1.SelectedRow;
    //make an images folder and put the Placeholder files there
    //The image just shows the "type" of image
    //Image1.ImageUrl = "~/uploads/" + row.Cells[1].Text + System.IO.Path.GetExtension(row.Cells[2].Text);
    Image1.ImageUrl = "~/img/" + DetermineImageToUse(System.IO.Path.GetExtension(row.Cells[2].Text));
    Image1.AlternateText = "Original filename: " + row.Cells[2].Text;
    //set the hyperlink around the image to point to the file you want displayed
    Hyp1.NavigateUrl = "~/uploads/" + row.Cells[1].Text + System.IO.Path.GetExtension(row.Cells[2].Text);
  }

  private string DetermineImageToUse(string ext)
  {
      bool rValue = string.Empty;
      if (ext.ToLower() == ".pdf") return "pdfFile.jpg";
      if (ext.ToLower() == ".jpg") return "jpgFile.jpg";
      if (ext.ToLower() == ".xlsx") return "xlsFile.jpg";
      if (ext.ToLower() == ".doc") return "docFile.jpg";
      return rValue;
  }

Author

Commented:
Ok thx....

Author

Commented:
I plugged in the code and added ckExt method.   Throwing error line 61 and 66.  
Cannot implicitly convert "bool" to "string".


using System;
using System.IO;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        Label1.Visible = true;
        if (FileUpload1.HasFile)

            //added method CheckExt to check file types specified
            if (CheckExt(System.IO.Path.GetExtension(FileUpload1.FileName)))
            {
                SqlConnection conn = new SqlConnection(SqlDataSource1.ConnectionString);
                SqlCommand cmd = new SqlCommand("INSERT INTO tblUploads (Filename) VALUES (@Filename); " + "SELECT @FileID = SCOPE_IDENTITY();", conn);
                cmd.Parameters.Add("@Filename", SqlDbType.NVarChar, 50).Value = FileUpload1.FileName;
                cmd.Parameters.Add("@FileID", SqlDbType.Int, 4);
                cmd.Parameters["@FileID"].Direction = ParameterDirection.Output;
                conn.Open();
                cmd.ExecuteNonQuery();
                //changed to use current file extention, you also could have potentially saved the ext in the db table as an option
                FileUpload1.SaveAs(Server.MapPath("~/Uploads/" + cmd.Parameters["@FileID"].Value.ToString() + System.IO.Path.GetExtension(FileUpload1.FileName)));
                GridView1.DataBind();
                Label1.Visible = false;
            }
    }

    private bool CheckExt(string p)
    {
        throw new NotImplementedException();
    }


    protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
    {
        GridViewRow row = GridView1.SelectedRow;
        //make an images folder and put the Placeholder files there
        //The image just shows the "type" of image
        //Image1.ImageUrl = "~/uploads/" + row.Cells[1].Text + System.IO.Path.GetExtension(row.Cells[2].Text);
        Image1.ImageUrl = "~/img/" + DetermineImageToUse(System.IO.Path.GetExtension(row.Cells[2].Text));
        Image1.AlternateText = "Original filename: " + row.Cells[2].Text;
        //set the hyperlink around the image to point to the file you want displayed
        Hyp1.NavigateUrl = "~/uploads/" + row.Cells[1].Text + System.IO.Path.GetExtension(row.Cells[2].Text);
    }

    private string DetermineImageToUse(string ext)
    {
        bool rValue = string.Empty;
        if (ext.ToLower() == ".pdf") return "pdfFile.jpg";
        if (ext.ToLower() == ".jpg") return "jpgFile.jpg";
        if (ext.ToLower() == ".xlsx") return "xlsFile.jpg";
        if (ext.ToLower() == ".doc") return "docFile.jpg";
        return rValue;
    }
 

}
Default.aspx
Default.aspx.cs

Commented:
That's because I didn't test it. I just wrote it on the fly here. Change this:

 private string DetermineImageToUse(string ext)
    {
        string rValue = string.Empty;
Commented:
This one is on us!
(Get your first solution completely free - no credit card required)
UNLOCK SOLUTION

Author

Commented:
Ok changed code accordingly.   I added 4 additional fields to data base and modified my gridvew..  Can you assist with the C# code for the 4 items added  with regard to entering into the data base when the upload button is clicked?    The fields below are as they appear in the data base and with their respective input box.

"Ship"      Ship number
"Dates"    Date picker
"Sta"        Station
"Desc1"  Upload description

Lastly when view the gridview virtually it diplays correctly and it does upload the added file extensions with the view to the right.   It does however, require an additional click on the place holder on the right after "View is clic
ked.

I have attached a screen shot of this for you.
Uploads.mdf
Default.aspx
Default.aspx.cs

Author

Commented:
Attached screen shot of display........
Screen-shot-before-clicking-view.doc

Author

Commented:
Getting the following error line 38with the attached code behind.  

Object must implement IConvertible.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.InvalidCastException: Object must implement IConvertible.

Source Error:


Line 36:                 cmd.Parameters["@FileID"].Direction = ParameterDirection.Output;
Line 37:                 conn.Open();
Line 38:                 cmd.ExecuteNonQuery();
Line 39:                 //changed to use current file extention, you also could have potentially saved the ext in the db table as an option
Line 40:                 FileUpload1.SaveAs(Server.MapPath("~/Uploads/" + cmd.Parameters["@FileID"].Value.ToString() + System.IO.Path.GetExtension(FileUpload1.FileName)));
Default.aspx.cs

Author

Commented:
Corrected some additional code and it is functioning properly in local host.   However, have another issue now directed at other question currently open.

Thx for the help.
Unlock the solution to this question.
Join our community and discover your potential

Experts Exchange is the only place where you can interact directly with leading experts in the technology field. Become a member today and access the collective knowledge of thousands of technology experts.

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.