How to save a file using the asp.net fileupload control? - c#

I have an asp.net webforms c# application that has a FileUpload control inside the InsertItemTemplate of a FormView. When inserting the new record the correct path + filename is saved to the appropriate field in the database, but the file isn't saved to the Data folder. Here is the code behind:
protected void fv_ven_doc_det_DataBound(object sender, EventArgs e)
{
if (fv_ven_doc_det.CurrentMode == FormViewMode.Insert)
{
//Set the fk
TextBox venIdFkTxt = (TextBox)fv_ven_doc_det.FindControl("venIdFkTextBox");
if (venIdFkTxt != null)
{
venIdFkTxt.Text = hdn_ven_id.Value;
}
//Get the upload date - current date and time
hdn_doc_upload_dt_txt.Value = DateTime.Now.ToString();
string docuplddt = fv_ven_doc_det.FindControl("docUpldDtTextBox").ToString();
docuplddt = hdn_doc_upload_dt_txt.Value;
TextBox docuplddttxt = (TextBox)fv_ven_doc_det.FindControl("docUpldDtTextBox");
if (docuplddttxt != null)
{
docuplddttxt.Text = hdn_doc_upload_dt_txt.Value;
}
//Set the current status
TextBox crntDocStatTxt = (TextBox)fv_ven_doc_det.FindControl("docStatTextBox");
if (crntDocStatTxt != null)
{
crntDocStatTxt.Text = "4";
}
//Set the filename and save the file
int i = 0;
FileUpload fu = (FileUpload)(fv_ven_doc_det.FindControl("fu_doc_upld"));
string filename = fu.FileName;
if (fu.HasFile == true)
{
while (System.IO.File.Exists(Server.MapPath("~/Data/") + filename))
{
i++;
filename = fu.FileName + " (" + i.ToString() + ")";
}
fu.PostedFile.SaveAs(Server.MapPath("~/Data/") + filename);
}
TextBox filenameTxt = (TextBox)fv_ven_doc_det.FindControl("docPathTextBox");
{
filenameTxt.Text = (Server.MapPath("~/Data/") + filename);
}
}
}
Here is the InsertItemTemplate of the FormView:
<InsertItemTemplate>
<asp:TextBox Text='<%# Bind("venIdFk") %>' runat="server" ID="venIdFkTextBox" Visible="false" />
<asp:TextBox Text='<%# Bind("docPath") %>' runat="server" ID="docPathTextBox" Visible="false" />
<asp:TextBox Text='<%# Bind("docStat") %>' runat="server" ID="docStatTextBox" Visible="false" />
<asp:TextBox Text='<%# Bind("docUpldDt") %>' runat="server" ID="docUpldDtTextBox" Visible="false" />
<div class="row">
<div class="form-group col-md-3">
<strong>Title</strong><br />
<asp:TextBox Text='<%# Bind("docTitle") %>' runat="server" ID="docTitleTextBox" CssClass="form-control widecontrol" /><br />
</div>
<div class="form-group col-md-3">
<strong>Type</strong><br />
<asp:DropDownList ID="ddlVenDocType" runat="server" DataSourceID="sdc_doc_type" DataTextField="dtype" DataValueField="dtypeId" SelectedValue='<%# Bind("docType") %>' AppendDataBoundItems="true" CssClass="form-control widecontrol"><asp:ListItem Value="">--Please Select--</asp:ListItem></asp:DropDownList><br />
</div>
<div class="form-group col-md-3">
<strong>Organization</strong><br />
<asp:DropDownList ID="ddlVenDocOrg" runat="server" DataSourceID="sdc_orgs" DataTextField="org" DataValueField="orgId" SelectedValue='<%# Bind("docOrg") %>' AppendDataBoundItems="true" CssClass="form-control widecontrol"><asp:ListItem Value="">--Please Select--</asp:ListItem></asp:DropDownList><br />
</div>
<div class="form-group col-md-3">
<strong>Department</strong><br />
<asp:DropDownList ID="ddlVenDocDept" runat="server" DataSourceID="sdc_depts" DataTextField="dept" DataValueField="deptId" SelectedValue='<%# Bind("docDept") %>' AppendDataBoundItems="true" CssClass="form-control widecontrol"><asp:ListItem Value="">--Please Select--</asp:ListItem></asp:DropDownList><br />
</div>
</div>
<div class="row">
<div class="form-group col-md-3">
<strong>Prior Contract Code</strong><br />
<asp:TextBox Text='<%# Bind("PriorContCd") %>' runat="server" ID="PriorContCdTextBox" CssClass="form-control widecontrol" /><br />
</div>
<div class="form-group col-md-3">
<strong>Legal / Compliance Contract ID</strong><br />
<asp:TextBox Text='<%# Bind("LegCompContId") %>' runat="server" ID="LegCompContIdTextBox" CssClass="form-control widecontrol" /><br />
</div>
</div>
<div class="row">
<div class="form-group col-md-12">
<strong>Description</strong><br />
<asp:TextBox Text='<%# Bind("docDesc") %>' runat="server" ID="docDescTextBox" CssClass="form-control widecontrol" Rows="5" TextMode="MultiLine" /><br />
</div>
</div>
<div class="row">
<div class="form-group col-md-12">
<asp:FileUpload ID="fu_doc_upld" runat="server" />
<asp:RequiredFieldValidator ID="rfv_fu_doc_upld" runat="server" ErrorMessage="A file must be chosen to upload." ControlToValidate="fu_doc_upld" ForeColor="#ff0000" Font-Bold="true">*</asp:RequiredFieldValidator>
</div>
</div>
<asp:LinkButton runat="server" Text="Insert" CommandName="Insert" ID="InsertButton" CausesValidation="True" CssClass="cmdlinkpdg" /> <asp:LinkButton runat="server" Text="Cancel" CommandName="Cancel" ID="InsertCancelButton" CausesValidation="False" CssClass="cmdlinkpdg" />
</InsertItemTemplate>
I'm not getting any errors, it just doesn't save the file.

