ASP.Net: How to maintain TextBox State after postback - c#

I would like to know how to maintain the control state that has been modified in Javascript.
I have two TextBoxes, one DropDownList and a button (all Runat=Server) in C# ASP.net 2010 Express.
First textbox is just accept whatever data user input. Second textbox enable state will change based on DDL selected value. If ddl selected value is "-", second textbox will become Enabled = False.
If not "-", it will become Enabled = True. This enable is done through Javascript.
In my Page Load event, I have below code.
if (!IsPostBack)
{
txtKey2.Text = "";
txtKey2.BackColor = System.Drawing.ColorTranslator.FromHtml("#CCCCCC");
txtKey2.Enabled = false;
}
And in my aspx page, I have some javascript which will clear the textbox data and disable the textbox.
Here is for Second Textbox.
<asp:TextBox ID="txtKey2" runat="server" Width="425px" EnableViewState="False"></asp:TextBox>
And here is for DDL.
<asp:DropDownList ID="selKey1" runat="server" onchange="EnableSelkey(this.value,1)">
<asp:ListItem Value="0">-</asp:ListItem>
<asp:ListItem Value="1">AND</asp:ListItem>
<asp:ListItem Value="2">OR</asp:ListItem>
</asp:DropDownList>
Here is the code for my Javascript. (I have a plan to implement other textbox and ddl so in my code I have Else if condition).
function EnableSelkey(val, strID) {
var txtBox;
if (strID == "1")
txtBox = document.getElementById('<%= txtKey2.ClientID %>');
else if (strID == "2")
txtBox = document.getElementById('<%= txtKey3.ClientID %>');
else
txtBox = document.getElementById('<%= txtKey4.ClientID %>');
if (val != 0) {
txtBox.disabled = false;
txtBox.style.backgroundColor = "White";
txtBox.value = "";
txtBox.select();
}
else {
txtBox.disabled = true;
txtBox.style.backgroundColor = "#CCCCCC";
txtBox.value = "";
}
}
I have nothing in button click event.
By using above all code, when I run the project, the page loads Ok.
The second textbox enabled state is set to False (through Page_Load event). So far Ok.
Then from my browser, I choose ddl value to other instead of "-", the textbox become enable because of javascript. This is Ok.
I input the value and click on the button. Page PostBack happens here. Textbox is still enabled (because of EnableViewState = False for my textbox).
I choose ddl value to "-", second textbox became disabled.
Click on the button, page postback happen, but this time the textbox is still enabled. << This is the issue I'm trying to solve. I change EnableViewState, ViewStateMode in different values but still the same.
Is there any solution for this one?
Here is my test image URL.
State 1 ,
State 2 ,
State 3
Sorry for the long post.

I have tried and found no solution beside using additional HiddenField control.
I update the hidden field value when I update the status of my textbox in Javascript.
And on my Page Load event, I checked all the hidden field values and based on the hiddenfield values, I will disable/enable my textboxes which is for me not a good solutions.
Imagine I have 10 or 15 textboxes on my form, I need to have 10 or 15 hidden field just to maintain client side action result.
Currently, this is the only solution for me.
I'm not sure can this consider as 'Answer' so I haven't close this question yet.

<asp:DropDownList ID="selKey1" runat="server" onchange="EnableSelkey(this.value,1)">
<asp:ListItem Value="0">-</asp:ListItem>
<asp:ListItem Value="1">AND</asp:ListItem>
<asp:ListItem Value="2">OR</asp:ListItem>
</asp:DropDownList>
function EnableSelkey(val, strID) {
var txtBox;
if (strID == "1")
txtBox = document.getElementById('<%= txtKey2.ClientID %>');
else if (strID == "2")
txtBox = document.getElementById('<%= txtKey3.ClientID %>');
else
txtBox = document.getElementById('<%= txtKey4.ClientID %>');
if (val != 0) {
txtBox.disabled = false;
txtBox.style.backgroundColor = "White";
txtBox.value = "";
txtBox.select();
}
else {
txtBox.disabled = true;
txtBox.style.backgroundColor = "#CCCCCC";
txtBox.value = "";
}
}
You Have to call you javascript function on every postback.
if (!IsPostBack)
{
txtKey2.Text = "";
txtKey2.BackColor = System.Drawing.ColorTranslator.FromHtml("#CCCCCC");
txtKey2.Enabled = false;
}
ScriptManager.RegisterClientScriptBlock(this, typeof(System.Web.UI.Page), "MyJSFunction", "EnableSelkey("+selKey1.SelectedValue+",1);", true);
It May be help you, Let me know for further help.

I found a solution that worked was to put the code that I put in the !IsPostBack section for enabling and disabling the textboxes also directly in the page load event.

Related

Having to click button twice to trigger postback in asp.net

