Text box getting cleared because of update panel - c#

I've have one table, in that table within one I've one and within that , I've update panel whose update mode is set to conditional. Within this update panel I've another table. The table contains 3 text boxes as: old password, new password and confirm password. On the textChanged event of the old password I am checking the user entered value with the value in db. But when the function completes its execution all the 3 text boxes looses its values regardless of whether I update the update panel or not. I don't know why it clears text boxes. I want to prevent text boxes from getting cleared. I tried to get the text box text in string variable and again assign it to text boxes (both in text box text changed event and in page load event under isPostBack condition) but its too, not working.
asp code:
.
.
.
<tr>
<td colspan="3">
<div>
<asp:UpdatePanel ID="updPnlChngPwd" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<table style="width:100%">
<tr>
<td>
Old Password
</td>
<td>:</td>
<td>
<asp:TextBox ID="txtOldPwd" runat="server" Height="21px" MaxLength="50" TextMode="Password" Width="60%" ontextchanged="txtOldPwd_TextChanged"
AutoPostBack="True"></asp:TextBox>
</td>
</tr>
<tr>
<td></td>
<td></td>
<td>
<asp:Label ID="lblWrongOldPwd" runat="server" Text="Wrong Old Password" ForeColor="Red" Visible="False"></asp:Label>
</td>
</tr>
<tr>
<td>
Password
</td>
<td>:</td>
<td></td>
</tr>
<tr>
<td></td>
<td>:</td>
<td>
<asp:TextBox ID="txtSuppRePwd" runat="server" Height="21px" MaxLength="50" TextMode="Password" Width="60%"></asp:TextBox>
</td>
</tr>
<tr>
<td></td>
<td>
<asp:Button ID="btnUpdPwd" runat="server" Text="Change Password" onclick="btnUpdPwd_Click"/></td>
<td>
</td>
</tr>
</table>
</ContentTemplate>
</asp:UpdatePanel>
</div>
<td>
</tr>
.
.
.
C# code for tetxt box textChanged event:
protected void txtOldPwd_TextChanged(object sender, EventArgs e)
{
DataTable dtOldPwd = Obj.DBAccess("select Pwd from Customer where Cust_Id = " + Convert.ToInt32(Session["SuppID"]) + " and Supp_Pwd = '" + txtOldPwd.Text + "'");
if (dtOldPwd.Rows.Count == 1)
{
lblWrongOldPwd.Visible = false;
}
else
{
lblWrongOldPwd.Visible = true;
updPnlChngPwd.Update();
}
}
Now I am not able to understand what exactly wrong I am doing, does having update panel inside the table causing problem?