OK, it helps to stop and think about what actually needs to happen. I moved the filename / path and upload to OnItemInserting and it all works now.

Related

How to calculate all rows in a GridView in a single button click

I have a GridView in which I'm letting users edit previously generated estimates. Everything works fine till I hit recalculate button but after that, all the row values go haywire.
Below is a screenshot of the layout for your reference.
In that, All the details are being fetched from database and few of them are editable and after changing the values, below there is a refresh button which I'm using to recalculate. but my loop is causing them to calculate incorrectly. Please help me rectify my mistake.
below is my aspx code:
<div class="card-body">
<div class="row">
<div class="col-md-12">
<asp:GridView ID="grdPurchaseBill" runat="server" CssClass="table table-bordered table-responsive table-sm" AutoGenerateColumns="False" ShowFooter="false">
<Columns>
<asp:TemplateField HeaderText="Product" ItemStyle-Wrap="false" ControlStyle-Width="100%" ItemStyle-Width="100%">
<ItemTemplate>
<asp:TextBox ID="txtProduct" runat="server" CssClass="form-control form-control-sm" Width="100%" Style="width: 100%;" AutoCompleteType="Disabled" autocomplete="off" Text='<%# Eval("product") %>'></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Weight" ItemStyle-Wrap="false" HeaderStyle-Wrap="false">
<ItemTemplate>
<asp:TextBox ID="txtWeight" runat="server" CssClass="form-control form-control-sm" Text='<%# Eval("weight") %>' Width="100%" Style="width: 100%;"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="# of Bags" ItemStyle-Wrap="false" ControlStyle-Width="100%" HeaderStyle-Wrap="false">
<ItemTemplate>
<asp:TextBox ID="txtBags" runat="server" CssClass="form-control form-control-sm" Text='<%# Eval("bags") %>' Width="100%" Style="width: 100%;"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Shortage %" ItemStyle-Wrap="false" ControlStyle-Width="100%" HeaderStyle-Wrap="false">
<ItemTemplate>
<asp:TextBox ID="txtShortagePercent" runat="server" CssClass="form-control form-control-sm" Text='<%# Eval("shortage_percent") %>' Width="100%" Style="width: 100%;"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Shortage" ItemStyle-Wrap="false" ControlStyle-Width="100%" HeaderStyle-Wrap="false">
<ItemTemplate>
<asp:TextBox ID="txtShortage" runat="server" CssClass="form-control form-control-sm" Text='<%# Eval("shortage") %>' Width="100%" Style="width: 100%;" Enabled="false"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Net Weight" ItemStyle-Wrap="false" ControlStyle-Width="100%" HeaderStyle-Wrap="false">
<ItemTemplate>
<asp:TextBox ID="txtNetWeight" runat="server" CssClass="form-control form-control-sm" Text='<%# Eval("net_weight") %>' Width="100%" Style="width: 100%;" Enabled="false"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Unit Price" ItemStyle-Wrap="false" HeaderStyle-Wrap="false" ControlStyle-Width="100%">
<ItemTemplate>
<asp:TextBox ID="txtRate" runat="server" CssClass="form-control form-control-sm" Text='<%# Eval("rate") %>' Width="100%" Style="width: 100%;"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Sub-Total" ItemStyle-Wrap="false" HeaderStyle-Wrap="false" ControlStyle-Width="100%">
<ItemTemplate>
<asp:TextBox ID="txtSubTotal" runat="server" CssClass="form-control form-control-sm" Text='<%# Eval("sub_total") %>' Width="100%" Style="width: 100%;" Enabled="false"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Hamali %" ItemStyle-Wrap="false" HeaderStyle-Wrap="false" ControlStyle-Width="100%">
<ItemTemplate>
<asp:TextBox ID="txtHamali" runat="server" CssClass="form-control form-control-sm" Text='<%# Eval("hamali_percent") %>' Width="100%" Style="width: 100%;"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Hamali Amt" ItemStyle-Wrap="false" HeaderStyle-Wrap="false" ControlStyle-Width="100%">
<ItemTemplate>
<asp:TextBox ID="txtHamaliAmount" runat="server" CssClass="form-control form-control-sm" Text='<%# Eval("hamali") %>' Width="100%" Style="width: 100%;" Enabled="false"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Driver Comm. " ItemStyle-Wrap="false" HeaderStyle-Wrap="false" ControlStyle-Width="100%">
<ItemTemplate>
<asp:TextBox ID="txtDriverCommission" runat="server" CssClass="form-control form-control-sm" Text='<%# Eval("driver_commission") %>' Width="100%" Style="width: 100%;"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Net Amt" ItemStyle-Wrap="false" ControlStyle-Width="100%" HeaderStyle-Wrap="false">
<ItemTemplate>
<asp:TextBox ID="txtNetAmount" runat="server" CssClass="form-control form-control-sm" Enabled="false" Text='<%# Eval("net_amount") %>' Width="100%" Style="width: 100%;"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
<div class="col-md-3">
<div class="form-group">
<label>Bill Date</label>
<div class="input-group margin input-group-sm">
<asp:TextBox ID="txtBDate" runat="server" CssClass="form-control form-control-sm" TabIndex="1" AutoCompleteType="Disabled" autocomplete="off"></asp:TextBox>
<ajax:CalendarExtender ID="ce1" runat="server" TargetControlID="txtBDate" Format="dd-MM-yyyy" />
<span class="input-group-btn">
<span class="fa fa-times"></span>
</span>
</div>
</div>
</div>
<div class="col-md-3">
<div class="form-group">
<label>Name</label>
<div class="input-group input-group-sm">
<asp:TextBox ID="txtcname" runat="server" CssClass="form-control form-control-sm" TabIndex="2" CausesValidation="True" AutoCompleteType="Disabled" autocomplete="off"></asp:TextBox>
<asp:HiddenField ID="hfCustomerId" runat="server" />
</div>
</div>
</div>
<div class="col-md-3">
<div class="form-group">
<label>Phone</label>
<asp:TextBox ID="txtcmobile" runat="server" CssClass="form-control form-control-sm" TabIndex="3" AutoCompleteType="Disabled" autocomplete="off"></asp:TextBox>
</div>
</div>
<div class="col-md-3">
<div class="form-group">
<label>Address</label>
<asp:TextBox ID="txtcaddress" runat="server" TextMode="MultiLine" TabIndex="6" CssClass="form-control form-control-sm"></asp:TextBox>
</div>
</div>
<div class="col-md-3">
<div class="form-group">
<label>Lorry Freight</label>
<asp:TextBox ID="txtLorryFreight" runat="server" TabIndex="6" CssClass="form-control form-control-sm"></asp:TextBox>
</div>
</div>
<div class="col-md-3">
<div class="form-group">
<label>Remarks</label>
<asp:TextBox ID="txtRemarks" runat="server" TabIndex="6" CssClass="form-control form-control-sm" TextMode="MultiLine"></asp:TextBox>
</div>
</div>
<div class="col-md-3">
<div class="form-group">
<label>Total Amount</label>
<asp:Label ID="lblTotal" runat="server" CssClass="form-control form-control-sm lblTotal" Text="0" ForeColor="Blue" BackColor="#DEE2E6"></asp:Label>
</div>
</div>
<div class="col-md-3">
<div class="form-group">
<label>Payable Amount</label>
<asp:Label ID="lblPayableAmt" runat="server" CssClass="form-control form-control-sm lblPayableAmt" Text="0" ForeColor="Blue" BackColor="#DEE2E6"></asp:Label>
</div>
</div>
<div class="col-md-3">
<div class="form-group">
<label>Paid Amount</label>
<asp:TextBox ID="txtPaidAmt" runat="server" CssClass="form-control form-control-sm txtPaidAmt" OnTextChanged="CalculatePaidAmount" AutoPostBack="true" TabIndex="8" ForeColor="Blue" Text="0"></asp:TextBox>
</div>
</div>
<div class="col-md-3">
<div class="form-group">
<label>Balance Amount</label>
<div class="input-group input-group-sm">
<label id="lblBalAmt" runat="server" class="form-control form-control-sm lblBalAmt" style="color: red; background-color: #DEE2E6;">0</label>
<span class="input-group-append">
<asp:LinkButton ID="lnkPayable" runat="server" OnClick="ReCalculate" CssClass="btn btn-outline-success btn-flat" Text="" TabIndex="9" CausesValidation="false"><i class="fa fa-sync"></i></asp:LinkButton>
</span>
</div>
</div>
</div>
</div>
</div>
And my aspx.cs code:
protected void GetBillDetails()
{
string query = "select * from estimates where bno='" + Request.QueryString["bno"].ToString() + "';";
grdPurchaseBill.DataSource = dal.GetData(query);
grdPurchaseBill.DataBind();
using (SqlConnection con = new SqlConnection(cm.constring))
{
con.Open();
using (SqlCommand cmd = new SqlCommand(query, con))
{
using (SqlDataReader dr = cmd.ExecuteReader())
{
while (dr.Read())
{
txtBDate.Text = dr["bill_date"].ToString();
txtcname.Text = dr["name"].ToString();
txtcmobile.Text = dr["mobileno"].ToString();
txtcaddress.Text = dr["address"].ToString();
txtLorryFreight.Text = dr["lorry_freight"].ToString();
txtRemarks.Text = dr["remarks"].ToString();
lblTotal.Text = dr["grand_total"].ToString();
lblPayableAmt.Text = dr["payable_amount"].ToString();
txtPaidAmt.Text = dr["paid_amount"].ToString();
lblBalAmt.InnerText = dr["balance_amount"].ToString();
bno.InnerText = Request.QueryString["bno"].ToString();
}
}
}
con.Close();
}
}
protected void ReCalculate(object sender, EventArgs e)
{
decimal PayableAmount = 0, PaidAmount = !string.IsNullOrEmpty(txtPaidAmt.Text) ? Convert.ToDecimal(txtPaidAmt.Text) : 0, NetWeight = 0, SubTotal = 0, NetAmount = 0;
foreach (GridViewRow Row in grdPurchaseBill.Rows)
{
TextBox txtProduct = Row.FindControl("txtProduct") as TextBox;
TextBox txtWeight = Row.FindControl("txtWeight") as TextBox;
TextBox txtBags = Row.FindControl("txtBags") as TextBox;
TextBox txtShortagePercent = Row.FindControl("txtShortagePercent") as TextBox;
TextBox txtShortage = Row.FindControl("txtShortage") as TextBox;
TextBox txtNetWeight = Row.FindControl("txtNetWeight") as TextBox;
TextBox txtRate = Row.FindControl("txtRate") as TextBox;
TextBox txtSubTotal = Row.FindControl("txtSubTotal") as TextBox;
TextBox txtHamali = Row.FindControl("txtHamali") as TextBox;
TextBox txtHamaliAmount = Row.FindControl("txtHamaliAmount") as TextBox;
TextBox txtDriverCommission = Row.FindControl("txtDriverCommission") as TextBox;
TextBox txtNetAmount = Row.FindControl("txtNetAmount") as TextBox;
Control txtShortagePercent_ctrl = Row.FindControl("txtShortagePercent") as TextBox;
if (txtShortagePercent_ctrl != null)
{
txtShortage.Text = (Convert.ToDecimal(txtWeight.Text) - (Convert.ToDecimal(txtWeight.Text) - (Convert.ToDecimal(txtWeight.Text)) * (Convert.ToDecimal(txtShortage.Text) / 100))).ToString("#0.00");
//txtHamaliAmount.Text = (calculateHamali(Convert.ToDecimal(txtWeight.Text), Convert.ToDecimal(txtHamali.Text))).ToString("#0.00");
decimal TotalHamali = Convert.ToDecimal(txtHamali.Text) > 0 ? ((Convert.ToDecimal(txtWeight.Text) / 100) * Convert.ToDecimal(txtHamali.Text)) : 0;
NetAmount += ((Convert.ToDecimal(txtSubTotal.Text) - TotalHamali));// + Convert.ToDecimal(txtDriverCommission.Text)
txtNetAmount.Text = NetAmount.ToString("#0.00");
txtHamaliAmount.Text = TotalHamali.ToString("#0.00");
NetWeight += (Convert.ToDecimal(txtWeight.Text) - (Convert.ToDecimal(txtWeight.Text) * Convert.ToDecimal(txtShortage.Text) / 100));
txtNetWeight.Text = NetWeight.ToString("#0.00");
txtShortage.Text = (Convert.ToDecimal(txtWeight.Text) - (Convert.ToDecimal(txtWeight.Text) - (Convert.ToDecimal(txtWeight.Text) * Convert.ToDecimal(txtShortage.Text) / 100))).ToString();
SubTotal += (Convert.ToDecimal(txtNetWeight.Text) * Convert.ToDecimal(txtRate.Text));
txtSubTotal.Text = SubTotal.ToString("#0.00");
TextBox totamt = Row.FindControl("txtNetAmount") as TextBox;
PayableAmount += Convert.ToDecimal(!string.IsNullOrEmpty(totamt.Text) ? totamt.Text : "0");
}
}
lblTotal.Text = (PayableAmount).ToString("#0.00");
lblPayableAmt.Text = (PayableAmount - Convert.ToDecimal(!string.IsNullOrEmpty(txtLorryFreight.Text) ? txtLorryFreight.Text : "0")).ToString("#0.00");
lblBalAmt.InnerText = (PaidAmount > 0 ? Convert.ToDecimal(lblPayableAmt.Text) - PaidAmount : Convert.ToDecimal(lblPayableAmt.Text) - 0).ToString("#0.00");
}