I have some validation code in my searchbutton click event and have been having problems with it having to be clicked twice to work.
Asp Code:
<asp:Button ID="SearchButton" runat="server" Text="Search" Width="148px" OnClick="SearchButton_Click" style="height: 35px" />
Code Behind
protected void SearchButton_Click(object sender, EventArgs e)
{
string title = TitleSearch.Text;
Regex rgx = new Regex("^[0-9A-Za-z ]+$");
if (title != "" && !rgx.IsMatch(title))
{
ErrorLabel.Text = "Special characters are not allowed";
}
else
{
SearchButton.PostBackUrl = "results.aspx";
}
}
does the textbox have postback ? becaus if you change the text in the textbox it will do postback when you leave the textbox.so if you click the button the postback of the textbox fires.
I would check the textbox with java
Add in you page load event "Change EditGroup to the TextBoxName you want to check"
EditGroup.Attributes.Add("onchange", "return SomeTextChanged();");
This will add an onchange event to the textbox and it will call the java function in your aspx page when you click the button
Then in your aspx page you add "Again change EditGroup to the name of the TextBox you want to check"
<script type="text/javascript">
function SomeTextChanged() {
var Entered = document.getElementById('<%= EditGroup.ClientID %>');
if (Entered.value != "" && !Entered.value.match("^[0-9A-Za-z ]+$"))
{
alert("Special characters are not allowed");
document.getElementById('<%= EditGroup.ClientID %>').value = '';
}
else
{
}
}
</script>
So if you enter something that is not allowed you will get a message saying "Special characters are not allowed"
This will also stop you page from executing the rest of the code in the button click event.
And you also need to empty the textbox"i know this is maybe not the best way but if you don't empty the textbox and the user will click the button again it will not run the java code because the text didn't change"
So if if the text is good the java script will do nothing and the button click event will fire

Selected value from database in DropDownList (not GridView)

I work in ASP NET 4.0 and C-sharp.
I have one form page .aspx with this DropDownList (Inside is the ID) and save the value S or N in the matching field in database :
<asp:DropDownList ID="Inside" runat="server" Width="100" CssClass="ddl_Class">
<asp:ListItem Text="-------" Value=""></asp:ListItem>
<asp:ListItem Text="S" Value="S"></asp:ListItem>
<asp:ListItem Text="N" Value="N"></asp:ListItem>
</asp:DropDownList>
I need that when the value of field Inside in database is valid and is not null, in the DropDownList it's selected the value set in the database and disable the DropDownList.
I have tried this code in .cs page without success.
Anybody know how can I do that?
code-behind
InsideDB = dr["Inside"].ToString();
if (!string.IsNullOrEmpty(InsideDB.ToString()))
{
Inside.Text = InsideDB.ToString();
Inside.Enabled = false;
}
else
{
Inside.Enabled = true;
}
Try SelectedValue instead of Text property.
InsideDB = dr["Inside"].ToString();
Inside.Enabled = true;
if (!string.IsNullOrEmpty(InsideDB.ToString()))
{
Inside.SelectedValue = InsideDB.ToString();
Inside.Enabled = false;
}
Try something like
Inside.SelectedIndex = Inside.Items.IndexOf(Inside.Items.FindByText(InsideDB.ToString()));
instead of Inside.Text = InsideDB.ToString();
This assumes that you have an item with that text in the dropdownlist already.
I know this is old post. But this may help others.
Inside.Items.FindByText(InsideDB.ToString()).Selected=true;
Inside.Enabled = false;

Label Does Not Change After TextBox OnTextChanged Event ASP.NET

I have a username TextBox and a Label which should update to (V or X) when the TextBox text is changed. The label is updated only if, for example I press a button which automatically refreshes the page.
Here is the code:
<asp:TextBox ID="username" runat="server" OnTextChanged="checkUsername" Width="80%"></asp:TextBox>
<asp:Label ID="usernameCheck" runat="server" CssClass="checkL"></asp:Label>
And the aspx.cs
protected void checkUsername(object sender, EventArgs e)
{
if (username.Text.Length < 3 || username.Text.Length > 15)
{
//---Label = X (in red)
usernameCheck.Text = "\u2715";
}
else
{
if (myBl.checkUsername(Convert.ToString(username)))
{
//---Label = X (in red)
usernameCheck.Text = "\u2715";
}
else
{
//---Label = V (in green)
usernameCheck.Text = "\u2713";
}
}
}
Thanks for any help.
You need to add AutoPostBack="true" to your TextBox. This will cause it to post back and for that server side event to fire.
There are much better ways of doing what you are trying to accomplish though, most of which do not require a full page postback. I would try to make an AJAX call using the javascript change event, and using something like a callback method.

disable dropdownlist on page load

