reset / clear all text box function not working - c#

I have a function that is supposed to clear/reset all textbox in my aspx.page and this page is using a master page but it doesn't work. below is the code. Just got this code from this site.
//Clear all textbox
ResetTextBoxes(this);
//function to clear textboxes
private void ResetTextBoxes(Control parent)
{
if (parent is TextBox)
{
((TextBox)parent).Text = string.Empty;
}
foreach (Control child in parent.Controls)
{
if (child is TextBox)
{
((TextBox)child).Text = string.Empty;
}
ResetTextBoxes(child);
}
}

Just want to share a solution on asp.net codebehind. In this , you should put all the id's of your textboxes in array.
TextBox[] textboxes = {TextBox2,TextBox3,TextBox4,TextBox5,TextBox6 };
for (int i = 0; i < 5; i++)
{
TextBox myTextBox = textboxes[i];
myTextBox.Text = "";
}

The other way around I found is use a javascript function that will clear all my asp.net Textboxes. I've added a class to all all the Textbox e.g.
<asp:TextBox ID="txtName" runat="server" class="mTxtBox"> </asp:TextBox>
<asp:TextBox ID="txtID" runat="server" class="mTxtBox"> </asp:TextBox>
<asp:TextBox ID="txtDept" runat="server" class="mTxtBox"> </asp:TextBox>
<asp:Button onclick="ClearTxtBoxes_Click" ID="ClearTxtBoxes" runat="server" Text="Clear Fields"> </asp:Button>
//onclick event of Button
ScriptManager.RegisterStartupScript(this,this.GetType(),"runJs","clearText();",true);
//my JavaScriptFunction
function clearText(){
$('.mTxtBox').val('');
}

Controls sometimes have a hard time updating. Try calling child.Refresh(); and see if that fixes it.

Related

Clearing the TextBox values in Update Panel when dropdown index changed in c#

I want to clear the Text field's values which is taken in Update panel but because of update panel the values are not getting cleared. It is not finding the TextBox control declared inside the Update panel in .aspx. So, when DropDown selected index changes, I want to reset the text fields values. Can anybody please help me out?
Here is my C# code for clearing the textfield's values:
void ClearInputs(ControlCollection ctrls)
{
foreach (Control ctrl in ctrls)
{
if (ctrl is TextBox)
((TextBox)ctrl).Text = String.Empty;
ClearInputs(ctrls.Controls);
}
}
to find textbox in updatepanel use
TextBox tb = (TextBox)updatepanel1.FindControl("textbboxid");
use update panel mode conditional and do updatepanel1.Update(); after cleaning your textboxes
Try This:
public void CleartextBoxes(Control parent)
{
foreach (Control x in parent.Controls)
{
if ((x.GetType() == typeof(TextBox)))
{
((TextBox)(x)).Text = "";
}
if (x.HasControls())
{
CleartextBoxes(x);
}
}
}
on your drop down change event call this funcation as:
CleartextBoxes(this);
Ok Try this, you have update panel with 20 textbox in it. In the Update panel get all textboxes in one div like this :
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager2" runat="server" ScriptMode="Release"></asp:ScriptManager>
<asp:UpdatePanel runat="server" ID="div_d2">
<ContentTemplate>
<div runat="server" id="div_d">
<asp:TextBox runat="server" ID="txt1">
</asp:TextBox>
<asp:TextBox runat="server" ID="txt2"></asp:TextBox>
</div>
</ContentTemplate>
</asp:UpdatePanel>
<asp:Button runat="server" ID="btnClear" Text="dasdas" OnClick="btnClear_Click" />
</form>
When the textboxes are in the div the clear code will work like this example I show you :
protected void btnClear_Click(object sender, EventArgs e)
{
clearText(div_d);
}
private void clearText(Control PanelID)
{
foreach (Control c in PanelID.Controls)
{
if (c is TextBox)
{
TextBox thetextBox = c as TextBox;
thetextBox.Text = "";
}
}
}

ASP updatepanel doesn't refresh ajax tabpage