Onclick event does not response in Update panel

I have a modal inside an update panel which give information of student when click on argument in a grid view.
In my modal I have also 3 textbox in which the value need to be save when click in save button.
It is not triggering the save button.
Here is my code:
<div class="modal fade" id="studinfo" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Student Info</h4>
<button type="button" class="close"
data-dismiss="modal">
×</button>
</div>
<div class="modal-body">
<asp:UpdatePanel ID="updModal" runat="server" ChildrenAsTriggers="false" UpdateMode="Conditional">
<ContentTemplate>
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
<div class="card h-100">
<div class="card-body">
<ul class="list-group list-group-flush">
<asp:TextBox ID="txtId" Visible="false" runat="server"></asp:TextBox>
<asp:Panel ID="typepannel" CssClass="list-group-item" runat="server">
<asp:Label ID="lbltype" runat="server"
Font-Bold="true" Text="Candidate Type: "></asp:Label>
<asp:Label ID="type" runat="server"
Text=''>
</asp:Label>
</asp:Panel>
<asp:Panel ID="colpanel" CssClass="list-group-item" runat="server">
<asp:Label ID="lblCol" runat="server"
Font-Bold="true" Text="College Attend: "></asp:Label>
<asp:Label ID="college" runat="server"
Text=''>
</asp:Label>
</asp:Panel>
<div class="list-group-item">
<asp:Label ID="lblName" runat="server"
Font-Bold="true" Text="Name: "></asp:Label>
<asp:Label ID="Name" runat="server"
Text=''>
</asp:Label>
</div>
<div class="list-group-item">
<asp:Label ID="lblNic" runat="server"
Font-Bold="true" Text="Nic: "></asp:Label>
<asp:Label ID="Nic" runat="server"
Text=''>
</asp:Label>
</div>
<div class="list-group-item">
<asp:Label ID="lblAge" runat="server"
Font-Bold="true" Text="Age: "></asp:Label>
<asp:Label ID="Age" runat="server"
Text=''>
</asp:Label>
</div>
<div class="list-group-item">
<asp:Label ID="lblAdress" runat="server"
Font-Bold="true" Text="Address: "></asp:Label>
<asp:Label ID="Address" runat="server"
Text=''>
</asp:Label>
</div>
<div class="list-group-item">
<asp:Label ID="lblacad" runat="server"
Font-Bold="true" Text="Academy: "></asp:Label>
<asp:Label ID="Academy" runat="server"
Text=''>
</asp:Label>
</div>
<h6 class="mt-3 mb-3">Parent in Charge</h6>
<div class="list-group-item">
<asp:Label ID="lblParent" runat="server"
Font-Bold="true" Text="Parent Name: "></asp:Label>
<asp:Label ID="parentName" runat="server"
Text=''>
</asp:Label>
</div>
<div class="list-group-item">
<asp:Label ID="lblNumber" runat="server"
Font-Bold="true" Text="Parent Contact Number: "></asp:Label>
<asp:Label ID="Number" runat="server"
Text=''>
</asp:Label>
</div>
<div class="list-group-item">
<asp:Label ID="lblEmail" runat="server"
Font-Bold="true" Text="Parent Email Address: "></asp:Label>
<asp:Label ID="Email" runat="server"
Text=''>
</asp:Label>
</div>
<div class="list-group-item">
<asp:Label ID="lblResult" runat="server"
Font-Bold="true" Text="Result: "></asp:Label>
<asp:DropDownList ID="ddlResult"
CssClass="select form-control"
runat="server">
</asp:DropDownList>
</div>
<div class="list-group-item">
<asp:Label ID="lblMarks" runat="server" Font-Bold="true" Text="Marks: "></asp:Label>
<asp:TextBox runat="server" ID="txtMarks"
CssClass="form-control form-control-lg" />
<asp:RequiredFieldValidator ID="rfvMarks" runat="server"
Display="Dynamic" ForeColor="Red"
ControlToValidate="txtMarks"
SetFocusOnError="true"
ErrorMessage="Marks is Mandatory">
</asp:RequiredFieldValidator>
<asp:CompareValidator ID="cmpVMarks" runat="server"
ControlToValidate="txtMarks"
Operator="DataTypeCheck"
Type="Double"
SetFocusOnError="true"
Display="Dynamic"
Text="Incorect data type"
ForeColor="Red"
ErrorMessage="Invalid">
</asp:CompareValidator>
<asp:RegularExpressionValidator ID="revPhone"
runat="server"
ControlToValidate="txtMarks"
SetFocusOnError="true"
Display="Dynamic"
ForeColor="Red"
ValidationExpression="^\d\d+(\.[1-9])?$"
ErrorMessage="Invalid">
</asp:RegularExpressionValidator>
</div>
<div class="list-group-item">
<asp:Label ID="lblpurcentage" runat="server"
Font-Bold="true" Text="Purcentage : "></asp:Label>
<asp:TextBox runat="server" ID="txtpur"
CssClass="form-control form-control-lg" />
<asp:RequiredFieldValidator
ID="rfvpur" runat="server"
Display="Dynamic" ForeColor="Red"
ControlToValidate="txtpur"
SetFocusOnError="true"
ErrorMessage="Purcentage is Mandatory">
</asp:RequiredFieldValidator>
<asp:CompareValidator ID="cvpur" runat="server"
ControlToValidate="txtpur"
Operator="DataTypeCheck"
Type="Double"
SetFocusOnError="true"
Display="Dynamic"
Text="Incorect data type"
ForeColor="Red"
ErrorMessage="Invalid">
</asp:CompareValidator>
</div>
</ul>
</div>
</div>
</ContentTemplate>
</asp:UpdatePanel>
<asp:Button ID="btnSave" OnClick="btnSave_Click"
CssClass="btn btn-success btn-block" runat="server" Text="Save" />
</div>
</div>
To make this data appear in modal I used updModal.Update(); in the button where I use to call the modal.
Here is my code behind of save button:
protected void btnSave_Click(object sender, EventArgs e)
{
try
{
string id = txtId.Text;
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "update tblStudent set stud_result=#res,stud_purcentage=#pur,stud_totalMarks=#marks where stud_Id=#id";
cmd.Parameters.AddWithValue("#id", id);
cmd.Parameters.AddWithValue("#res", ddlResult.SelectedValue);
cmd.Parameters.AddWithValue("#pur", txtpur.Text.Trim());
cmd.Parameters.AddWithValue("#marks", txtMarks.Text.Trim());
con.Open();
cmd.Connection = con;
updModal.Update();
}
catch (Exception ex)
{
ScriptManager.RegisterStartupScript(this, GetType(), "LaunchServerSide",
"$(function () { showUErrorModal(); });", true);
}
finally
{
con.Close();
}
}
When I have try to put the button inside the update panel it freeze the app when I triger the button.
Can someone please please help me with that? Thank you in advance.

