AsyncFileUpload in Repeater in UpdatePanel - c#

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

Related

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.

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.

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

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.

asp button doesn't invoke postback in usercontrol updatepanel

I have two asp buttons in my user control inside an update panel. But when I click them the postback is not completed (I have a java script alert set to page_load to tell me when a post back occurs, for example, it fires when the dropdownlist selection is changed). I can't figure out why the buttons are not posting back.
My usercontrol, the buttons in question are createBtn and signinBtn.
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="Login.ascx.cs" Inherits="TestApp2.Views.Login" %>
<asp:UpdatePanel ID="LoginMainUpdatePanel" runat="server" UpdateMode="Conditional" OnUnload="UpdatePanel_Unload">
<ContentTemplate>
<asp:TextBox ID="infoTB" runat="server" TextMode="MultiLine" />
<div>
<div class="left-align" style="background-color:blue">
<asp:button runat="server" id="createBtn" CssClass="btn btn-default" OnClick="createBtn_Click" Text="Create" /><br/>
<asp:button runat="server" id="signinBtn" CssClass="btn btn-default" OnClick="signinBtn_Click" Text="Sign In" />
</div>
<!-- Login View -->
<div id="loginView" runat="server" class="centre-form centering text-center" style="background-color:green">
<h1>Login</h1>
<asp:Label ID="info" runat="server" Text="" />
<div class="form-group">
<label for="userIn">Username</label>
<asp:TextBox runat="server" id="userIn" CssClass="form-control" TextMode="SingleLine" />
<asp:RequiredFieldValidator runat="server" id="reqUser" controltovalidate="userIn" errormessage="Enter Username" />
</div>
<div class="form-group">
<label for="passwordIn">Password</label>
<asp:TextBox runat="server" id="passwordIn" CssClass="form-control" Text="Enter Password" TextMode="Password" />
<asp:RequiredFieldValidator runat="server" id="reqPass" controltovalidate="passwordIn" errormessage="Enter Password" />
</div>
<asp:Button runat="server" id="loginBtn" CssClass="btn btn-default" onclick="loginBtn_Click" text="Login" />
</div>
<!-- Create Account View -->
<div id="createView" runat="server" class="centre-form centering text-center" style="background-color:green">
<h1>Create</h1>
<div class="form-horizontal">
<div class="form-group" style="background-color:yellow;">
<asp:TextBox runat="server" id="personalFName" CssClass="form-control" TextMode="SingleLine" />
<label class="control-label" for="personalFName">First Name</label>
</div>
<div class="form-group">
<asp:TextBox runat="server" id="personalLName" CssClass="form-control" TextMode="SingleLine" />
<label class="control-label" for="personalLName" >Last Name</label>
</div>
<div class="form-group">
<asp:DropDownList runat="server" id="selGender" CssClass="form-control">
<asp:ListItem Value="Male" Text="Male" />
<asp:ListItem Value="Female" Text="Female" />
<asp:ListItem Value="Other" Text="Other" />
</asp:DropDownList>
<label class="control-label" for="selGender">Gender</label>
</div>
<asp:UpdatePanel ID="dobUpdatePanel" runat="server" UpdateMode="Conditional" OnUnload="UpdatePanel_Unload">
<ContentTemplate>
<div class="form-group">
<asp:DropDownList runat="server" id="selYear" CssClass="form-control" OnSelectedIndexChanged="selYear_SelectedIndexChanged" AutoPostBack="true" />
<asp:DropDownList runat="server" id="selMonth" CssClass="form-control" OnSelectedIndexChanged="selMonth_SelectedIndexChanged" AutoPostBack="true" />
<asp:DropDownList runat="server" id="selDay" CssClass="form-control"/>
<label class="control-label" for="selDay" >Date of Birth</label>
</div>
</COntentTemplate>
</asp:UpdatePanel>
</div>
</div>
</div>
</ContentTemplate>
</asp:UpdatePanel>
The code behind is as so
public partial class Login : System.Web.UI.UserControl
{
private DateMenu dobCtrl;
protected void Page_Load(object sender, EventArgs e)
{
if (Session[Paths.USERDETAILS] != null) Response.Redirect(Paths.USERCTRL_BASE + "Profile.ascx");
else setDetails();
}
protected void loginBtn_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
String SOAPbdy = "<Username>" + userIn.Text + "</Username><Password>" + passwordIn.Text + "</Password>";
HTTPRequest req = new HTTPRequest();
String response = req.HttpSOAPRequest(SOAPbdy, "GetUser");
infoTB.Text += response;
String uIDs = (new XMLParse(response)).getElementText("UserID");
int uID = 0;
Int32.TryParse(uIDs, out uID);
if (uID > 0)
{
Session["userDetails"] = response;
info.Text = "Success";
}
else info.Text = "Login failed";
}
}
private void setDetails()
{
if (dobCtrl == null) dobCtrl = new DateMenu(selYear, selMonth, selDay);
dobCtrl.setDateDropdown();
}
protected void UpdatePanel_Unload(object sender, EventArgs e)
{
MethodInfo methodInfo = typeof(ScriptManager).GetMethods(BindingFlags.NonPublic | BindingFlags.Instance)
.Where(i => i.Name.Equals("System.Web.UI.IScriptManagerInternal.RegisterUpdatePanel")).First();
methodInfo.Invoke(ScriptManager.GetCurrent(Page),
new object[] { sender as UpdatePanel });
}
protected void selYear_SelectedIndexChanged(object sender, EventArgs e)
{
dobCtrl.fillDays();
}
protected void selMonth_SelectedIndexChanged(object sender, EventArgs e)
{
dobCtrl.fillDays();
}
protected void createBtn_Click(object sender, EventArgs e)
{
loginView.Visible = false;
}
protected void signinBtn_Click(object sender, EventArgs e)
{
}
}
I believe you have to register the controls for postback using
ScriptManager.RegisterPostbackControl()
https://msdn.microsoft.com/en-us/library/system.web.ui.scriptmanager.registerpostbackcontrol%28v=vs.110%29.aspx
Try setting up the triggers for the UpdatePanel like so:
<asp:UpdatePanel ID="LoginMainUpdatePanel" runat="server" UpdateMode="Conditional" OnUnload="UpdatePanel_Unload">
<ContentTemplate>
<asp:TextBox ID="infoTB" runat="server" TextMode="MultiLine" />
<div>
<div class="left-align" style="background-color:blue">
<asp:button runat="server" id="createBtn" CssClass="btn btn-default" OnClick="createBtn_Click" Text="Create" /><br/>
<asp:button runat="server" id="signinBtn" CssClass="btn btn-default" OnClick="signinBtn_Click" Text="Sign In" />
</div>
[...]
</div>
</ContentTemplate>
<Triggers>
<asp:PostBackTrigger ControlID="createBtn" />
<asp:PostBackTrigger ControlID="signinBtn" />
</Triggers>
</asp:UpdatePanel>
Try adding PostBackTriggers for the UpdatePanel.
Add 2 triggers one for each of the buttons.
<asp:UpdatePanel ID="myUpdatePanel" runat="server" UpdateMode="Conditional"ChildrenAsTriggers="false">
<ContentTemplate>
//Your Content
</ContentTemplate>
<Triggers>
<asp:PostBackTrigger ControlID="createBtn" />
<asp:PostBackTrigger ControlID="Signbtn" />
</Triggers>
</asp:UpdatePanel>
It was because of the asp form validation, no postback (async or not) was occurring because the form wasn't valid. Removing that made it all work.