I have an ajax tabcontainer in an updatepanel with all tabpages set visible until you want to add a tabpanel based on the dropdownlist selected value
CODE:
<cc1:TabContainer ID="tabControlParameters" runat="server" CssClass="ajax__tab_xp"
ScrollBars="Both" ActiveTabIndex="15" UseVerticalStripPlacement="True">
<%--EnvironmentTab --%>
<cc1:TabPanel ID="pnlEnvironment" HeaderText="Environment" runat="server" Visible="false">
<ContentTemplate>
//somecontent
</ContentTemplate>
</cc1:TabPanel>
<cc1:TabPanel ID="pnlDatabase" HeaderText="Environment" runat="server" Visible="false">
<ContentTemplate>
//somecontent
</ContentTemplate>
</cc1:TabPanel>
<cc1:TabPanel ID="pnlFirstError" HeaderText="Environment" runat="server" Visible="false">
<ContentTemplate>
//somecontent
</ContentTemplate>
</cc1:TabPanel>
With a button add which is inside the Updatepanel and has a correct async trigger assigned to it.
From C# codebehind I've made a loop to check if the dropdownlist selectedvalue = panel_headertext if so make it visible
CODE:
protected void btnAddParameters_Click(object sender, EventArgs e)
{
String Parameter = ddlParameterTypes.SelectedValue.ToString();
AjaxControlToolkit.TabContainer container = (AjaxControlToolkit.TabContainer)tabControlParameters;
foreach (object obj in container.Controls)
{
if (obj is AjaxControlToolkit.TabPanel)
{
AjaxControlToolkit.TabPanel tabPanel = (AjaxControlToolkit.TabPanel)obj;
if (tabPanel.HeaderText == ddlParameterTypes.SelectedValue)
{
tabPanel.Visible = true;
tabPanel = tabControlParameters.ActiveTab;
container.ActiveTab = tabPanel;
}
}
}
}
Now this works perfectly if the updatepanel trigger is set to fullPostback but it's set to async postback then it only works on the first click even though the event is fired every time I'm clicking on the button. Am I missing something obvious here?
Petar
You have the same value in HeaderText for each of your TabPanels. I think it'll work if you correct the HeaderText attributes.

cross page posting asp.net not returning values

I have a web form as
<asp:TextBox ID="txtname" runat="server" Text="Post on Next Page"/>
<asp:Button ID="btn1" runat="server" PostBackUrl="~/Page2.aspx" Text="Post on next page" />
Now on Page2.aspx the code-behind is as follows:
protected void Page_Load(object sender, EventArgs e)
{
if(PreviousPage!=null && PreviousPage.IsCrossPagePostBack)
{
TextBox txt1 = (TextBox)PreviousPage.FindControl("txtname");
label1.Text = "Value: " + txt1.Text;
}
}
I end up getting the error object reference not set to instance of an object for txt1
Where label1 is a label used to display the output. However, the value is not displayed.
What step am i missing?
Try this
if (PreviousPage != null && PreviousPage.IsCrossPagePostBack)
{
//get the content place holder from master page of your previous page where your controls are placed
//In this code the txtname textbox is placed inside ContentPlaceHolderID="MainContent"
var cp =PreviousPage.Master.FindControl("MainContent") as ContentPlaceHolder;
//find the textbox inside content place holder from previous page
TextBox txt1 = cp.FindControl("txtname") as TextBox;
label1.Text = "Value: " + txt1.Text;
}
Are you sure that PostBackURL is valid on a Textbox? Normally this attribute is attached to something that submits, such as a Button or LinkButton, eg:
<form runat="server">
Name:<asp:textbox id="TextBox1" runat=Server />
<asp:button id="Button1" Text="Submit"
PostBackUrl="demo_postbackurl.aspx" runat="Server" />
</form>
Edit: Aha! - you do use a button.
Your code looks OK to me.
If the TextBox is within another control FindControl might not find it - if (for example) it's within a Panel you would need to do something like
TextBox txt1 = (TextBox)PreviousPage.MyPanel.FindControl("txtname");
If it's not within another control then I'm afraid I don't know.

textBox ontextChanged not firing when user adds text

I am creating a textBox within a repeater like this ( so there are many textboxes created inside a loop and added to the repeater control)
.aspx.cs
TextBox textBox = new TextBox();
textBox.TextChanged += new EventHandler(textBox_TextChanged);
and I have a function like this for changing the textBox background color to white if that textbox has some text(it is yellow on creation of the form)
protected void textBox_TextChanged(object sender, EventArgs e)
{
TextBox textBox = sender as TextBox;
if (textBox.Text != String.Empty)
{
textBox.BackColor = System.Drawing.Color.White;
}
}
but the function doesn't seem to be hit at all. Any pointers on what I am doing wrong?
Thanks.
I would suggest to save the round trip to the server and do it with javascript. When you create your control in the code behind add the onchange client event attribute and handle it:
myTextBox.Attributes.Add("onchange",
"this.style.backgroundColor = (this.value != '')?'#fff':'yellow';");
Hope it helps!
Sample java Script
<script type="text/javascript" language="javascript">
function runScript(evt, ID) {
var ctl = document.getElementById(ID.id);
if (ctl.value == '') {
ctl.style.backgroundColor = '#FFFF00';
}
else
ctl.style.backgroundColor = '#FFFFFF';
return true;
}
</script>
Sample Repeater Control HTML
<asp:Repeater ID="rpt" runat="server">
<HeaderTemplate>
<table>
<tr>
<td>
textBox
</td>
</tr>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td>
<asp:TextBox ID="ed" runat="server" BackColor="Yellow" onkeyUp="return runScript(event, this)" autocomplete="off"></asp:TextBox>
</td>
</tr>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>
Thank you guys for the help. This is the final code I used
.aspx.cs.
textBox.Attributes.Add("onkeypress","javascript:changebackgroundcolor()");
.aspx
<script type="text/javascript">
function changebackgroundcolor() {
var element;
for (var i = 0; i < document.forms[0].elements.length; i++) {
element = document.forms[0].elements[i];
switch (element.type) {
case 'textarea':
if (element.value.length > 0) {
element.style.borderwidth = "thin";
element.style.bordercolor = "White";
element.style.borderstyle = "solid";
}
break;
}
}
}
</script>