AsyncFileUpload in Repeater in UpdatePanel

The AsyncFileUpload works. Only issue is the file name disappears when the LinkButton to repeat the AsyncFileUpload control is pressed. Is there a way to get and store the file name? FileName does not work. Not really keen on sharing code-behind but may do so if it is necessary to solve this issue.
<asp:UpdatePanel ID="LibraryResourceUpdatePanel" runat="server">
<ContentTemplate>
<div class="field-group list-of-resource">
<asp:Repeater ID="RptRequest" runat="server" OnItemDataBound="RptRequest_ItemDataBound">
<ItemTemplate>
<div class="resource">
<div class="remove-input">
<asp:LinkButton ID="LbRemoveRequest" CssClass="ic fa fa-minus-circle" runat="server" OnClick="LbRemoveRequest_Click" CausesValidation="false"></asp:LinkButton>
<span>Remove</span>
</div>
<h2>Details of Resources
<span class="counter">
<asp:Literal ID="LitCount" runat="server"></asp:Literal>
</span>
</h2>
<ul>
<li>
<fieldset class="form-group">
<legend>Accession No.</legend>
<asp:TextBox ID="TxbAccessionNumber" CssClass="form-control" runat="server" />
<asp:RequiredFieldValidator runat="server" ControlToValidate="TxbAccessionNumber" ErrorMessage="Email is required" ForeColor="Red" Display="Dynamic" />
</fieldset>
</li>
<li>
<fieldset class="form-group">
<legend>Details</legend>
<asp:TextBox ID="TxbDetails" runat="server" Rows="4" TextMode="MultiLine" />
<asp:RequiredFieldValidator runat="server" ControlToValidate="TxbDetails" ErrorMessage="Details are required" ForeColor="Red" Display="Dynamic" />
</fieldset>
</li>
<li>
<fieldset class="form-group">
<legend>Image</legend>
<ajaxToolkit:AsyncFileUpload runat="server"
ID="FileUpload" OnUploadedComplete="FileUpload_UploadedComplete" ClientIDMode="AutoID" PersistFile="true"/>
<asp:RequiredFieldValidator runat="server" ControlToValidate="FileUpload" ErrorMessage="File Upload required" ForeColor="Red" Display="Dynamic" />
</fieldset>
</li>
</ul>
</div>
</ItemTemplate>
</asp:Repeater>
</div>
<div class="add-input">
<asp:LinkButton ID="LbAddRequest" CssClass="ic fa fa-plus-circle" runat="server" OnClick="LbAddRequest_Click" CausesValidation="false" ></asp:LinkButton>
<span>Add another request</span>
</div>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="LbAddRequest" EventName="click" />
</Triggers>
</asp:UpdatePanel>
First add command name to linkbutton and remove click event:
<asp:LinkButton ID="LbAddRequest" runat="server"
CommandName="AddRequest"></asp:LinkButton>
<span>Add another request</span>
And try this ItemCommand event in code-behind to get in work:
protected void RptRequest_ItemCommand(object source, RepeaterCommandEventArgs e)
{
if (e.CommandName == "AddRequest")
{
FileUpload myFileUpload = (FileUpload)e.Item.FindControl("FileUpload");
if (myFileUpload.HasFile)
{
try
{
string filename = Path.GetFileName(myFileUpload.FileName);
myFileUpload.SaveAs(Server.MapPath("~/") + filename);
myStatusLabel.Text = "Upload Success";
}
catch (Exception ex)
{
myStatusLabel.Text = "Upload Fail" + ex.Message;
}
}
else
{
myStatusLabel.Text = "myFileUpload Has No File";
}
}
}
Read detail here : https://forums.asp.net/t/1904302.aspx?FileUpload+Inside+a+Repeater+Can+t+Find+File

