Codeone Codeone - 3 years ago 115
ASP.NET (C#) Question

Image upload not working Always get the FALSE value

UI ui
Image upload part is not working, I want to upload image path in Database but not working, and not bind correctly can't save it, can you please help me, Table to displayed upload image value is always FALSE enter image description here
ASPX

<asp:TemplateField HeaderText="Images">
<ItemTemplate>
<asp:FileUpload runat="server" AutoPostBack="True" ID="fileupload" CommandArgument='<%# Eval("strImage") %>' ClientIDMode="Static"/>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="">
<ItemTemplate>
<asp:Image ImageUrl="~/Uploaded Images/Default.png" runat="server" ID="image" Width="40" Height="40"/>
</ItemTemplate>
</asp:TemplateField>


CODE

#region Detail Save1
private DataTable CreateDetailSave()
{
DataTable dtDetailSave1 = new DataTable();
DataColumn dc1;
dc1 = new DataColumn("intArticleDetailId");
dtDetailSave1.Columns.Add(dc1);
dc1 = new DataColumn("intSectionId");
dtDetailSave1.Columns.Add(dc1);
dc1 = new DataColumn("intCompoundId");
dtDetailSave1.Columns.Add(dc1);
dc1 = new DataColumn("decSectionWeight");
dtDetailSave1.Columns.Add(dc1);
dc1 = new DataColumn("intMessageId");
dtDetailSave1.Columns.Add(dc1);
dc1 = new DataColumn("strImage");
dtDetailSave1.Columns.Add(dc1);

foreach (GridViewRow row in gvArticle.Rows)
{
DataRow dr = dtDetailSave1.NewRow();

Label lblintArticleDetailId = (Label)row.FindControl("lblArticleDetailId");
Label lblSectionId = (Label)row.FindControl("lblSectionId");
DropDownList ddlCompound = (DropDownList)row.FindControl("ddlCompoundId");
TextBox txtdecSectionWeighte = (TextBox)row.FindControl("txtdecSectionWeighte");
DropDownList intMessage = (DropDownList)row.FindControl("ddlMessage");

FileUpload fileupload = (FileUpload)row.FindControl("fileupload");

dr["intArticleDetailId"] = CurrentMode == "Add" ? -1 : Convert.ToInt32(lblintArticleDetailId.Text);

dr["intSectionId"] = Convert.ToInt32(lblSectionId.Text);
dr["intCompoundId"] = ddlCompound.SelectedValue;
dr["decSectionWeight"] = txtdecSectionWeighte.Text.Trim() != "" ? Convert.ToDecimal(txtdecSectionWeighte.Text.Trim()) : 0;
dr["intMessageId"] = intMessage.SelectedValue;
dr["strImage"] = fileupload.HasFile;

dtDetailSave1.Rows.Add(dr);
}
return dtDetailSave1;
}
#endregion

#region pageload
protected void Page_Load(object sender, EventArgs e)
{

if (!IsPostBack)
{

ClearControls();

FillArticleDetails();

EnableControls(false);
Session["SearchPopup"] = false;

}
else
{
if (Session["SearchPopup"] != null)
{
SearchPopup = (bool)(Session["SearchPopup"]);
if (SearchPopup != false)
{
MyMPE.Show();
}
else
{
MyMPE.Hide();
}
}

vAdSearchParaList = new List<SearchParametors>();

}
}
#endregion
#region Create Article table
private void createArticleDataTable()
{
if (dt.Columns.Count == 0)
{
dt.Columns.Add(new DataColumn("intArticleDetailId", typeof(int)));
dt.Columns.Add(new DataColumn("intSectionId", typeof(int)));
dt.Columns.Add(new DataColumn("strSectionName", typeof(string)));
dt.Columns.Add(new DataColumn("intCompoundId", typeof(string)));
dt.Columns.Add(new DataColumn("decSectionWeight", typeof(string)));
dt.Columns.Add(new DataColumn("intMessageId", typeof(string)));
dt.Columns.Add(new DataColumn("fileupload", typeof(string)));

}

gvArticle.DataSource = dt;
gvArticle.DataBind();
}
#endregion

#region Compound Grid - Add empty row
private void ArticleGridAddEmptyRow(int newId)
{
DataRow newDr = null;
newDr = dt.NewRow();
newDr["intArticleDetailId"] = 1;
newDr["intSectionId"] = 1;
newDr["strSectionName"] = "";
newDr["intCompoundId"] = "";
newDr["decSectionWeight"] = "";
newDr["intMessageId"] = "";
newDr["strImage"] = "";

dt.Rows.Add(newDr);

if (dtArticleDetails == null || dtArticleDetails.Rows.Count == 0)
{
dtArticleDetails = dt;
}
else
{
dtArticleDetails.Merge(dt);

gvArticle.DataSource = dt;
gvArticle.DataBind();
}
}
#endregion

protected void gvArticle_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
GridViewRow row = gvArticle.Rows[e.RowIndex];
FileUpload fu = row.Cells[0].FindControl("strImage") as FileUpload;
if (fu != null && fu.HasFile)
{
fu.SaveAs(Server.MapPath("~/Uploaded Images" + fu.FileName));
}
}





