C# Dynamically filled DropDownList resets on button OnClick - c#

I am having a bit of a DUH moment and need some help. I have a DropDownList control that gets filled with values on page load and a submit button that does further manipulations. However, when the button is clicked DropDownList returns a value of "-1" and not of the selected option. What is wrong here?
Web page:
<%# Page Language="C#" MasterPageFile="/new/MasterPageA2.master" EnableEventValidation="false" AutoEventWireup="true" CodeFile="Checkout.aspx.cs" Inherits="Common_Checkout" EnableViewState="true" %>
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">
<asp:UpdatePanel ID="UpdatePanel" runat="server">
<ContentTemplate>
<asp:Label runat="server" ID="test11"></asp:Label>
<asp:DropDownList ID="ddlbillingcountry" required="true" EnableViewState="true" runat="server"></asp:DropDownList>
<asp:Button ID="ImageButton1" AlternateText="Proceed" OnClick="ImageButton1_Click" CausesValidation="false" runat="server" />
</ContentTemplate>
</asp:UpdatePanel>
<asp:UpdateProgress ID="UpdateProgress1" runat="server">
<ProgressTemplate>
<p>Loading...</p>
</ProgressTemplate>
</asp:UpdateProgress>
</asp:Content>
Code behind:
protected void Page_Load(object sender, EventArgs e) {
if (!IsPostBack) {
PopulateCountry(ddlbillingcountry);
}
}
private void PopulateCountry(DropDownList Controlname) {
DatasetTableAdapters.CountryTableAdapter _CountryTableAdapter = new DatasetTableAdapters.CountryTableAdapter();
Controlname.ClearSelection();
Controlname.Items.Clear();
DataTable _DataTable = _CountryTableAdapter._Eco_Country_Select();
Controlname.DataSource = _DataTable;
Controlname.DataTextField = "CountryName";
Controlname.DataValueField = "Country";
Controlname.DataBind();
Controlname.Items.Insert(0, new ListItem("- Select Country -", ""));
}
protected void ImageButton1_Click(object sender, EventArgs e) {
test11.Text += "<p>clicked " + ddlbillingcountry.SelectedIndex + " - " + ddlbillingcountry.SelectedValue.ToString();
}

You could set the datasource property to the name of a function which returns a dataset.
Try datasource='<%# PopulateCountry("ddlbillingcountry") %>' but you will need to change or overload the function to change the argument to a string, remembering to set the datavaluefield and datatextfield.Or you may want to create a separate function and call that with no arguments.

Related

Read textBox from dynamically created