Get TextBox Text value in a button

I'm trying to get the value of txt_MRP in the codebehind but it keeps giving me
The name "txt_MRP" doesn't exist in this current context
Why is this reference not available? How can I get it?
(The button that I am pressing is btn_add_to_cart_Click)
<div class="row">
<div class="col-lg-2"></div>
<div class="col-lg-4">
<asp:DataList ID="DataList3" runat="server" DataSourceID="SqlDataSource1">
<ItemTemplate>
<ul id="etalage">
<li>
<img id="Img1" class="etalage_thumb_image" runat="server" src='<%# Eval("Fotografia1") %>' />
<img id="Img2" class="etalage_source_image" runat="server" src='<%# Eval("Fotografia2") %>' />
</li>
</ul>
<br />
</ItemTemplate>
</asp:DataList>
</div>
<div class="col-lg-6">
<asp:DataList ID="DataList1" runat="server" DataKeyField="ID" DataSourceID="SqlDataSource1" >
<ItemTemplate>
<div id="product_name_width">
<asp:Label ID="Product_nameLabel" runat="server" CssClass="product_name" Text='<%# Eval("Nombre") %>' />
<br />
</div>
<span id="rs">₡</span><asp:Label ID="MRPLabel" CssClass="price" runat="server" Text='<%# Eval("Precio") %>' />
<br />
<br />
<span id="brand_name">Marca</span>
<asp:Label ID="BrandLabel" runat="server" CssClass="brand" Text='<%# Eval("Marca") %>' />
<br />
</div>
<div class="form-group">
<label> Cantidad </label>
<asp:TextBox CssClass="form-control" ID="txt_MRP" runat="server" ></asp:TextBox>
</div>
<div id="buy_now_css" runat="server">
<ul>
<li>
<asp:Button ID="btn_add_to_cart" CssClass="btn btn-primary" runat="server" Text="Añadir al Carrito" OnClick="btn_add_to_cart_Click" />
</li>
<li>
<asp:Button ID="btn_buy_now" CssClass="btn btn-success" runat="server" Text="Comprar" OnClick="btn_buy_now_Click" />
</li>
</ul>
</div>
</ItemTemplate>
</asp:DataList>
<asp:DataList ID="DataList2" runat="server" DataKeyField="ID" DataSourceID="SqlDataSource1">
<ItemTemplate>
<h2>Descripcion</h2>
<div id="Description_width">
<asp:Label ID="DetailLabel" CssClass="description" runat="server" Text='<%# Eval("Descripcion") %>' />
</div>
</ItemTemplate>
</asp:DataList>
</div>
</div>
txt_MRP does not exist because it is in a DataList Control. It is only available inside the scope of the Control.
If you want to get the value you have to use another method.
Change the button event from Onclick to OnCommand and add a CommandName and set the ItemIndex as CommandArgument.
<asp:Button ID="btn_add_to_cart" CommandName="addToCart" CommandArgument='<%# Container.ItemIndex %>' CssClass="btn btn-primary" runat="server" Text="Añadir al Carrito" OnCommand="btn_add_to_cart_Command" />
And in code behind
protected void btn_add_to_cart_Command(object sender, CommandEventArgs e)
{
//check the correct commandname
if (e.CommandName == "addToCart")
{
//get the row number from the commandargument
int itemIndex = Convert.ToInt32(e.CommandArgument);
//find the texbox in the correct row with findcontrol
TextBox textBox = DataList1.Items[itemIndex].FindControl("txt_MRP") as TextBox;
//do stuff with the value
Label1.Text = textBox.Text;
}
}
You have to assign the delegate or button. For instance:
var button = new Button();
button.Click += new EventHandler("btnAddToCart");
You also may need a CommandArgument, to be able to send a specific value back. But to actually register the click event would be like the above.

