The OnSelectedIndexChanged event is not firing for my dropdown box. All forums I have looked at told me to add the AutoPostBack="true", but that didn't change the results.
HTML:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="Label1" runat="server" Text="Current Time: " /><br />
<asp:Label ID="lblCurrent" runat="server" Text="Label" /><br /><br />
<asp:DropDownList ID="cboSelectedLocation" runat="server" AutoPostBack="true" OnSelectedIndexChanged="cboSelectedLocation_SelectedIndexChanged" /><br /><br />
<asp:Label ID="lblSelectedTime" runat="server" Text="Label" />
</div>
</form>
</body>
</html>
Code behind:
public partial class _Default : Page
{
string _sLocation = string.Empty;
string _sCurrentLoc = string.Empty;
TimeSpan _tsSelectedTime;
protected void Page_Load(object sender, EventArgs e)
{
AddTimeZones();
cboSelectedLocation.Focus();
lblCurrent.Text = "Currently in " + _sCurrentLoc + Environment.NewLine + DateTime.Now;
lblSelectedTime.Text = _sLocation + ":" + Environment.NewLine + DateTime.UtcNow.Add(_tsSelectedTime);
}
//adds all timezone displaynames to combobox
//defaults combo location to seoul, South Korea
//defaults current location to current location
private void AddTimeZones()
{
foreach(TimeZoneInfo tz in System.TimeZoneInfo.GetSystemTimeZones())
{
string s = tz.DisplayName;
cboSelectedLocation.Items.Add(s);
if (tz.StandardName == "Korea Standard Time") cboSelectedLocation.Text = s;
if (tz.StandardName == System.TimeZone.CurrentTimeZone.StandardName) _sCurrentLoc = tz.StandardName;
}
}
//changes timezone name and time depending on what is selected in the cbobox.
protected void cboSelectedLocation_SelectedIndexChanged(object sender, EventArgs e)
{
foreach (TimeZoneInfo tz in System.TimeZoneInfo.GetSystemTimeZones())
{
if (cboSelectedLocation.Text == tz.DisplayName)
{
_sLocation = tz.StandardName;
_tsSelectedTime = tz.GetUtcOffset(DateTime.UtcNow);
}
}
}
}
Any advice into what to look at for a rookie asp coder?
EDIT: added more code behind
Graham Clark was correct in needing the !Page.IsPostBack, but it is now something with the global variables that I set. This code was dragged and dropped from a c# project, so I assume there is some issues with global variables and asp.net. Time for me to do more research on this to understand how global variables differ in a standalone as opposed to a web program.
Are you databinding your drop-down list every trip back to the server, or just on a postback? If you're doing it every time, it could be that the server doesn't think anything has been selected, therefore the event won't fire.
Say you're databinding the drop-down in the Page_Load event. You want to do it like this:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
// bind drop-down list here
}
}
Related
Hi i am busy creating a asp.net project that needs to get three values from the user. I am using a textbox with a range textmode to get these values and the first time the user moves the slider it works perfectly but after that the user can.t adjust any of the textboxes anymore.
I tried using a slider extender but this does not seem to work and only a textbox shows.
my html code to create the textboxes and labels showing the value
body>
<form id="form1" runat="server">
<p>
Quantum 1 Length:
<asp:TextBox ID="txtVal1" runat="server" TextMode="Range" min="1" Max="8" OnTextChanged="txtVal1_TextChanged1" AutoPostBack="True"></asp:TextBox>
<asp:Label ID="lblVal1" runat="server" Text="/////"></asp:Label>
</p>
<p>
Quantum 2 Length:
<asp:TextBox ID="txtVal2" runat="server" TextMode="Range" min="1" Max="8" OnTextChanged="txtVal2_TextChanged1" AutoPostBack="True"></asp:TextBox>
<asp:Label ID="lblVal2" runat="server" Text="/////"></asp:Label>
</p>
<p>
Quantum 3 Length:
<asp:TextBox ID="txtVal3" runat="server" TextMode="Range" min="1" Max="8" AutoPostBack="True" OnTextChanged="txtVal3_TextChanged1"></asp:TextBox>
<asp:Label ID="lblVal3" runat="server" Text="/////"></asp:Label>
</p>
<p>
<asp:Button ID="btnNext" runat="server" AutoPostBack="true" Height="24px" OnClick="btnNext_Click" style="margin-left: 0px" Text="Next" Width="150px" />
<script type="text/javascript" __designer:mapid="129">
function NextPage() {
window.open('Execution.aspx', 'Execution');
}
</script>
<asp:Label ID="lblError" runat="server" ForeColor="Red" Text="Invalid input; Please ensure that Quantum 1 <= Quantum 2 <= Quantum 3" Visible="False"></asp:Label>
</p>
</form>
</body>
My C# code used to control the boxes and change their values
public partial class Quantums : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
try
{
txtVal1.Text = HttpContext.Current.Session["Q1"].ToString();
}
catch { }
try
{
txtVal2.Text = HttpContext.Current.Session["Q2"].ToString();
}
catch { }
try
{
txtVal3.Text = HttpContext.Current.Session["Q3"].ToString();
}
catch { }
lblVal1.Text = txtVal1.Text;
lblVal2.Text = txtVal2.Text;
lblVal3.Text = txtVal3.Text;
//UpdatePanel1.Triggers.Add(new AsyncPostBackTrigger() { ControlID = "btnNext" });
}
protected void txtVal1_TextChanged1(object sender, EventArgs e)
{
HttpContext.Current.Session["Q1"] = txtVal1.Text;
}
And then the same code for textbox 2 and 3. Any suggestions on why the textboxes vaklue keeps resetting and autopostback is enabled on all three buttons.
I just noticed you were missing if(Page.IsPostBack()) return;. Your problem is that every time you change your textbox, the 'Page_Load' event is enacted, then the respective event handler (see page life cycle). So you were setting the text to the sessions, then setting the sessions to the text, effectively doing nothing.
You actually don't need anything for this page in the Page_load method, at least for now. Try the following:
protected void Page_Load(object sender, EventArgs e)
{
}
protected void txtVal1_TextChanged(object sender, EventArgs e)
{
Session["Q1"] = txtVal1.Text;
lblVal1.Text = txtVal1.Text;
}
protected void txtVal2_TextChanged(object sender, EventArgs e)
{
Session["Q2"] = txtVal2.Text;
lblVal2.Text = txtVal2.Text;
}
protected void txtVal3_TextChanged(object sender, EventArgs e)
{
Session["Q3"] = txtVal3.Text;
lblVal3.Text = txtVal2.Text;
}
You can then access the user input values using the respective session values. For example:
protected void Submit(object sender, EventArgs e)
{
List<string> answers = new List<string>();
answers.Add(Session["Q1"].ToString());
answers.Add(Session["Q2"].ToString());
answers.Add(Session["Q3"].ToString());
// Do stuff with answers
}
I want to focus on the same ListItem which causes the postback in a asp.net radiobuttonlist. But the implementation that have developed currently is focusing on first listitem only. Is there a way to focus on the particular listitem which causes the postback. I can not use Update panel in my case. My HTML and CodeBehind is as below:
HTML
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="lblName" runat="server" Text="Name" AssociatedControlID="txtName"></asp:Label>
<asp:TextBox ID="txtName" runat="server" Text="Enter your name"></asp:TextBox>
<br />
<br />
<asp:Label ID="lblPersonType" AssociatedControlID="rdoPersonType" runat="server" Text="Person Type"></asp:Label>
<br />
<asp:RadioButtonList ID="rdoPersonType" RepeatLayout="Flow" AutoPostBack="true" runat="server" OnSelectedIndexChanged="rboPersonType_Selected"></asp:RadioButtonList>
</div>
</form>
</body>
</html>
CodeBehind
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
rdoPersonType.Items.Add(new ListItem() { Text = "Student", Value = "1", Selected = true });
rdoPersonType.Items.Add(new ListItem() { Text = "Greencard Holder", Value = "2" });
rdoPersonType.Items.Add(new ListItem() { Text = "Refugee", Value = "3" });
rdoPersonType.Items.Add(new ListItem() { Text = "Asylum", Value = "4" });
}
}
protected void rboPersonType_Selected(object sender, EventArgs e)
{
rdoPersonType.Focus();
}
There are several ways to do that. You can either control the entire thing from the client side, or you can do this from the server side:
protected void rboPersonType_Selected(object sender, EventArgs e)
{
ClientScript.RegisterStartupScript(
typeof(Page),
"SetFocus",
string.Format("document.getElementById('{0}_{1}').focus();", rdoPersonType.ClientID, rdoPersonType.SelectedIndex),
true);
}
I have a WebForms page that I would like to inject some additional controls into at runtime. Currently I am achieving this in the Page_Load event using a Literal control.
For example the page looks like this (note that the TextBox1 is not an asp control just to show that it works):
<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">
<input id="TextBox1" type="text" runat="server"/>
<asp:Literal ID="Literal1" runat="server" Visible="false"></asp:Literal>
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
</asp:Content>
And the code behind:
protected void Page_Load(object sender, EventArgs e)
{
Literal1.Visible = true;
if (!IsPostBack) Literal1.Text = "<input id=\"TextBox2\" type=\"text\" runat=\"server\"/>";
}
This works fine and both textboxes appear on the screen but if I type a value in to both and trigger a postback only the value of TextBox1 is retained.
I have tried moving my code to OnPreRender and OnPreLoad but still have the same issue.
I have noticed that when I view the page source TextBox1 has a UniqueId (e.g. ctl00$MainContent$TextBox1) while Textbox2 still has runat="server" as an attribute.
You can't inject server controls like this. You would need to add them as suggested in #Arvin's answer.
However, you use inject non-ASP.NET HTML controls similar to what you are doing and get their values.
From your code change the input's id to a name and drop the runat="server":
protected void Page_Load(object sender, EventArgs e)
{
Literal1.Visible = true;
if (!IsPostBack) Literal1.Text = "<input name=\"TextBox2\" type=\"text\" />";
}
Then you can get it's value on postback:
string textbox2value = Request.Form["TextBox2"];
Then, if you want to add the control on postback with it's value:
Literal1.Text = "<input name=\"TextBox2\" type=\"text\" value=\"" +
Server.HTMLEncode(textbox2value) + "\" />";
if you want to inject a textbox you should use placeholder like this :
<input id="TextBox1" type="text" runat="server"/>
<asp:PlaceHolder ID="plh" runat="server"></asp:PlaceHolder>
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
protected void Page_Load(object sender, EventArgs e)
{
TextBox TextBox = new TextBox();
TextBox.ID = "TextBox2";
plh.Controls.Add(TextBox);
}
protected void Button1_Click(object sender, EventArgs e)
{
var Text1 = TextBox1.Value;
var Text2 = Request.Form["TextBox2"];
}
I have been searching around and I am lost on how to do what I am attempting to do.
I am trying to create a form where the first column is a list of names, and the next column is all dropdown lists. The idea is that for each name the user will pic a value. Each name may require two, or three or more values. I want to create a dynamic form where a user can click add in the row and another dropdown list appears.
Ex.
"Name" | Add Button | DropDown
then when I click add...
"Name" | Add Button | DropDown | DropDown
and have it keep going.
I am able to create the form and I have it working creating the dropdown lists. The problem is that I am adding the controls on the ItemCommand of a repeater, so they must be recreated every time. Because of this I cannot find a way to keep the values selected in each dropdown, when I have to recreate them.
Typically no more than two dropdowns are required but there are a few cases where three is needed, and it could arise for more. I would like to keep this dynamic as possible.
I know that if I added the dropdown's in the page Init they would be persisted on the postback, but at least in my design the user has to click add to get another drop down.
Is there a way to capture the data from these dropdowns then reload them every time? Or a better way to achieve this functionality?
Thank You for your help.
Here is some of the asp and code behind that I am using. This is functioning as I wish, but I don't know how to keep the data on a postback, as all of the dropdown lists I add are lost.
ASP:
<table>
<asp:Repeater ID="repChemicals" runat="server" OnItemCommand="repChemicals_OnItemCommand">
<ItemTemplate>
<tr>
<td>
<asp:HiddenField ID="hfNumber" runat="server" />
<%# Eval("ChemicalName") %>
</td>
<td>
<asp:Button runat="server" ID="btnAdd" Text="Add" CommandArgument="ADD" />
</td>
<td>
<div id="divContainer" runat="server">
<asp:DropDownList runat="server" Width="60px" ID="ddlTest"></asp:DropDownList>
</div>
</td>
</tr>
</ItemTemplate>
</asp:Repeater>
</table>
C#:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
List<Chem> Chemicals = new List<Chem>();
Random rnd = new Random();
for (int z = 0; z <= 10; z++)
{
List<string> t = new List<string>();
Chem a = new Chem()
{
ChemicalName = "Chemical" + z.ToString()
};
Chemicals.Add(a);
}
repChemicals.DataSource = Chemicals;
repChemicals.DataBind();
}
}
public void repChemicals_OnItemCommand(object sender, RepeaterCommandEventArgs e)
{
int number = 0;
foreach (RepeaterItem i in repChemicals.Items)
{
HiddenField hf = (HiddenField)repChemicals.Items[i.ItemIndex].FindControl("hfNumber");
if (i.ItemIndex == e.Item.ItemIndex)
{
if (!string.IsNullOrWhiteSpace(hf.Value))
{
number = Convert.ToInt16(hf.Value) + 1;
}
else
{
number = 1;
}
hf.Value = number.ToString();
}
else
{
if (!string.IsNullOrWhiteSpace(hf.Value))
{
number = Convert.ToInt16(hf.Value);
}
else
{
number = 0;
}
}
for (int x = 0; x < number; x++)
{
DropDownList ddl = new DropDownList();
ddl.Style.Add("width", "60px");
ddl.ID = "ddl" + i.ToString() + x.ToString();
ddl.Style.Add("Margin-right", "3px");
ddl.Attributes.Add("runat", "server");
ddl.DataSource = DataSource();
ddl.DataBind();
Control c = repChemicals.Items[i.ItemIndex].FindControl("divContainer");
c.Controls.Add(ddl);
}
}
Some of the loops are for creating test data. Basically I am storing a number of dynamic controls on each row in a hiddenfield. Then on the item command I loop through all of the rows and recreate all of the previously existing ddl's, and add one to the row that teh command came from.
This isn't exactly answering your question, but it accomplishes your ultimate goal in a less complex way and one that takes advantage of built in ASP.NET controls so maintaining state between postbacks is taken care of for you.
It utilizes jQuery, jQuery UI and a DropDownChecklist plugin.
ASPX
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.21/jquery-ui.min.js"></script>
<script type="text/javascript" src="js/ui.dropdownchecklist.js"></script>
<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.21/themes/base/jquery-ui.css"/>
</head>
<body>
<form id="form1" runat="server">
<div>
<table>
<asp:Repeater ID="repChemicals" runat="server">
<ItemTemplate>
<tr>
<td>
<%# Container.DataItem %>
</td>
<td>
<div id="divContainer" runat="server">
<asp:ListBox ID="lstAttributes" SelectionMode="Multiple" runat="server"></asp:ListBox>
</div>
</td>
</tr>
</ItemTemplate>
</asp:Repeater>
</table>
<asp:Button ID="btnPostback" Text="Postback" runat="server"/>
</div>
</form>
</body>
</html>
C#
using System;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace PersonAttributes
{
public partial class People : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
repChemicals.ItemCreated += RepChemicalsOnItemCreated;
var chemicals = new[] {"Hydrogen", "Helium", "Lithium", "Beryllium", "Boron"};
if(!IsPostBack)
{
repChemicals.DataSource = chemicals;
repChemicals.DataBind();
}
var dropDownChecklist = "$(document).ready(function () { $('select').dropdownchecklist(); });";
ScriptManager.RegisterStartupScript(this,GetType(),"initDropDownChecklist",dropDownChecklist,true);
}
private void RepChemicalsOnItemCreated(object sender, RepeaterItemEventArgs repeaterItemEventArgs)
{
var lst = repeaterItemEventArgs.Item.FindControl("lstAttributes") as ListBox;
if (lst == null)
return;
lst.DataSource = new[] {"Option 1", "Option 2", "Option 3"};
}
}
}
See it in action at CodeRun.
I have a textbox in my webpage and I want to fire as soon User clicks or enter something on this textbox. Code is working but it is firing when an User hits Enter button. I want it to fire when user types their 1st character. Which event is app for this?
This is my mockup code:
<asp:TextBox ID="txtAgentName" runat="server" OnTextChanged = "txtAgentName_TextChanged"></asp:TextBox>
But when I am running this webpage it is showing me this err:
CS0123: No overload for 'txtAgentName_TextChanged' matches delegate 'System.EventHandler'
I have this on my code behind:
protected virtual void txtAgentName_TextChanged(object sender, EventArgs e)
{
}
Made a breakpoint in in here, and seems like it is firing when I am hitting Enter button. I want to fire when user enter 1st character inside that textbox.
What I am doing wrong here?
your event handler must have this signature
protected void txtAgentName_TextChanged(object sender, EventArgs e)
{
...
}
does it?
<%# Page Language="C#" %>
<script runat="server">
protected void txtSearch_TextChanged(object sender, EventArgs e)
{
lblSearchResults.Text = "Search for: " + txtSearch.Text;
}
</script>
<html>
<head>
<title>TextBox AutoPostBack</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label
id="lblSearch"
Text="Search:"
Runat="server" />
<asp:TextBox
id="txtSearch"
AutoPostBack="true"
OnTextChanged="txtSearch_TextChanged"
Runat="server" />
<hr />
<asp:Label
id="lblSearchResults"
Runat="server" />
</div>
</form>
</body>
</html>
Use javascript's TextBox1.Attributes.Add("OnKeyPress", "GetKeyPress()") and then postback if you wish.