<td>
<asp:TextBox ID="txtSuppRePwd" runat="server" Height="21px" MaxLength="50" TextMode="Password" Width="60%"></asp:TextBox>
</td>
You have TextMode set to password which will not save your textbox value .
However you will get your textbox value as string on textchange event
protected void txtbx_TextChanged(object sender, EventArgs e)
{
string txtValue = txtbx.Text;
ViewState["xyz"]= txtValue;
}
and you have to save this value in ViewState to use it for btnClick event .
OR
You can also set textbox attribute at Page_Load event which is a very bad practice to do like this
protected void Page_Load(object sender, EventArgs e)
{
txtbx.Attributes.Add("value", txtbx.Text);

TextBox with TextMode="Password" will be cleared after postback or partial postback. This is the default behavior of the password textbox so submit all the data at a time and do the validation in your code.
Alternatively, You can store password in in viewstate or session and restore after postback.

Related

FindControl() always returns null from DataList Textbox

I have 8 items in a SQL table with a Description, ItemNumber, and ImagePath.
protected void Page_Load(object sender, EventArgs e)
{
//fill the datalist for the Signs Table
string tCallFrom = "Program." + System.Reflection.MethodBase.GetCurrentMethod().Name;
string tQry = #"SELECT * FROM [js_Signs]";
DataTable tblSigns = objCommMethods.fReturnTableFromQry(clsDBSelect.enumDBSelect.ProjectMaster, tQry, tCallFrom);
SignsList.DataSource = tblSigns;
SignsList.DataBind();
}
I am using a DataList to show all of the items along with a textbox that will allow a user to input the number of items they want:
<asp:DataList ID="SignsList" runat="server" RepeatColumns="4" CellPadding="2" Width="90%" ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<table>
<tr>
<th>
<%#DataBinder.Eval(Container.DataItem, "Description") %>
</th>
</tr>
<tr>
<th>
<%#DataBinder.Eval(Container.DataItem, "ItemNumber") %>
</th>
</tr>
<tr>
<td>
<asp:Image ID="SignImage" runat="server" ImageUrl='<%#DataBinder.Eval(Container.DataItem, "ImagePath") %>' />
</td>
</tr>
<tr style="text-align: center;">
<td>
<asp:TextBox ID="txtSignQuantity" runat="server" CssClass="txtBox" BackColor="White" Enabled="true"
type="number" min="0" ToolTip="Please choose quantity of signs needed."/>
</td>
</tr>
<tr>
<td>
<p> </p>
</td>
</tr>
</table>
</ItemTemplate>
</asp:DataList>
<div class="btnGroup">
<div class="btnDiv">
<asp:Button ID="btnSave" runat="server" Text="Save" CssClass="btnSave" Width="90px" Visible="true" OnClick="btnSave_Click"/>
</div>
<div class="btnDiv">
<asp:Button ID="btnCancel" runat="server" Text="Clear" CssClass="btnCancel" Width="90px" Visible="true" OnClick="btnCancel_Click"/>
</div>
</div>
After the saved button is clicked in C# I want to find out the value that a user entered but it is always returning null:
protected void btnSave_Click(object sender, EventArgs e)
{
TextBox txtSignQuantity;
string tempSignQuantity;
try
{
foreach (DataListItem item in SignsList.Items)
{
txtSignQuantity = item.FindControl("txtSignQuantity") as TextBox;
tempSignQuantity = txtSignQuantity.Text;
}
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
I also checked and the Count of SignsList.Items was 8, so I know that it is retrieving the correct information. Sorry, I've never used a Data List before so I'm not really sure how to go about this...
The short answer is that data binding on postback is causing the problem. Check the Page.IsPostBack property before doing data binding:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
//fill the datalist for the Signs Table
string tCallFrom = "Program." + System.Reflection.MethodBase.GetCurrentMethod().Name;
string tQry = #"SELECT * FROM [js_Signs]";
DataTable tblSigns = objCommMethods.fReturnTableFromQry(clsDBSelect.enumDBSelect.ProjectMaster, tQry, tCallFrom);
SignsList.DataSource = tblSigns;
SignsList.DataBind();
}
}
ASP.NET WebForms attempts to abstract away the fact that the control instances that were used to render the page are not the same instances it has when handling postback events. Data binding compounds the abstraction because it has to create controls in response to the DataBind call, and then on postback, recreate them based on the ViewState it saved.
Initializing controls from ViewState happens on the Init event, so when the Load event is fired later in the page lifecycle and you call DataBind on the control, everything it restored gets wiped out and recreated.
As for why you were getting null, it may have been that the controls were wiped out but not recreated; it may have had to do with other event handlers that didn't get rewired after the second data binding.

ASP.NET how to change background color of table row on button click + row entry?

I have a table with one row which is filled in with values after the user clicks a button. I want to change the background color of the row to different colors based on the values that are filled in to the row.
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Search" />
<tr>
<td runat="server" id ="td1" class="auto-style1"></td>
<td runat="server" id ="td2" class="auto-style1"></td>
<td runat="server" id ="td3" class="auto-style1"></td>
<td runat="server" id ="td4" class="auto-style1"></td>
</tr>
and my Button1_Click function looks like
protected void Button1_Click(object sender, EventArgs e)
{
string[]toDisp = someFunction();
td1.InnerText = toDisp[0];
td2.InnerText = toDisp[1];
td3.InnerText = toDisp[2];
td4.InnerText = toDisp[3];
}
Basically, I want to set the background color of the table row based on the value of toDisp[1]. How should I go about doing this? Thanks.
If its going to be just 1 row
just set a ID to it with runat attribute
<tr id="test" runat="server">
<td runat="server" id ="td1" class="auto-style1"></td>
<td runat="server" id ="td2" class="auto-style1"></td>
<td runat="server" id ="td3" class="auto-style1"></td>
<td runat="server" id ="td4" class="auto-style1"></td>
</tr>
then based on the condition of toDisp[1]
you can write a switch statement or Random (based on color requirement) to just set
test.BgColor = "SomeColor";

Using FindControl to find the contents of an HTML control

I've got this code in the code-behind on my page, which works perfectly fine for a repeater:
protected void AcctAssnRepeater_ItemCommand(object source, RepeaterCommandEventArgs e)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["PBRConnectionString"].ConnectionString);
con.Open();
{
string str10 = ((HtmlInputText)e.Item.FindControl("txtFlgUpdatedOn")).Value;
}
}
I'm trying to do something similar on another page, but it is telling me that "item" isn't valid:
protected void btnSubmit_OnClick(object sender, EventArgs e)
{
string str10 = ((HtmlInputText)e.Item.FindControl("txtDtSentToCIS")).Value;
}
I'm still a C# n00b, can anyone tell me how to reference the value inside this control? Both pages have a runat="server" on the aspx side, so I would expect that there's a way to do it, I'm sure my syntax just needs adjusting.
Thanks!
EDIT: Here's a piece of the aspx. Maybe I should note that it's all inside a Tab Control.
<div style="width:430px;border:1px solid blue;float:left;">
<asp:Panel ID="Panel3" runat="server" Height="220px" style="float:left; margin-left: 19px"
Width="410px">
<table>
<tr>
<td width="210px">BIL Name:</td>
<td width="200px"><asp:textbox id="txtCISName" runat="server"></asp:textbox></td>
</tr>
<tr>
<td width="210px">Date Sent To BIL:</td>
<td width="200px"><input type="text" id="txtDtSentToCIS" class="datepicker" name="txtDtSentToCIS" runat="server" style="height: 14px; width: 70px" /></td>
</tr>
<tr>
<td width="210px">BIL Sign Off Received:</td>
<td width="200px"><asp:DropDownList ID="cboCISSignOff" runat="server" Height="16px"
AutoPostBack="True" onselectedindexchanged="chkCISSignOff_CheckedChanged">
<asp:ListItem>N</asp:ListItem>
<asp:ListItem>Y</asp:ListItem>
</asp:DropDownList></td>
</tr>
<tr>
<td width="210px"><asp:Label runat="server" Text="BIL Response:" ID="CISResp" /></td>
<td width="200px"><asp:textbox id="txtCISResponse" runat="server"
textmode="MultiLine" rows="9" Width="180px"></asp:textbox></td>
</tr>
</table>
</asp:Panel>
</div>
You should be able to use the ID to reach the control. For ex. a textbox:
<asp:TextBox ID="txtDtSentToCIS" runat="server" />
In your code behind you can do something as
SomeMethod(this.txtDtSentToCIS.Text);
or
string enteredByUser = this.txtDtSentToCIS.Text;
If you want to access repeater containing textbox(es) from outside the repeater, you may code like this:
Iterating the RepeaterItemCollection:
foreach (RepeaterItem item in Repeater1.Items)
{
TextBox txtDtSentToCIS = item.FindControl("txtDtSentToCIS") as TextBox;
}
Or simply accessing through indexer:
TextBox txtDtSentToCIS = Repeater1.Items[1].FindControl("txtDtSentToCIS") as TextBox;
Good luck.
If you are using asp I would suggest that you use an asp Text box.
<asp:TextBox ID="textBoxName" runat="server" />
When the button is clicked and you OnClick method is called you can search for the text box by name and assign the text to your string.
string str10 = textBoxName.text;
You don't really need to use the find control unless that control is buried in another control like a grid view or login view.
What could be happening is that the FindControl method only works for the first control collection in this case the only control contained is "Panel3", try this:
var panel = e.Item.FindControl("Panel3") as Panel;
string str10 = ((HtmlInputText)panel.FindControl("txtFlgUpdatedOn")).Value;
Good luck