Disabling PostBack for blank/default ListItem in DataBound DropDownList

I have a DropDownList that is populated from a datasource. After it is bound, I place an empty field at the top of the list so that it appears blank to the user (creating a sort of 'default item'). I have some code behind handling the SelectedIndexChanged event, but it doesn't really need to be executed if the user were to select the empty ListItem.
Here is my code:
.aspx
<asp:DropDownList ID="dropDownList" runat="server" AutoPostBack="true" OnSelectedIndexChanged="dropDownList_SelectedIndexChanged">
</asp:DropDownList>
C# Codebehind adding the blank ListItem
dropDownList.Items.Insert(0, new ListItem(String.Empty, String.Empty));
dropDownList.SelectedIndex = 0;
Since I don't need the page to do a postback when the user clicks just this specific index, I want to disable postback entirely for just this listitem. Is this even possible? If so, how?
Set disabled="disabled", this will make the item not selectable (and not do postback)
<asp:DropDownList runat="server" ID="dddl">
<asp:ListItem Text="" disabled="disabled" Selected="True"></asp:ListItem>
<asp:ListItem Text="test"></asp:ListItem>
</asp:DropDownList>
Alternatively if you want to be able to select the first (empty) item but not do postback, do this:
<asp:DropDownList runat="server" ID="dddl" AutoPostBack="true" onchange="if(this.selectedIndex == 0)return false;">
<asp:ListItem Text="" Selected="True"></asp:ListItem>
<asp:ListItem Text="test"></asp:ListItem>
</asp:DropDownList>
You could add a required field validator. Then set the CausesValidation property of the DropDownList to true. This will prevent the postback and also provide the end-user feedback.
<asp:DropDownList ID="dropDownList" runat="server" AutoPostBack="true" OnSelectedIndexChanged="dropDownList_SelectedIndexChanged" CausesValidation="true">
</asp:DropDownList>
<asp:RequiredFieldValidator ID="rfvDropDownList" runat="server" ErrorMessage="Must select a value!" ControlToValidate="dropDownList" />
Could you add an onChange attribute to run a JS function that checks if the value is empty before posting back?
i.e.
dropDownList.Attributes.Add("onChange", "javascript: return ddlChange()");
function ddlChange
{
if(document.getElementById("<%= dropDownList.ClientID %>").value == "")
return false;
return true;
}
1.web control use postback, add attribute to cancel postback.
but option will not be selected.
protected void rblRecentOrder_DataBound(object sender, EventArgs e)
{
RadioButtonList rbl = sender as RadioButtonList;
ListItem itemX = rbl.Items.FindByText("NA");
// if no NA item then add it
if (itemX == null)
{
itemX = new ListItem("NA");
// set item cancel postback, but option will not be selected
itemX.Attributes.Add("onclick", "return false;");
}
}
2.or use javacsript call postback when need
<script>
function myPostback() {
// call asp.net postback
__doPostBack('tagName', 'params');
}
// TextBox
function updateValue(id, value) {
let obj = document.getElementById(id);
obj.value = value;
}
// Label
function updateInnerHTML(id, value) {
var obj = document.getElementById(id);
obj.innerHTML = value;
}
// DrowdownList
function setSelectOption(id, value) {
let obj = document.getElementById(id);
if (obj)
obj.value = value;
}
// RadioButtonList
function selectRadio(id) {
let obj = document.getElementById(id);
// input type=radio
if (obj) {
let items = obj.getElementsByTagName("INPUT");
for (var i = 0; i < items.length; i++) {
items[i].checked = true;
}
}
}
</script>
c#
switch(Request.Form["__EVENTTARGET"])
{
case "tageName":
var params = Request.Form["__EVENTARGUMENT"];
//..........
break;
}

Categories