I am trying to create a textbox dynamically using a string. and then trying to read on a buttton click.
<%# Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="textboxtest.aspx.cs" Inherits="test2.textboxtest" %>
<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<div id="TextBoxDiv" runat="server" class="asid box">
</div>
<asp:Button ID="Button1" runat="server" Text="CreateTextBox" onclick="Button1_Click" />
<asp:Button ID="Button2" runat="server" Text="ReadTextBox" onclick="Button2_Click" />
</asp:Content>
Here is the code behind.
protected void Button1_Click(object sender, EventArgs e)
{
string finalText = #"<input type=""text"" ID=""T1"" runat=""server"">
<asp:TextBox ID=""TB1"" runat=""server""></asp:TextBox>";
TextBoxDiv.InnerHtml = finalText;
}
protected void Button2_Click(object sender, EventArgs e)
{
TextBox txtAddress2 = (TextBox)Page.FindControl("TB1");
foreach (Control c in TextBoxDiv.Controls)
{
if (c is TextBox)
{
TextBox txt = (TextBox)c;
string str = txt.Text;
}
}
}
As you can see from the code i have tried to access the textbox using find control and also looping through. but both are failing.
I managed to get it to work, but by only having to create dynamic textboxes in Page_Init event. So every time there is a post back you need to re-create your dynamic controls. You can check online, they say the same thing.
So here is the client side:
<asp:PlaceHolder runat="server" id="TextBoxesHere" />
<asp:Button ID="Button1" CssClass="btn btn-primary btn-outline" runat="server"
Text="CreateTextBox" OnClick="Button1_Click" />
<asp:Button ID="Button2" CssClass="btn btn-primary btn-outline" runat="server"
Text="ReadTextBox" OnClick="Button2_Click" />
Server Side:
protected void Page_Init(object sender, EventArgs e)
{
TextBox txt = new TextBox();
txt.ID = "T1";
txt.CssClass = "form-control";
TextBoxesHere.Controls.Add(txt);
}
protected void Button1_Click(object sender, EventArgs e)
{
TextBox txt = new TextBox();
txt.ID = "T1";
txt.CssClass = "form-control";
TextBoxesHere.Controls.Add(txt);
}
protected void Button2_Click(object sender, EventArgs e)
{
TextBox txt = (TextBox)TextBoxesHere.FindControl("T1");
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "", "alert('" + txt.Text + "');", true);
}
use a Placeholder instead of a div (it will generate a div) and then add controls in the placeholder instead of using InnerHtml.
So this can be achieved like this:
<%# Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="textboxtest.aspx.cs" Inherits="test2.textboxtest" %>
<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="server"></asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<asp:PlaceHolder runat="server" ID="TextBoxPlaceHolder"></asp:PlaceHolder>
<asp:Button ID="Button1" runat="server" Text="CreateTextBox" onclick="Button1_Click" />
<asp:Button ID="Button2" runat="server" Text="ReadTextBox" onclick="Button2_Click" />
</asp:Content>
Code-behind:
protected void Button1_Click(object sender, EventArgs e)
{
string finalText = #"<input type=""text"" ID=""T1"" runat=""server"">";
var textbox = new TextBox();
textbox.ID = "TB1";
this.TextBoxPlaceHolder.Controls.Add(new LiteralControl(finalText));
this.TextBoxPlaceHolder.Controls.Add(textbox);
}
protected void Button2_Click(object sender, EventArgs e)
{
TextBox txtAddress2 = (TextBox)Page.FindControl("TB1");
foreach (Control c in TextBoxDiv.Controls)
{
if (c is TextBox)
{
TextBox txt = (TextBox)c;
string str = txt.Text;
}
}
}

LinkButton OnClick() doesnt hit the srcipt function

In my aspx page, I has a Linkbutton linkbtTitle inside a Repeater Control:
<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" Runat="Server">
<script runat="server">
protected void Buttonlink_Click(object sender, System.EventArgs e)
{
LinkButton linkbtTitle = (LinkButton)sender;
linkbtTitle.ForeColor = System.Drawing.Color.HotPink;//change color when selected
linkbtTitle.Font.Underline = true;
linkbtTitle.Font.Italic = true;
}
</script>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" Runat="Server">
<asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server" />
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:Repeater ID="Repeater1" runat="server">
<ItemTemplate>
<asp:LinkButton ID="linkbtTitle" runat="server" Text='<%#Eval("TITLE")%>' CommandArgument='<%#Eval("ID")%>' OnCommand="linkbtTitle_Click" OnClick="Buttonlink_Click" ></asp:LinkButton>
</ItemTemplate>
</asp:Repeater>
</ContentTemplate>
</asp:UpdatePanel>
</asp:Content>
I use method OnCommand="linkbtTitle_Click" to auto download attachment when client click on Linkbutton and OnClick="Buttonlink_Click" to change color of selected Linkbutton.
When I built this page, the attachment is downloaded automatically but the Selected LinkButton doesnt change its color.
Try to debug, function Buttonlink_Click() is not called, it has an message: Expression Statement is not assignment or call when hovering mouse on statement: ... OnClick="Buttonlink_Click" ...
I wonder if there is some problem in linkbtTitle_Click Please take a look at my code behind:
public void linkbtTitle_Click(object sender, CommandEventArgs e)
{
//auto download the attachment when selected
int mamd = Convert.ToInt32(e.CommandArgument.ToString());
string sql = "select * from MAU_DON where MA_MAU_DON="+mamd;
DataTable maudon = l.EXECUTEQUERYSQL(sql);
string attachment = dirPath["MAU_DON"].DIRECTORY + #"/" + maudon.Rows[0]["PATH"].ToString();
HttpContext.Current.Response.ContentType = "application/octet-stream";
HttpContext.Current.Response.AddHeader("Content-Disposition",
"attachment; filename=" + Path.GetFileName(attachment));
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.WriteFile(attachment);
HttpContext.Current.Response.End();
}
It will not hit the server side function. The eventing mechanism is slightly altered when a control like linkbutton or even a normal button itself is used in the item template. Instead of the onclick event firing, an event on the repeater will fire...its called ItemCommand. This happens via a mechanism called event bubbling.
To know which button caused it, you need to use the CommandName and CommandArgument.
<asp:LinkButton ID="lnkbtn" runat="server" CommandName="foo" CommandArgument="<%# Eval ("Id") %>" Text="FooBtn" />
In the code behind, the repeater's item command event, we write something like
if (e.CommandName == "foo")
{
// so we know what button triggered this
// access the value of e.CommandArgument to get associated row data.
}