Retrieving value from Asp.Net TextBox

Problem: I have an asp.net Textbox that I am putting text into and on text change it should assign its value to a variable, this does not happens.
Question: What is the best method to retrieve the value from the Textbox?
C# Code:
protected void btnSourceConnect_Click(object sender, EventArgs e)
{
if (Util.Connection(SourceString, 0))
{
lblTesting.Text = "Working!";
}
else
{
lblTesting.Text = "It No Work";
}
}
protected void txtSourceServer_TextChanged(object sender, EventArgs e)
{
SourceString.DataSource = txtSourceServer.Text;
}
protected void txtSourceDatabase_TextChanged(object sender, EventArgs e)
{
SourceString.InitialCatalog = txtSourceDatabase.Text;
}
protected void txtSourceUN_TextChanged(object sender, EventArgs e)
{
SourceString.UserID = txtSourceUN.Text;
}
protected void txtSourcePass_TextChanged(object sender, EventArgs e)
{
SourceString.Password = txtSourcePass.Text;
}
Asp.Net Code:
<table style="width: 100%;Border:1px solid Black;">
<tr>
<td class="style1">
Source Server:</td>
<td class="style1">
<asp:TextBox ID="txtSourceServer" runat="server"
ontextchanged="txtSourceServer_TextChanged" AutoPostBack="True"></asp:TextBox>
</td>
<td class="style1">
Source Database:
</td>
<td class="style1">
<asp:TextBox ID="txtSourceDatabase" runat="server"
ontextchanged="txtSourceDatabase_TextChanged" AutoPostBack="True"></asp:TextBox>
</td>
</tr>
<tr>
<td class="style1">
User Name:
</td>
<td class="style1">
<asp:TextBox ID="txtSourceUN" runat="server"
ontextchanged="txtSourceUN_TextChanged" AutoPostBack="True"></asp:TextBox>
</td>
<td class="style1">
Password:
</td>
<td class="style1">
<asp:TextBox ID="txtSourcePass" runat="server"
ontextchanged="txtSourcePass_TextChanged" AutoPostBack="True"></asp:TextBox>
</td>
</tr>
<tr>
<td class="style1">
</td>
<td class="style1">
</td>
<td class="style1">
</td>
<td class="style1">
<asp:Button ID="btnSourceConnect" runat="server" Text="Test Connection"
onclick="btnSourceConnect_Click" />
</td>
</tr>
</table>
What is the best method to retrieve the value from the Textbox?
The best method is like this control I am writing right now, you have a button that make post back, and then you read the value of the text box on code behind - on post back.
Using the AutoPostBack="True" on every TextBox you use involves too many unnecessary post backs to the server, it is better to use a "submit" button and save all your values when the user click on submit.
In you case you have a button, and you only need to remove the auto post back and set your values only when you try to connect as:
protected void btnSourceConnect_Click(object sender, EventArgs e)
{
SourceString.UserID = txtSourceUN.Text;
SourceString.DataSource = txtSourceServer.Text;
SourceString.InitialCatalog = txtSourceDatabase.Text;
SourceString.Password = txtSourcePass.Text;
if (Util.Connection(SourceString, 0))
{
lblTesting.Text = "Working!";
}
else
{
lblTesting.Text = "It No Work";
}
}
AutoPostback = true on a TextBox will cause the page to post back when the text box loses focus, not on every text change.
From the look of your code most of this functionality should be happening on the client side (i.e. with javascript).

