Solved

C# - ASP.Net: Uploading File Path to Database, Error Returned on Gridview Data bind

Posted on 2008-10-11
3
2,966 Views
Last Modified: 2013-12-17
Hello,
I am brand new to development of any kind so please forgive me if this is a bit arduous.  I will put in code samples at the end.

Thanks,
AJ

Technologies:
C#, ASP.Net 2.0, SQL Server 2005

What I am doing (or trying to do):
Create a web page where a client can see a list of files, click on one and download it.  I am using the gridview control to display this info.  Currently it is display only...I haven't yet figured out how to make the file name a link that, in turn downloads the file.

There is also a file upload page where they can browse their computer, select a file and upload it.

I am using the FileUploader control to upload the file to a folder and return the file path (with other info) to the database table.

Problems:

1. The file uploads correctly into my folder and the file path (and additional info) is successfully inserted into my database.  The problem, however, comes in when I try to view the files on the screen with my gridview.  When I just had text for my file name, it worked.  If I have the file path, it breaks and throws this exception:

InnerException      {"Failed to enable constraints. One or more rows contain values violating non-null, unique, or foreign-key constraints."}      System.Exception {System.Data.ConstraintException}

I have checked my database tables several times and I don't think I am doing any such things.  My table essentially is:

ID     int  PK not null,
FileName    nvarchar(1000) not null,
Description nvarchar(255) null,
Upload Date datetime not null

My first thought was that my datatype was incorrect in the database but the table accepts the path in the FileName column just fine...the problem is in the gridview.  Since I am brand new, I don't have any templating or custom code on the gridview and I thought it would just display whatever I was returning from that column.

The above is my main problem but I will throw in a couple more questions while I am at it.

The otherhalf of this is to make the file name a link that, when clicked on, downloads the file to the users computer.  I want this to be a save as box, not open the file in the browser since a lot of these files will be non-traditional file extensions.  The two things I am currently stuck on are:

1. How to make the FileName column display only the name and extension of the file instead of the whole path (example: Test.doc instead of C:\importantinfo\Test.doc)

2. How to make the FileName column a link that downloads the file.

If anyone has any helpful pointers on these two issues as well, I would be really grateful.

***Page Source:***
 

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="ViewClientFilesbyDateRange.aspx.cs" Inherits="FileTransfer2.ViewClientFilesbyDateRange" %>
 

<!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>ViewFiles</title>

</head>

<body style="padding-right: 10px; padding-left: 10px; padding-bottom: 10px; padding-top: 10px; background-color: #eff3fb">

    <form id="form1" runat="server">

    <div style="padding-right: 10px; padding-left: 10px; padding-bottom: 10px; padding-top: 10px; background-color: #eff3fb">

        <asp:label id="lblSearchHeader" runat="server" font-bold="True" font-names="Calibri"

            font-size="Medium" text="Search Records by Date Range"></asp:label><br />

        <asp:textbox id="txtStartDate" runat="server" font-names="Calibri" font-size="Small"

            forecolor="Black">

        </asp:textbox>&nbsp;

        <asp:textbox id="txtEndDate" runat="server" font-names="Calibri" font-size="Small"

            forecolor="Black">

        </asp:textbox>

        &nbsp;&nbsp;

        <asp:button id="btnSubmitDates" runat="server" font-bold="True" font-names="Calibri"

            onclick="btnSubmitDates_Click" text="Submit" /><br />

        <asp:label id="lblEnterDates" runat="server" font-bold="True" font-names="Calibri"

            font-size="Small" text="Enter Start and End Dates (mm/dd/yyyy):"></asp:label><br />

        <asp:regularexpressionvalidator id="valStartDate" runat="server" controltovalidate="txtStartDate"

            display="Dynamic" errormessage="Start Date Formatted Incorrectly (mm/dd/yyyy)"

            validationexpression="\d{2}/\d{2}/\d{4}" font-names="Calibri" font-size="Smaller">

        </asp:regularexpressionvalidator>

        <br />

        <asp:regularexpressionvalidator id="valEndDate" runat="server" controltovalidate="txtEndDate"

            errormessage="End Date Formatted Incorrectly (mm/dd/yyyy)" validationexpression="\d{2}/\d{2}/\d{4}" font-names="Calibri" font-size="Smaller">

        </asp:regularexpressionvalidator><br />

        <br />

        <asp:gridview id="GridView1" runat="server" allowpaging="True" allowsorting="True"

            autogeneratecolumns="False" cellpadding="4" datasourceid="ObjectDataSource1"

            forecolor="#333333" gridlines="None" height="241px" style="font-size: smaller;

            font-family: Calibri, Arial" width="713px">

            <footerstyle backcolor="#507CD1" font-bold="True" forecolor="White" />

            <rowstyle backcolor="#EFF3FB" horizontalalign="Center" />

            <columns>