I have 2 dropdownlists populated from database:
what I want is to disable the second one on page load and when the value of the first one =="1".
here is my second dropdownlist:
<asp:DropDownList ID="DropDownList2" runat="server" AutoPostBack="True"
DataSourceID="SqlDataSource2" DataTextField="BName" DataValueField="BId"
OnDataBound="DownList2_DataBound"
OnSelectedIndexChanged="DropDownList2_SelectedIndexChanged">
</asp:DropDownList>
This what I tried to disable the dropdownlist2 (javascript):
<script type="text/javascript">
window.onload = function () {
document.getElementById('DropDownList2').disabled = true;
}
</script>
Tried another thing in C# code:
protected void Page_Load(object sender, EventArgs e)
{
if (DropDownList1.SelectedValue.ToString() == "1")
{
DropDownList2.Enabled = false;
}
}
I even tried this alone in page_load:
DropDownList2.Enabled = false;
The problem is it's disabled on SelectedIndexChanged for dropdownlist1 but not on page load! Is there's something missing in my code?
This statement allow you to set the dropdown2 to disable at page load.
$('#' + '<%=DropDownList2.ClientID%>').attr('disabled',true);
you can do this using Jquery simply as follow:
$(document).ready(function () {
var isPostBack = '<%=IsPostBack%>';
if (isPostBack == 'False' || $('#' + '<%=DropDownList1.ClientID%>').val() == '1') {
//This statement allow you to set the dropdown2 to disable
$('#' + '<%=DropDownList2.ClientID%>').attr('disabled', true);
}
else {
$('#' + '<%=DropDownList2.ClientID%>').attr('disabled', false);
}
$('#' + '<%=DropDownList1.ClientID%>').on("change", function () {
//Your code here
if ($('#' + '<%=DropDownList1.ClientID%>').val() == '1') {
$('#' + '<%=DropDownList2.ClientID%>').attr('disabled', true);
}
else {
$('#' + '<%=DropDownList2.ClientID%>').attr('disabled', false);
}
});
});
It is likely that the DropDownList1.SelectedValue is not equal to "1" on Page Load as I guess you'd be DataBinding it somehow, which would take effect afterwards.
Try adding a SelectedIndexChanged function for DropDownList1 and dis/enabling DropDownList2 here. You can put Enabled="False" in the markup for DropDownList2 to ensure it starts off Disabled.
The issue is likely that document.getElementById('DropDownList2') doesn't find your dropdown list. The ID for the list is a server-side value that doesn't necessarily translate to the client-side ID. If you set ClientIDMode for the control to Static, then the client ID will be DropDownList2. Another option is to access the ClientID property of the control when outputting your JavaScript (if it's inline):
document.getElementById('<%=DropDownList2.ClientID%>').disabled = true;
All that being said, even if that's the case, it'd be better to just start with Enabled="False" as #aaroncatlin suggests so you don't have to wait for the JavaScript to execute before it is disabled.
in ASP.NET the generated ID differs from the asp ID on the component, to access the element from Javascript you need to use <%=DropDownList2.ClientID%> the corresponding javascript will be something like this :
document.getElementById(<%=DropDownList2.ClientID%>).disabled = true;
The DropDownList would have a default selected index of -1 and a null value for selected value. I usually check against the selected index, instead of by value. For example,
if(DropDownList1.SelectedIndex < 1){
// assuming that index 0 holds your value of "1"
DropDownList2.Enabled = false;
}
And #Jacob did rightly point out about you needing to get the proper ClientID for your JavaScript function.

problem with check box in asp .net c#?

The controls on aspx page are like this
Submitted
Submission Date
I want, if the check box is checked, then the textbox will be enabled I wrote
if(chkSubmitted.Checked)
{
txtSubmissionDate.Enabled = true;
}
in the page load event. But when the page is loaded this checkbox having no effect on. Whats going wrong?
If you want the action of clicking the checkbox to enable the textbox, you'll need to do a postback when the box is checked by setting AutoPostBack="True":
<asp:CheckBox runat="server" ID="chkSubmitted" AutoPostBack="True" />
Or, you could use JavaScript:
<asp:CheckBox runat="server" ID="chkSubmitted" onclick="setSubmissionDateEnabled()" />
function setSubmissionDateEnabled()
{
var chkSubmitted = document.getElementById("<%= chkSubmitted.ClientID %>");
var txtSubmissionDate = document.getElementById("<%= txtSubmissionDate.ClientID %>");
txtSubmissionDate.disabled = !chkSubmitted.checked;
}
First set autopostback property to true of checkbox
write following code in checkbox_Selectedindexchanged event
if(chkSubmitted.Checked)
{
txtSubmissionDate.Enabled = true;
}
else
{
txtSubmissionDate.Enabled = false;
}
Thats most likely because the default state of txtSubmissionDate is enabled already.
Try this in your page_load:
txtSubmissionDate.enabled = !chkSubmitted.Checked
To clarify, the textbox should not (!) be enabled when the Checkbox is.
Put this in Page_PreRender event. At this stage it will capture the user affected state of chkSubmitted.

Categories