ValidationSummary in MasterPage hide success label

I've got a ValidationSummary and SuccessLabel in the MasterPage
When the SuccessLabel has detail in it, and then the ValidationSummary then fails validation I want it to hide the SuccessLabel and only show the ValidationSummary.
<div id="ApplicationStatus" class="ValidationSummaryContainer">
<asp:Label ID="StatusLabel" CssClass="SuccessSummary" runat="server"
Visible="false"></asp:Label>
<asp:Label ID="WarningLabel" CssClass="WarningSummary" runat="server"
Visible="false"></asp:Label>
<asp:ValidationSummary ID="ErrorValidationSummary" runat="server"
CssClass="ValidationSummary" DisplayMode="List" />
<asp:CustomValidator ID="ErrorCustomValidator" runat="server"></asp:CustomValidator>
</div>
<div id="ApplicationContent" class="ApplicationContentContainer">
<asp:ContentPlaceHolder ID="MainContent" runat="server">
</asp:ContentPlaceHolder>
</div>
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
StatusLabel.Text = "Successfully loaded record";
}
}
<asp:Content ID="Content1" ContentPlaceHolderID="MainContentPlaceHolder" runat="server">
<asp:Textbox ID = "Text1" runat="server"/>
<asp:RequiredFieldValidator id="InputTextBoxRequiredFieldValidator" runat="server"
ControlToValidate="Text1" Visible="false" CssClass="InlineNoWrap" Enabled="true">
</asp:RequiredFieldValidator>
<asp:Button ID = "Button1" runat="server" Text="Submit"/>
</asp:Content>
I'm trying to find a way in JavaScript to catch the validation error and hide the StatusLabel.
I don't want to have to put a javascript function on every button on every page that uses the MasterPage.
Thanks,
Alex
How about something like this:
protected void Submit(object sender, EventArgs e)
{
if (IsValid)
{
StatusLabel.Visible = true;
}
else
{
StatusLabel.Visible = false;
}
}
Your validation code are totally miss lot of fields.
ok now we are going your pint .
Set visible false in your label for page load event
then success time add the label text ,and set visible true
you miss control to validate and validationgroup and display fields
please see this sample

updatepanel and javascript include file