<asp:BoundField DataField="File Name" HeaderText="File Name" SortExpression="File Name"></asp:BoundField>

<asp:BoundField DataField="Description" HeaderText="Description" SortExpression="Description"></asp:BoundField>

<asp:BoundField DataField="ClientFile" HeaderText="ClientFile" SortExpression="ClientFile"></asp:BoundField>

<asp:BoundField DataField="Upload Date" HeaderText="Upload Date" SortExpression="Upload Date"></asp:BoundField>

<asp:CheckBoxField DataField="eSign" HeaderText="eSign" SortExpression="eSign"></asp:CheckBoxField>

</columns>

            <pagerstyle backcolor="#2461BF" forecolor="White" horizontalalign="Center" />

            <selectedrowstyle backcolor="#D1DDF1" font-bold="True" forecolor="#333333" />

            <headerstyle backcolor="#507CD1" font-bold="True" font-size="Medium" forecolor="White"

                horizontalalign="Center" />

            <editrowstyle backcolor="#2461BF" horizontalalign="Center" />

            <alternatingrowstyle backcolor="White" />

        </asp:gridview></div>

        <asp:objectdatasource id="ObjectDataSource1" runat="server" oldvaluesparameterformatstring="original_{0}"

            selectmethod="GetFilesbyClientDateRange" typename="FileTransfer2.DataSets.ClientFilesbyDateRangeTableAdapters.getFilesbyClientDateRangeTableAdapter">

            <selectparameters>

<asp:Parameter DefaultValue="" Name="startDate" Type="DateTime"></asp:Parameter>

<asp:Parameter DefaultValue="" Name="endDate" Type="DateTime"></asp:Parameter>

<asp:Parameter Name="UserName" Type="String"></asp:Parameter>

</selectparameters>

        </asp:objectdatasource><br />

        <asp:button id="btnUploadFile" runat="server" font-bold="True" font-names="Calibri"

            onclick="btnUploadFile_Click" text="Upload New File" /><br />

        <br />

        <br />

    </form>

</body>

</html>
 
 

***CODE BEHIND***
 

using System;

using System.Data;

using System.Configuration;

using System.Collections;

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;
 

namespace FileTransfer2

{

    public partial class ViewClientFilesbyDateRange : System.Web.UI.Page

    {

        protected void Page_Load(object sender, EventArgs e)

        {

            ObjectDataSource1.SelectParameters["UserName"].DefaultValue = this.User.Identity.Name;

            ObjectDataSource1.SelectParameters["startDate"].ConvertEmptyStringToNull = true;

            ObjectDataSource1.SelectParameters["endDate"].ConvertEmptyStringToNull = true;
 

            if (!Page.IsPostBack)

            {

                ObjectDataSource1.SelectParameters["startDate"].DefaultValue = string.Empty;

                ObjectDataSource1.SelectParameters["endDate"].DefaultValue = string.Empty;

                GridView1.DataBind(); //This is where my exception is generated

            }
 

        }
 