Access TextBox in DataList by ID from Button-Click handler in codebehind

I have a textbox which is kept inside Datalist. I need to find it via ID, so that i can insert text written to that textbox to the database.Here is my aspx page containing textbox.
<asp:Content ID="Content1" ContentPlaceHolderID="ccont" Runat="Server">
<div id="ccont">
<asp:DataList ID="mydatalist" ItemStyle-CssClass="lft_c_down" runat="server">
<ItemTemplate>
<div id="wholeC">
<div id="ctop">
<div id="lft_l">
<div id="lft_c_top">
<asp:Image runat="server" ImageUrl='<%#DataBinder.Eval(Container.DataItem,"ipath")%>' Height="250px" Width="300px" />
<br/>
</div>
<div id="lft_c_down">
<b>Product Name:</b>
<asp:Label ID="lbl2" Text='<%#DataBinder.Eval(Container.DataItem,"products") %>' runat="server" />
<br/>
<b>brand:</b>
<asp:Label ID="lbl1" Text='<%#DataBinder.Eval(Container.DataItem,"brand") %>' runat="server" />
<br/>
<b>Price:</b>
<asp:Label ID="Label1" Text='<%#DataBinder.Eval(Container.DataItem,"price") %>' runat="server" />
</div>
</div>
<div id="lft_r">
<b>Details:</b>
<asp:Label ID="Label2" Text='<%#DataBinder.Eval(Container.DataItem,"description") %>' runat="server" />
</div>
</div>
<div id="cmt">
<asp:TextBox ID="tb_cmt" runat="server" Height="35px" Width="620" placeholder="comment.." />
<asp:Button ID="Button1" runat="server" Text="Comment" backcolor="black" BorderStyle="None" Font-Names="Consolas" Font-Overline="False"
ForeColor="White" Height="34px" Width="108px" OnClick="cmt_Click" />
</div>
</div>
</ItemTemplate>
</asp:DataList>
</div>
The Textbox with ID="tb_cmt" is the text box i want to access in my code behind as:
protected void cmt_Click(object sender, EventArgs e)
{
// how to get the TextBox?
sq.connection();
SqlCommand cmd = new SqlCommand("insert into comment(ecomment,sid) values(#myecomment,#mysid)", sq.con);
cmd.Parameters.AddWithValue("#myecomment",tb_cmt.text)//but here tb_cmt is not recognized.
}
You can use the NamingContainer property of the button that was clicked to get the DataListItem. Then you just have to use FindControl to get the reference to your TextBox:
protected void cmt_Click(object sender, EventArgs e)
{
Button btn = (Button) sender;
DataListItem item = (DataListItem) btn.NamingContainer;
TextBox txt = (TextBox) item.FindControl("tb_cmt");
//... save
}

Categories

Resources