full aspx




<asp:GridView ID="gvArticle" ShowHeaderWhenEmpty="True" CssClass="table table-bordered table-condensed table-hover" AutoGenerateColumns="False" runat="server" AllowPaging="True" PageSize="15" OnRowDataBound="gvArticle_RowDataBound" BackColor="White" BorderColor="#CCCCCC" BorderStyle="None" BorderWidth="1px" CellPadding="4" ForeColor="Black" GridLines="Horizontal" OnRowUpdating="gvArticle_RowUpdating">
<%--<HeaderStyle BackColor="#3d4247" ForeColor="White" />--%>
<Columns>
<asp:TemplateField HeaderText="intArticleDetail" Visible="false">
<ItemTemplate>
<asp:Label ID="lblArticleDetailId" Width="2" Text='<%# Bind("intArticleDetailId") %>' ClientIDMode="Static" runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>

<asp:TemplateField HeaderText="SectionID" Visible="false">
<ItemTemplate>
<asp:Label ID="lblSectionId" Width="2" Text='<%# Bind("intSectionId") %>' ClientIDMode="Static" runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>

<asp:TemplateField HeaderText="Section">
<ItemTemplate>
<asp:Label ID="lblSectionName" Width="100" Text='<%# Bind("strSectionName") %>' ClientIDMode="Static" runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Compound">
<EditItemTemplate>
<asp:Label ID="lblItemTypeEdit" Width="50" Text='<%# Bind("strCompoundName") %>' lientIDMode="Static" AutoPostBack="true" runat="server">
</asp:Label>
</EditItemTemplate>

<ItemTemplate>
<asp:DropDownList ID="ddlCompoundId" Width="200" CssClass="form-control my-DropDownThin" lientIDMode="Static" AutoPostBack="true" runat="server">
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>


<asp:TemplateField HeaderText="Weight">
<ItemTemplate>
<asp:TextBox ID="txtdecSectionWeighte" Width="100%" Text='<%# Bind("decSectionWeight") %>' lientIDMode="Static" runat="server"> </asp:TextBox>
</ItemTemplate>
</asp:TemplateField>

<%--<asp:TemplateField HeaderText="Messagers">
<ItemTemplate>
<asp:TextBox ID="txtMessage" Width="100%" Text='<%# Bind("intMessageId") %>' ClientIDMode="Static" runat="server"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>--%>

<asp:TemplateField HeaderText="Messagers">
<EditItemTemplate>
<asp:Label ID="lblMessageId" Width="50" Text='<%# Bind("strMessage") %>' ClientIDMode="Static" AutoPostBack="true" runat="server">
</asp:Label>
</EditItemTemplate>

<ItemTemplate>
<asp:DropDownList ID="ddlMessage" Width="300" CssClass="form-control my-DropDownThin" lientIDMode="Static" AutoPostBack="true" runat="server">
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>

<asp:TemplateField HeaderText="Images">
<ItemTemplate>


<asp:FileUpload runat="server" AutoPostBack="True" ID="uploadFImage" CommandArgument='<%# Eval("strImage") %>' ClientIDMode="Static"/>

</ItemTemplate>
</asp:TemplateField>


<asp:TemplateField HeaderText="">
<ItemTemplate>


<asp:Image ImageUrl="~/Uploaded Images/Default.png" runat="server" ID="btnViewFImage" Width="40" Height="40"/>

</ItemTemplate>
</asp:TemplateField>

</Columns>

<FooterStyle BackColor="#CCCC99" ForeColor="Black" />
<HeaderStyle BackColor="#333333" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="White" ForeColor="Black" HorizontalAlign="Right" />
<SelectedRowStyle BackColor="#CC3333" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#F7F7F7" />
<SortedAscendingHeaderStyle BackColor="#4B4B4B" />
<SortedDescendingCellStyle BackColor="#E5E5E5" />
<SortedDescendingHeaderStyle BackColor="#242121" />