Button or link button event does not fire time to time

In my whole project I have several events and surprising thing is that sometime some event fire up and sometime doesnot.I don't know hat is going on. I have tried many option after seraching from google. Please someone help me. I am in very bad situation.
protected void btnSubmit_Click(object sender, EventArgs e)
{
try
{
if (Session["userid"] != null)
{
if (FileUpload1.HasFile)
{
string str = FileUpload1.FileName;
FileUpload1.PostedFile.SaveAs(Server.MapPath(".")
+ "//images//" + str);
string path = "~//images//" + str.ToString();
con.Open();
Label1.Text = "File uploaded successfully";
main addinfo = new main();
string Id = Request.QueryString["id"];
string SQL = "insert into
mandir(with_user,name,place,with_district,with_religion,
with_religion_category,description,photo)
values('" + Session["userid"] + "','" + txttemplename.Text.Trim()
+ "','" + txtaddress.Text.Trim() + "','" +
ddldistrict.SelectedItem.Value + "','" +
ddlreligion.SelectedItem.Value + "','" +
ddlreligioncategory.SelectedItem.Value +
"','" + txtdescription.Value + "','" + path + "')";
addinfo.saveData(SQL);
con.Close();
txttemplename.Text = "";
txtaddress.Text = "";
txtdescription.Value = "";
string message1 = "Thank you for providing the information";
Page.ClientScript.RegisterStartupScript(this.GetType(),
"Popup", "ShowPopup('" + message1 + "');", true);
// lblenquirymsg.Text = "";
}
else
{
Label1.Text = "File not uploaded successfully";
}
}
else
{
// lblinfo.Text = "You Must Login Or Register To give information";
string message = "You Must Login Or Register To Comment";
Page.ClientScript.RegisterStartupScript(this.GetType(),
"Popup", "ShowPopup('" + message + "');", true);
}
}
catch (Exception ex)
{
Console.WriteLine("{0} Exception caught.", ex);
}
<div class="weltext">
<h2>Add information</h2>
<div>
<div class="txt-st4" style="margin-bottom:8px; margin-top:10px;">Please fill the form below to provide information.</div>
<div style="padding:0px 0 10px 0;">
<form method="post">
<div style="margin-bottom:3px;"></div>
<div style="margin-bottom:7px;">
<div style="margin-bottom:3px;">Temple Name <span style="color:#F00">*<br />
</span><asp:TextBox ID="txttemplename" class="input_field1 verifyText" runat="server" style="margin-left: 0px" ></asp:TextBox>
</div>
<%-- <asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server"
ErrorMessage="please input alphabets." ControlToValidate="txtfullname"
ValidationExpression="^[a-zA-Z]+$" Height="19px" Width="165px"></asp:RegularExpressionValidator>--%>
<asp:RequiredFieldValidator ID="rfvtemplelname" runat="server"
ControlToValidate="txttemplename" ErrorMessage="*"></asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="revtemplelname" runat="server"
ControlToValidate="txttemplename" ErrorMessage="Only alphabets are allowed"
ForeColor="Red" ValidationExpression="^[a-zA-Z ]+$" > </asp:RegularExpressionValidator>
</div>
<div style="margin-bottom:4px;">
<div class="field required">
<div style="margin-bottom:3px;">
Address<span style="color:#F00">*<br /></span>
<asp:TextBox ID="txtaddress" class="input_field1 verifyText" runat="server" style="margin-left: 0px" ></asp:TextBox>
<asp:RequiredFieldValidator ID="rfvaddress" runat="server"
ControlToValidate="txtaddress" ErrorMessage="Please enter valid address"></asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="revaddress" runat="server"
ControlToValidate="txtaddress" ErrorMessage="Only alphabets are allowed"
ForeColor="Red" ValidationExpression="^[a-zA-Z ]+$" > </asp:RegularExpressionValidator>
</div>
</div>
</div>
<div style="margin-bottom:4px;">
<div class="field required">
<div style="margin-bottom:3px;"> Choose district <span style="color:#F00">*<br />
</span><asp:DropDownList ID="ddldistrict" runat="server" class="input_field1 verifyText" OnLoad="ddldistrict_Load" style="margin-left: 0px"></asp:DropDownList></div><div style="margin-bottom:4px;">
<div class="field required">
<br />
</div></div>
<div style="margin-bottom:3px;"> Choose religion<span style="color:#F00">*<br />
</span><asp:DropDownList ID="ddlreligion" class="input_field1 verifyText" runat="server" OnLoad="ddlreligion_Load" style="margin-left: 0px"></asp:DropDownList></div><div style="margin-bottom:4px;">
<div class="field required">
<br />
</div></div>
<div style="margin-bottom:3px;"> Choose religion category <span style="color:#F00">*<br />
</span><asp:DropDownList ID="ddlreligioncategory" class="input_field1 verifyText" runat="server" OnLoad="ddlreligioncategory_Load" style="margin-left: 0px" ></asp:DropDownList>
</div><div style="margin-bottom:4px;">
<div class="field required">
<br />
</div></div>
<%--<asp:RegularExpressionValidator ID="RegularExpressionValidator2" runat="server"
ErrorMessage="please input alphabets." ControlToValidate="txtaddress"
ValidationExpression="^[a-zA-Z]+$" Height="19px" Width="165px"></asp:RegularExpressionValidator>--%>
</div>
</div>
<div style="margin-bottom:3px;">Description<span style="color:#F00">*</span></div>
<div style="margin-bottom:4px;">
<div class="field required">
<textarea id="txtdescription" runat="server" name="description" class="text_area" style="width: 532px; height: 180px"></textarea>
<%-- <asp:RequiredFieldValidator ID="rfvdescription" runat="server" ControlToValidate="txtdescription"
ErrorMessage="*" InitialValue="Select"></asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="revdescription" Runat="server"
ErrorMessage="ERROR: Please enter a valid description<br/>" SetFocusOnError="true" Display="Dynamic"
ControlToValidate="txtdescription" ValidationGroup="MandatoryContent"
ValidationExpression="^[A-Za-z'\-\p{L}\p{Zs}\p{Lu}\p{Ll}\']+$"
ForeColor="Red"></asp:RegularExpressionValidator>--%>
</div>
</div>
Choose picture:<br />
<asp:FileUpload ID="FileUpload1" runat="server" style="margin-left: 0px" /><br />
<%-- <asp:Button ID="Button1" runat="server" Text="Upload Image" onclick="Button1_Click" /><br >--%>
<br />
<span style="color:#F00">
<asp:Label ID="Label1" runat="server" Text="Label" Visible="False"></asp:Label>
<span style="color:#F00">
<div id="dialog" style="display: none">
</div>
<asp:Button id="btnSubmit" Text="Submit " runat="server" class="btn" OnClick="btnSubmit_Click" />
<%--<asp:Button ID="btnSubmit" Text="Submit" runat="server" value="Submit Now" class="btn" CausesValidation="False" style="margin-left: 13px" OnClick="btnSubmit_Click" />--%>
<br />
</span>
</span>
<br />
<div>
<%-- <asp:Button ID="btnReset" Text="Reset Form" runat="server" value="Reset Form" class="btn" OnClick="btnReset_Click" />--%>
<asp:Label ID="lblenquirymsg" runat="server"></asp:Label>
</div>
</form>
</div>
</div>
<p>
<asp:Label ID="lblenquirymsg1" runat="server"></asp:Label>
</p>
The above event is also not firing.

Categories

Resources