Question

this is a simple DetailsView with for inserting data in Database. all of my parameters are set in form. however, i need to set one of them in code behind. this form is used to upload files to file system using FileUpload control in DetailsVeiw. but i need to enter the uploaded files path to DB. How can i make this happen? while testing the code i find out that the parameters from the form are working and the data is inserted to the DB but not the one from code behind. thanks in advance.

the Form:

        <asp:DetailsView ID="DetailsView1" runat="server" AutoGenerateInsertButton="True" AutoGenerateRows="False" DataKeyNames="attachmentID" DataSourceID="SqlDataSource1" DefaultMode="Insert" Height="50px" Width="125px"
            OnItemInserted="DetailsView1_ItemInserted">
            <Fields>
                <asp:BoundField DataField="attachmentID" HeaderText="attachmentID" InsertVisible="False" ReadOnly="True" SortExpression="attachmentID" />
                <asp:BoundField DataField="attachmentTitle" HeaderText="attachmentTitle" SortExpression="attachmentTitle" />
                <asp:TemplateField HeaderText="Attach File" SortExpression="FileName">
                    <InsertItemTemplate>
                        <asp:FileUpload ID="FileUpload1" runat="server" />
                    </InsertItemTemplate>
                </asp:TemplateField>
                <asp:BoundField DataField="attachmentType" HeaderText="attachmentType" SortExpression="attachmentType" />
                <asp:BoundField DataField="attachmentDescription" HeaderText="attachmentDescription" SortExpression="attachmentDescription" />
                <asp:BoundField DataField="attachmentFile" HeaderText="attachmentFile" SortExpression="attachmentFile" InsertVisible="false"/>

            </Fields>
        </asp:DetailsView>
        <asp:Label ID="StatusLabel" runat="server" Text="Label"></asp:Label>
        <br />

        <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:SPMS_DBConnectionString1 %>" 
            InsertCommand="INSERT INTO [Attachment] ( [attachmentTitle], [attachmentFile], [attachmentType], [projectID], [attachmentDescription], [attachmentDate]) VALUES ( @attachmentTitle, @attachmentFile, @attachmentType, @projectID, @attachmentDescription, GetDate())" 
            ProviderName="<%$ ConnectionStrings:SPMS_DBConnectionString1.ProviderName %>">

            <InsertParameters>
                <asp:Parameter Name="attachmentTitle" Type="String" />
                <asp:Parameter Name="attachmentType" Type="String" />
                <asp:SessionParameter Name="projectID" SessionField="project" Type="String" />
                <asp:Parameter Name="attachmentDescription" Type="String" />
                <asp:Parameter Name="attachmentFile" Type="String" />
            </InsertParameters>

        </asp:SqlDataSource>

    </div>
</form>

in the Code behind: this is the line of code that doesn't affect the parameters:

    SqlDataSource1.InsertParameters["attachmentFile"].DefaultValue = Convert.ToString(MapPath("~/AttachedFiles/") + filename);

the Code behind:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;


public partial class stdDocumentsInsert : System.Web.UI.Page
{

string filename;
protected void Page_Load(object sender, EventArgs e)
{
    if (!Directory.Exists(Server.MapPath("~/AttachedFiles/")))
    {
        Directory.CreateDirectory(Server.MapPath("~/AttachedFiles/"));
    }
}
protected void DetailsView1_ItemInserted(object sender, DetailsViewInsertedEventArgs e)
{


    FileUpload fu1 = (FileUpload)this.DetailsView1.FindControl("FileUpload1");
    //if (fu1 == null)
    //{
    //    //e.Cancel = true;
    //    StatusLabel.Text = "Could not find file upload";
    //}
    if (fu1.HasFile)
    {
        try
        {
            filename = Path.GetFileName(fu1.PostedFile.FileName);
            fu1.SaveAs(Server.MapPath("~/AttachedFiles/") + filename);
            StatusLabel.Text = "Upload status: File uploaded!";
            SqlDataSource1.InsertParameters["attachmentFile"].DefaultValue = Convert.ToString(MapPath("~/AttachedFiles/") + filename);
            //SqlDataSource1.insert(); // when i used this it worked but other fields in DB became Null


        }
        catch (Exception ex)
        {
            StatusLabel.Text = "Upload status: The file could not be uploaded. The following error occured: " + ex.Message;
        }

    }
    else
    {
        //e.Cancel = true;
        StatusLabel.Text = "No file uploaded";
        return;
    }
}
}
Was it helpful?

Solution

From MSDN DetailsView.ItemInserted Event:

"Occurs when an Insert button within a DetailsView control is clicked, but after the insert operation."

So you are setting the value after the insert. You code is correct for setting the Insert Parameter you just have to call it in the DetailsView.ItemInserting event

OTHER TIPS

Add a varbinary field named as tc in the database itself then do the following :

Protected Sub SqlDataSource1_Inserting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.SqlDataSourceCommandEventArgs) Handles SqlDataSource1.Inserting
        Dim FU As New FileUpload
        FU = DetailsView1.FindControl("fileupload1")    
        Using fs As Stream = FU.PostedFile.InputStream
            Using br As New BinaryReader(fs)
                Dim tc As SqlParameter
                tc = New SqlParameter("@tc", SqlDbType.VarBinary)
                Dim bytes As Byte() = br.ReadBytes(DirectCast(fs.Length, Long))
                tc.Value = bytes
                e.Command.Parameters.Add(tc)

            End Using
        End Using       
    End Sub
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top