</asp:GridView>
</div>
</ContentTemplate>
<Triggers>
<asp:PostBackTrigger ControlID="gvArticle"/>
</Triggers>

</asp:UpdatePanel>
</div>
</div>





gvArticle_rowdatabound

protected void gvArticle_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Footer)
{


}
else if (e.Row.RowType == DataControlRowType.DataRow)
{


{


}

DataTable CompoundCode = clsArticle.CompoundDataForGrid("");

DropDownList ddlCompoundId = (DropDownList)e.Row.FindControl("ddlCompoundId");
if (ddlCompoundId != null)
{
ddlCompoundId.DataTextField = "Compound Code";
ddlCompoundId.DataValueField = "Compound Id";
ddlCompoundId.DataSource = CompoundCode;
ddlCompoundId.DataBind();

string country = (e.Row.FindControl("ddlCompoundId") as DropDownList).Text;
ddlCompoundId.Items.FindByValue(country).Selected = true;
}


DataTable MsgCode = clsArticle.MessageDataForGrid("");

DropDownList ddlMessage = (DropDownList)e.Row.FindControl("ddlMessage");
if (ddlMessage != null)
{
ddlMessage.DataTextField = "Message Name";
ddlMessage.DataValueField = "Message Id";
ddlMessage.DataSource = MsgCode;
ddlMessage.DataBind();

ddlMessage.Items.Insert(0, new ListItem("Please select"));
string country = (e.Row.FindControl("ddlMessage") as DropDownList).Text;
ddlMessage.Items.FindByValue(country).Selected = true;
}



//}


}
}

Answer Source

Your code has lots of issues. First of all FileUpload control doesn't have AutoPostBack property as well as CommandArgument property so you need a button in each row.

.aspx fragment

<asp:TemplateField HeaderText="upload">
    <ItemTemplate>
        <asp:FileUpload ID="fileupload" AutoPostBack="true"  runat="server" />
    </ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="upload">
    <ItemTemplate>
        <asp:Button ID="btnUpdate" Text="upload" OnClick="btnUpdate_Click" CommandArgument='<%#Eval("PK_FIELD") %>' runat="server" />
    </ItemTemplate>
</asp:TemplateField>

.aspx.cs fragment

protected void btnUpdate_Click(object sender, EventArgs e)
{
    FileUpload fu = 
      ((GridViewRow)((WebControl)sender).NamingContainer)
          .FindControl("fileupload") as FileUpload;
    bool ok = false;
    if (fu != null && fu.HasFile)
    {
        try
        {
            //possible issue here.
            //process NEED PERMISSION to write to this folder
            //also some checks with fu.PostedFile are recommended
            fu.SaveAs(Server.MapPath("~/images/" + fu.FileName));
            ok = true;
        }
        catch (Exception ex)
        {
            ok = false;
        }
    }
    if (ok)
    {
        //update DB table and GridViewRow image field.
    }
}

I hope this explanation is useful and acceptable.

Update based on your gridview

    <asp:GridView ID="gvArticle" ShowHeaderWhenEmpty="True" CssClass="table
     table-bordered table-condensed table-hover" AutoGenerateColumns="False"
     runat="server" AllowPaging="True" PageSize="15" 
    OnRowDataBound="gvArticle_RowDataBound" 
 DataKeyNames="PK_field"  **important**
    >
        <%--<HeaderStyle BackColor="#3d4247" ForeColor="White" />--%>
        <Columns>
            <asp:TemplateField HeaderText="intArticleDetail" Visible="false">
            <ItemTemplate>
               <asp:Label ID="lblArticleDetailId" Width="2" 
Text='<%# Eval("intArticleDetailId") %>' **Bind is nonsense for label**
 runat="server"></asp:Label> **ClientIDMode="Static" remove everiwhere**
            </ItemTemplate>
            </asp:TemplateField> 

            <asp:TemplateField HeaderText="SectionID" Visible="false">
                 <ItemTemplate>
                    <asp:Label ID="lblSectionId" Width="2" Text='<%# Bind("intSectionId") %>' ClientIDMode="Static" runat="server"></asp:Label> 
                 </ItemTemplate>
            </asp:TemplateField>                                                        
        <asp:TemplateField HeaderText="Section">
            <ItemTemplate>
                <asp:Label ID="lblSectionName" Width="100"  Text='<%# Bind("strSectionName") %>' ClientIDMode="Static" runat="server"></asp:Label> 
            </ItemTemplate>
        </asp:TemplateField>  
        <asp:TemplateField HeaderText="Compound">
            <EditItemTemplate>** no edit mode remove**
                <asp:Label ID="lblItemTypeEdit" Width="50" 