I have found many solution for my issue but none doesn't work in my scenario.
I have created a test project to demo my concept.
Basically, there is a page that host a user control...
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<div>
<uc1:WebUserControl1 ID="WebUserControl11" runat="server" />
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
<br />
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
</div>
</form>
WebUserControl1 has a dropdownlist and two other webusercontrols (to be displayed based on the selection of dropdownlist element) inside updatepanel as below.
<%# Register Src="WebUserControl2.ascx" TagName="WebUserControl2" TagPrefix="uc2" %>
<%# Register Src="WebUserControl3.ascx" TagName="WebUserControl3" TagPrefix="uc3" %>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:DropDownList ID="DropDownList1" runat="server"
OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged"
AutoPostBack="True">
</asp:DropDownList>
<asp:Panel ID="pnlCreditCard" Visible="false" runat="server">
<uc2:WebUserControl2 ID="WebUserControl21" runat="server" />
</asp:Panel>
<asp:Panel ID="pnlGiftCard" Visible="false" runat="server">
<uc3:WebUserControl3 ID="WebUserControl31" runat="server" />
</asp:Panel>
</ContentTemplate>
</asp:UpdatePanel>
Code behind file for WebUserControl1 is .....
public enum PaymentMethod
{
CreditCard = 0,
GiftCard
}
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
BindPaymentMethods(Enum.GetValues(typeof(PaymentMethod)));
}
private void BindPaymentMethods(Array paymentMethods)
{
DropDownList1.DataSource = paymentMethods;
DropDownList1.DataBind();
if (paymentMethods.Length > 0)
{
DropDownList1.SelectedIndex = 0;
UpdateCreditOrGiftCardPanelVisibility();
}
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
UpdateCreditOrGiftCardPanelVisibility();
}
private void UpdateCreditOrGiftCardPanelVisibility()
{
if(DropDownList1.SelectedValue == Enum.GetName(typeof(PaymentMethod),PaymentMethod.CreditCard))
{
pnlGiftCard.Visible = false;
pnlCreditCard.Visible = true;
}
else if (DropDownList1.SelectedValue == Enum.GetName(typeof(PaymentMethod), PaymentMethod.GiftCard))
{
pnlCreditCard.Visible = false;
pnlGiftCard.Visible = true;
}
}
Now, the problem starts here...There is an external javascript file [JScript1.js] (embedded resource) which basically is used to display an alert box.
<script language="javascript" type="text/javascript">
window.onload = function() {
alert('creditcard form');
}
WebUserControl2.ascx.cs code behind is
protected void Page_Load(object sender, EventArgs e)
{
ScriptManager.RegisterClientScriptInclude(this.Page, this.Page.GetType().BaseType, "JScript1", Page.ClientScript.GetWebResourceUrl(this.Page.GetType().BaseType, "WebApplication1.JScript1.js"));
}
Alert window doesn't get displayed when I change the dropdownlist value. Even the script is getting registered three times (look in the firebug)
Need to use ScriptInclude instead of ScriptBlock as the original JS file is too big.
Can email the test app....
Thanks in Advance
After working around a bit, I found the solution.
I registered a ScriptManagerProxy in WebUserControl2.ascx
<asp:ScriptManagerProxy ID="ScriptManager1" runat="server" >
<Scripts>
<asp:ScriptReference Assembly="WebApplication1" Name="WebApplication1.JScript1.js" />
</Scripts>
</asp:ScriptManagerProxy>
Then on the code behind of the same control, added...
protected override void OnPreRender(EventArgs e)
{
base.OnPreRender(e);
ScriptManager.RegisterStartupScript(this, GetType(), "test", "doSomething();", true);
}
and the JScript1.js file looks like below.
function doSomething() {
alert('via dosomething control2 form');
}
Hope that helps. Though I had to litter around more in my practical scenario but this was certainly the way I got it working.
Thanks,

Recaptcha in Updatepanel disappears during PostBack

I am using Google ReCaptcha V2 and it is inside an updatepanel. IF validation failed ReCaptcha disappears on postback.
I read similar topics but I have not yet found an answer that solves my problem.
Please help!
My ASPX code :
<%# Register Assembly="GoogleReCaptcha" Namespace="GoogleReCaptcha" TagPrefix="cc1" %>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<form id="formRegister" runat="server">
<asp:ScriptManager ID="ScriptManagerRegister" EnablePartialRendering="true" runat="server"></asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanelRegister" hildrenAsTriggers="false" UpdateMode="Conditional" runat="server">
<ContentTemplate>
<asp:Panel ID="Panel1" runat="server"></asp:Panel>
<asp:Button ID="ButtonRegister" runat="server" Text="Registrera" CssClass="btn btn-primary btn-md" /><br />
<asp:Label ID="Label1" runat="server" Text=""></asp:Label>
</asp:Panel>
</ContentTemplate>
</asp:UpdatePanel>
</form>
</asp:Content>
My code behind C#
GoogleReCaptcha.GoogleReCaptcha ctrlGoogleReCaptcha = new GoogleReCaptcha.GoogleReCaptcha();
protected override void CreateChildControls()
{
base.CreateChildControls();
ctrlGoogleReCaptcha.PublicKey = "My Public Key";
ctrlGoogleReCaptcha.PrivateKey = "My Private Key";
this.Panel1.Controls.Add(ctrlGoogleReCaptcha);
}
protected void Page_Load(object sender, EventArgs e)
{
ButtonRegister.Click += new EventHandler(ButtonRegister_Click);
}
protected void ButtonRegister_Click(object sender, EventArgs e)
{
if (ctrlGoogleReCaptcha.Validate())
{
//submit form
Label1.Text = "Success";
}
else
{
Label1.Text = "Captcha Failed!! Please try again!!";
}
}
use this script after body
<body>
<script language="javascript" type="text/javascript">
function pageLoad()
{
$('.g-recaptcha').each(function (index, obj) {
grecaptcha.render(obj, { 'sitekey': 'yoursitekey' });
});
}
</script>

Categories