Dyanamically disable validation on asp.net controls

Depending upon the responses from the user when they complete a form, controls may or may not be required. All of these controls have validation attached to them. For instance, if the user hasn't lived at their address for at least 2 years, I need to validate previous address information; if not, I need to skip that validation.
I've tried disabling the validator control with jQuery and although when the validation text is 'greyed out', it still causes validation.
<script src="../../Scripts/jquery-1.6.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#ddlSpouseData').change(
function () {
var selection = $('#<%= ddlAddressData.ClientID%>').get(0).selectedIndex;
if (selection == 1) {
alert(selection);
$('#rfvAddressType').attr('disabled', 'disabled');
$('#rfvBAddress').attr('disabled', 'disabled');
}
});
});
</script>
<table id="MyTable" class="tableModule">
<tr>
<td class="tableDataBorder">
Data is not available and<br /> will be provided later.
</td>
<td class="tableDataBorder">
<asp:DropDownList ID="ddlAddressData" runat="server">
<asp:ListItem>Please Select</asp:ListItem>
<asp:ListItem>Yes</asp:ListItem>
<asp:ListItem>No</asp:ListItem>
</asp:DropDownList>
</td>
</tr>
<tr class="hideRow">
<td class="tableDataBorder">
Identifying Document
</td>
<td class="tableDataBorder">
<asp:DropDownList ID="ddlAddressType" runat="server">
<asp:ListItem>Please Select</asp:ListItem>
<asp:ListItem>Home</asp:ListItem>
<asp:ListItem>Office</asp:ListItem>
<asp:ListItem>Other</asp:ListItem>
</asp:DropDownList>
<br />
<asp:RequiredFieldValidator ID="rfvAddressType" CssClass="regexError" ControlToValidate="ddlAddressType"
runat="server" ErrorMessage="Please select address type" Display="Dynamic"
InitialValue="Please Select"></asp:RequiredFieldValidator>
</td>
</tr>
<tr class="hideRow">
<td class="tableDataBorder">
Address
</td>
<td>
<asp:TextBox ID="txtAddress" MaxLength="50" runat="server" CssClass="StdTxtBox"></asp:TextBox><br />
<asp:RequiredFieldValidator ID="rfvBAddress" CssClass="regexError" ControlToValidate="txtAddress"
runat="server" ErrorMessage="Please enter your address" Display="Dynamic"></asp:RequiredFieldValidator>
</td>
</tr>
</table>
Instead of your RequiredFieldValidator, use a CustomValidator instead.
So for example you can change your 'rfvAddressType' requiredfieldvalidator as follows:
<asp:CustomValidator runat="server"
id="valAddressType"
controltovalidate="ddlAddressType"
onservervalidate="cusCustom_ServerValidate"
errormessage="Please select address type" />
Then on the server code:
protected void cusCustom_ServerValidate(object sender, ServerValidateEventArgs e)
{
if (ddlAddressType.SelectedItem.Value == "1")
e.IsValid = false; // or do any additional validation checks here!
else
e.IsValid = true;
}
More details here:
http://asp.net-tutorials.com/validation/custom-validator/
https://web.archive.org/web/20211020145934/https://www.4guysfromrolla.com/articles/073102-1.aspx
Try disabling or enabling validators on the run to achieve your desired functionality. You can try this code. I haven't tested it.
//Syntax:
ValidatorEnable(ValidatorContronName,Boolean);
//Explanation:ValidatorContronName - This is ClientID of the Validation control.
Boolean - true(Enable) / false(Disable)
//Example:
ValidatorEnable(document.getElementById('<%=rfvAddressType.ClientID%>'), false);

Categories