Text='<%# Bind("strCompoundName") %>' ** see above**
ClientIDMode="Static" 
AutoPostBack="true" 
runat="server">                                                                               
                </asp:Label>
            </EditItemTemplate>
            <ItemTemplate>
                <asp:DropDownList ID="ddlCompoundId" Width="200" 
    CssClass="form-control my-DropDownThin" ClientIDMode="Static" AutoPostBack="true" runat="server">                                                                               
                </asp:DropDownList>
            </ItemTemplate>
         </asp:TemplateField>
    <asp:TemplateField HeaderText="Weight">
    <ItemTemplate>
    <asp:TextBox ID="txtdecSectionWeighte" Width="100%" Text='<%# Bind("decSectionWeight") %>' ClientIDMode="Static" runat="server">  </asp:TextBox>                                                                            
    </ItemTemplate>
    </asp:TemplateField>
    <asp:TemplateField HeaderText="Messagers">                                                                
    <ItemTemplate>

    <asp:TextBox ID="txtMessage" Width="100%" Text='<%# Bind("intMessageId") %>' ClientIDMode="Static" runat="server"></asp:TextBox>
    </ItemTemplate>
</asp:TemplateField>--%>

        <asp:TemplateField HeaderText="Messagers">
    <EditItemTemplate>
    <asp:Label ID="lblMessageId" Width="50" Text='<%# Bind("strMessage") %>' ClientIDMode="Static" AutoPostBack="true" runat="server">                                                                               
    </asp:Label>
    </EditItemTemplate>

        <ItemTemplate>
    <asp:DropDownList ID="ddlMessage" Width="300" CssClass="form-control my-DropDownThin" ClientIDMode="Static" AutoPostBack="true" runat="server">                                                                               
    </asp:DropDownList>
    </ItemTemplate>
    </asp:TemplateField>
    <asp:TemplateField HeaderText="Images">                                                                <ItemTemplate>
**work with upload. remove wrong attributes**
**AutoPostBack="True"CommandArgument='<%# Eval("strImage") %>' ClientIDMode="Static" ** 
          <asp:FileUpload runat="server" ID="uploadFImage" />
</ItemTemplate>
</asp:TemplateField> 
<asp:TemplateField HeaderText="">                                                                
<ItemTemplate>
<asp:Image ImageUrl="~/Uploaded Images/Default.png" runat="server" ID="btnViewFImage"  Width="40" Height="40"/>
</ItemTemplate>
</asp:TemplateField> 
</Columns>


     <FooterStyle BackColor="#CCCC99" ForeColor="Black" />
     <HeaderStyle BackColor="#333333" Font-Bold="True" ForeColor="White" />
     <PagerStyle BackColor="White" ForeColor="Black" HorizontalAlign="Right" />
     <SelectedRowStyle BackColor="#CC3333" Font-Bold="True" ForeColor="White" />
     <SortedAscendingCellStyle BackColor="#F7F7F7" />
     <SortedAscendingHeaderStyle BackColor="#4B4B4B" />
     <SortedDescendingCellStyle BackColor="#E5E5E5" />
     <SortedDescendingHeaderStyle BackColor="#242121" />

</asp:GridView>    
** place update button outside to update all columns **
<asp:Button ID="btnUpdate" Text="upload" OnClick="btnUpdate_Click" runat="server" />

//.aspx.cs
    protected void btnUpdate_Click(object sender, EventArgs e)
{
foreach(GridViewRow row in gvArticle.rows)
{

    FileUpload fu = 
          row.FindControl("fileupload") as FileUpload;
    bool ok = false;
    if (fu != null && fu.HasFile)
    {
        try
        {
            //possible issue here.
            //process NEED PERMISSION to write to this folder
            //also some checks with fu.PostedFile are recommended
            fu.SaveAs(Server.MapPath("~/images/" + fu.FileName));
            ok = true;
        }
        catch (Exception ex)
        {
            ok = false;
        }
    }
    if (ok)
    {
        //update DB table and GridViewRow image field.
    }
}
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download