        protected void btnSubmitDates_Click(object sender, EventArgs e)

        {

            ObjectDataSource1.SelectParameters["startDate"].DefaultValue = this.txtStartDate.Text.Trim();

            ObjectDataSource1.SelectParameters["endDate"].DefaultValue = this.txtEndDate.Text.Trim();

            GridView1.DataBind();

        }
 

        protected void btnUploadFile_Click(object sender, EventArgs e)

        {

            Response.Redirect("FileUpload.aspx");

        }

    }

}
 
 

***File Upload code in case it is needed***
 

SOURCE CODE:
 

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="FileUpload.aspx.cs" Inherits="FileTransfer2.FileUpload" %>
 

<!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>Untitled Page</title>

</head>

<body>

    <form id="form1" runat="server">

    <div style="padding-right: 10px; padding-left: 10px; padding-bottom: 10px; padding-top: 10px; font-family: Calibri, Arial; background-color: #eff3fb">

        <asp:sqldatasource id="SqlDataSource1" runat="server" connectionstring="<%$ ConnectionStrings:FileTransferConnectionStringFileUpload %>"

            selectcommand="SELECT [ID], [FileName], [Description], [ClientFile], [UploadDate], [eSign] FROM [ClientFiles]">

        </asp:sqldatasource><br />

        <asp:linkbutton id="lbtnReturntoHome" runat="server" font-size="Smaller" onclick="lbtnReturntoHome_Click" font-names="Calibri">Return to Home Page</asp:linkbutton><br />

        <br />

        <asp:label id="Label1" runat="server" font-bold="True" font-size="X-Large" text="Select and Upload File">

        </asp:label><br />

        <br />

        &nbsp;<asp:fileupload id="FileUpload1" runat="server" font-names="Calibri"></asp:fileupload><br />

        <asp:label id="lblError" runat="server" font-bold="True" font-names="Calibri" font-size="Smaller"

            forecolor="Red" height="21px" width="291px"></asp:label><br />

        <asp:label id="lblDescription" runat="server" text="Description:" font-bold="True" font-size="Small"></asp:label><br />

        &nbsp;<asp:textbox id="txtDescription" runat="server" font-names="Calibri" height="97px" maxlength="255" rows="5" textmode="MultiLine" width="280px"></asp:textbox>

        <br />

        <asp:label id="Label2" runat="server" font-names="Calibri" font-size="Small" text="(Description max 255 characters.)">

        </asp:label><br />

        <br />

        <asp:button id="btnSubmit" runat="server" onclick="btnSubmit_Click" text="Submit" font-names="Calibri" font-overline="False" font-size="Medium" />

        <br />

        <br />

        <asp:label id="lblResults" runat="server" height="21px" width="291px" font-names="Calibri" font-size="Small" forecolor="DarkGreen"></asp:label><br />

        <br />

        <br />

        <br />

        <br />

        <br />

        <br />

        <br />

        <br />

        <br />

        <br />

        <br />

        <br />

    </div>

    </form>

</body>

</html>
 
 

CODE BEHIND:
 

using System;

using System.Data;

using System.Configuration;

using System.Collections;

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;

using System.Data.SqlClient;  
 
 

namespace FileTransfer2

{

    

    public partial class FileUpload : System.Web.UI.Page

    {

        protected void Page_Load(object sender, EventArgs e)

        {

            

        }
 

        protected void lbtnReturntoHome_Click(object sender, EventArgs e)

        {

            Response.Redirect("default.aspx");

        }
 

        

        protected void btnSubmit_Click(object sender, EventArgs e)

        {

            

            
 

            if (FileUpload1.HasFile)

                try

                {
 

                    string fn = System.IO.Path.GetFileName(FileUpload1.PostedFile.FileName); 

                    string SaveLocation = Server.MapPath("UploadedFiles") + "\\" + fn; 

                    lblResults.Text = "File Successfully Uploaded: <br>" + "File name: " +

                        FileUpload1.PostedFile.FileName + "<br>" +

                        FileUpload1.PostedFile.ContentLength + " kb<br>" +

                        "Content type: " +

                        FileUpload1.PostedFile.ContentType;
 
 

                    ClientFileRepository repository = new ClientFileRepository();

                    repository.InsertNewFile(SaveLocation, txtDescription.Text);

                    

                    lblError.Text = "";
 

                    

                }

                

                catch (Exception ex) //this should catch if jibberish is entered but it doesn't

                {

                    //lblError.Text = "Error: File was not found.";

                    Response.Write("Error: " + ex.Message);

                }

            else

            {

                txtDescription.Text = "";

                lblResults.Text = "";

                lblError.Text = "You have not specified a file.";

            }
 
 

                        

        }

    }

}
 
 

Stored Procedure class:

using System;

using System.Data;

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;

using System.Data.SqlClient;
 

namespace FileTransfer2

{

    public class ClientFileRepository

    {

        public void InsertNewFile(string fileName, string description)

        {

            using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["FileTransferConnectionString"].ToString()))

            {

                using (SqlCommand cmd = new SqlCommand("InsertNewFile", conn)) //stored proc name

                {

                    cmd.CommandType = CommandType.StoredProcedure;

                    cmd.Parameters.AddWithValue("@FileName", fileName); // replace w/ FileUpload1.PostedFile.FileName (FileUpload.aspx) don't know how //did it in code behind

                    cmd.Parameters.AddWithValue("@Description", description);

                    conn.Open();

                    cmd.ExecuteNonQuery();

                }

            }

        }

    }

}

Open in new window

0
Comment
Question by:AJ0424
  • 2
3 Comments
 
LVL 26

Accepted Solution

by:
Anurag Thakur earned 500 total points
Comment Utility
check the follwoing link as the user was also getting the same error as you are getting
http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=541116&SiteID=1

Also in the code i could not see FileTransfer2.DataSets.ClientFilesbyDateRangeTableAdapters.getFilesbyClientDateRangeTableAdapter class
0
 

Author Comment

by:AJ0424
Comment Utility
Ragi,

Thanks for the link!  I created a new page that worked fine and figured out that it must not be with the grid but rather with the data set but I had no idea how to go about correcting the problem.

For anyone as new as I am, in the middle of the project I changed a field from nvarchar(255) to nvarchar(1000).  Even though the database was correct, the dataset was still hard coded with my original values.  I had to open [DataSetName].Designer.cs and I found all of the original values and changed them to 1000.  Now everything works fine.

Thanks,
AJ
0
 

Author Closing Comment

by:AJ0424
Comment Utility
If you have any thoughts on the final two questions of my post, I would love to hear them.  Thanks so much for your help, it is really appreciated.

AJ

1. How to make the FileName column display only the name and extension of the file instead of the whole path (example: Test.doc instead of C:\importantinfo\Test.doc)

2. How to make the FileName column a link that downloads the file.
0

Featured Post

Do You Know the 4 Main Threat Actor Types?

Do you know the main threat actor types? Most attackers fall into one of four categories, each with their own favored tactics, techniques, and procedures.

Join & Write a Comment

ASP.Net to Oracle Connectivity Recently I had to develop an ASP.NET application connecting to an Oracle database.As I am doing it first time ,I had to solve several problems. This article will help to such developers  to develop an ASP.NET client…
More often than not, we developers are confronted with a need: a need to make some kind of magic happen via code. Whether it is for a client, for the boss, or for our own personal projects, the need must be satisfied. Most of the time, the Framework…
In this tutorial you'll learn about bandwidth monitoring with flows and packet sniffing with our network monitoring solution PRTG Network Monitor (https://www.paessler.com/prtg). If you're interested in additional methods for monitoring bandwidt…
This video explains how to create simple products associated to Magento configurable product and offers fast way of their generation with Store Manager for Magento tool.

762 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now