I would like to the ToolTip always be the same as the ASP TextBox's Text. Of course I can write
AnyTextBox.Text = "any text";
AnyTextBox.ToolTip = "any text";
but I do not want to duplicate hundreds of assignment statements.
I also could write change event handlers for the Text property, but I do not want to write dozens of event handlers just for this (if there is a more elegant solution)
Is there? Something like this:
<asp:TextBox ID="AnyTextBox" runat="server" ToolTip="binding magic goes here, but how?">
Thx in advance
You could write your own custom control which inherits from TextBox? I used the Text property to set the tooltip, but you can do it the other way around if you want.
Control:
public class TooltipTextBox : TextBox {
public new string Text {
get { return base.Text; }
set
{
base.Text = value;
this.ToolTip = value;
}
}
}
Markup:
<my:TooltipTextBox ID="AnyTextBox" runat="server" Text="binding magic goes here">
As far as i know there is no such automatism. For what it's worth, maybe you can use PreRender:
protected void Page_PreRender(Object sender, EventArgs e)
{
var allTextControlsWithTooltips = new List<WebControl>();
var stack = new Stack<Control>(this.Controls.Cast<Control>());
while (stack.Count > 0)
{
Control currentControl = stack.Pop();
if (currentControl is WebControl && currentControl is ITextControl)
allTextControlsWithTooltips.Add((WebControl)currentControl);
foreach (Control control in currentControl.Controls)
stack.Push(control);
}
foreach (var txt in allTextControlsWithTooltips)
txt.ToolTip = ((ITextControl)txt).Text;
}
You could also use a UserControl which handles this event, then you just need to put it on all of the pages that should behave in this way. Or you could let all pages inherit from one base page.
I think using a JavaScript event handler will be your easiest solution. You don't need to write hundreds of event handlers though. Just write one and then use that same event handler for all your text boxes!
<asp:TextBox ID="AnyTextBox" runat="server" onchange="setTooltip(this)" />
And then the script would be
function setTooltip(textbox) {
textbox.title = textbox.value;
}
That's it! Set that onchange event for all your Textboxes who you want to have this tooltip behavior.
You can do this in the TextChanged event of the textbox :
<asp:TextBox ID="AnyTextBox" runat="server" TextChanged="AnyTextBoxTextChanged">
protected void AnyTextBoxTextChanged(object sender, EventArgs e)
{
this.AnyTextBox.Tooltip = this.AnyTextBox.Text;
}
That depends if you are looking for "live update" of tooltip = i.e. do you want to change the tooltip when the user changes the text on website? Then use "onchange" event of the input and JS function that would change its "title" attribute on each event call.
Or you want to ease of your server-side work and do not want to specify tooltip and text for each item, then go with custom control way (and I recommend RGraham code).
Or match both methods and use custom control that would also provide JS "refresh" code :-)
Try using jquery
$(function () {
var maybe = true;
var text = $('.myTextBox').val();
if (maybe) {
$('.myTextBox').attr('title', text);
}
});
Related
OK, so I am trying to apply the accounting number format for all textboxes on my Form.
Now, I did some research here and found this post that will help me to set the format.
And then I found another post to apply the format for all textbox controls on the form without adding the format code individually to all controls.
Well, the thing is that the code on the format uses the control name, which will bind it to a single textbox control. I tried the control name (TextoBox) instead, and it also failed.
There is another issue to consider, that even if I manage to get past the above problem, the code from format is an event, named after the control name, so I do not think it will work if I apply it to a class or method and call for it.
While I already do have the solution to what I want, I would like to know if there is a faster way to apply it, which will not add so much lines to my code. Trying to learn how to keep things easier to read, doing less with more. Any advise?
Thanks for reading.
It sounds like you have all the pieces, just need help putting it together. For the ControlName, you can cast the sender object to the control and access its Name property.
void SetProperty(Control ctr)
{
foreach (Control control in ctr.Controls)
{
if (control is TextBox)
{
control.Leave += control_Leave;
}
else
{
if (control.HasChildren)
{
SetProperty(control);
}
}
}
}
void control_Leave(object sender, EventArgs e)
{
var textBox = sender as TextBox;
Double value;
if (Double.TryParse(textBox.Text, out value))
textBox.Text = String.Format(System.Globalization.CultureInfo.CurrentCulture, "{0:C2}", value);
else
textBox.Text = String.Empty;
}
Usage:
SetProperty(this);
Also, from my comment on the OP: If accounting is truly important, I would suggest using the Decimal type instead of Double. Double will be faster, but Decimal is more precise. Figure out which trade off makes sense and make a decision based on that.
Edit per comments:
myTextBox.Leave -= control_Leave
If you know the name of the control, the above will work. You will need to do this after you use SetProperty(this). If you want to handle this inside the SetProperty() method, do a check on control.Name == "myTextBox".
You can subscribe multiple controls event(that use the same args) to the same event handler :
public YourFormConstructor()
{
foreach(var textbox in form.Controls.OfType<TextBox>())
textbox.Leave += FormatCurrencyText;
}
private void FormatCurrencyText(object sender, EventArgs e)
{
var textbox = sender as TextBox;
Double value;
if (Double.TryParse(textbox.Text, out value))
textbox.Text = String.Format(System.Globalization.CultureInfo.CurrentCulture, "{0:C2}", value);
else
textbox.Text = String.Empty;
}
I have a TextView that starts out with a default text value, and then based on what a user does, that TextView's text needs to change in the code when a button is clicked. Seems simple enough, yet I'm running into problems.
Currently, what is happening is when the user clicks the submit button which triggers the change of the text, the new text is just being added to the screen under the original TextView instead of just simply changing the text value. It's almost as if it's adding a new TextView.
Here is the code that does this:
lblSlogan.Invalidate();
lblSlogan.SetText(currentSlogan.Slogan, TextView.BufferType.Normal);
I also tried it this way, with no luck:
lblSlogan.Invalidate();
lblSlogan.Text = currentSlogan.Slogan;
lblSlogan is a TextView. Am I missing something? I also tried it without the invalidate(), but that changed nothing either.
Thanks.
-- edit --
It's important to note that I'm using C# with Xamarin. Not Java. Here is my click method for the button. This is where the TextView change happens.
btnOk.Click += delegate(object sender, EventArgs e)
{
if (answerBox.Text.ToLower() == currentSlogan.Company.ToLower())
{
// correct answer
currentUserScore += currentSlogan.Points;
currentSlogan.Answered = true;
DatabaseBuffer.MarkSloganAnsweredAndUpdateScore(currentSlogan, currentUserScore);
currentSlogan = DatabaseBuffer.GetNextUnansweredSlogan(currentSlogan.ID);
}
if (currentUserScore >= pointsToPass)
{
// user has beaten level
}
else
{
lblSlogan.SetText(currentSlogan.Slogan, TextView.BufferType.Normal);
answerBox.Text = "";
}
};
i didn't understand why you are calling the method invalidate() on your TextView, otherwise ,a simple code like this should work (add this code in the onCreate() method) :
setContentView(R.layout.main);
TextView lblSlogan = (TextView) findViewById(R.id.lblSlogan);
Button btnChangeSlogan = (Button) findViewById(R.id.btnChangeSlogan);
btnChangeSlogan.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
lblSlogan.setText("Put your new text here");// cal setText() in the onclick method when ever you want to change the text
}
});
I think your problem is this:
answerBox.Text.ToLower() == currentSlogan.Company.ToLower()
you should use "equals", not "==".
(answerBox.Text.ToLower()).Equals( currentSlogan.Company.ToLower())
A couple of points here.
Personally I use the built in abstract methods that Xamarin provides. They tend to give me much more consistent results. You can simply assign the new value to the .Text property of the Textview. IE
textView.Text = newValue;
In C# you do not need to use the .Equals operator to do string comparisons. That's strictly a Java requirement. See this [link] (Why would you use String.Equals over ==?).
Assign listener to button and in that listener you add text with the setText() method (or appendText() for appending..)
findViewById(R.id.button2).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
text.setText("This is new text");
}
});
Here you can add text View Dynamically.
var aLabel = new TextView (this);
aLabel.Text = "Hello Text!!!";
aLabel.SetTextSize (Android.Util.ComplexUnitType.Dip, 15f);
RelativeLayout ll = new RelativeLayout(this);
ll.AddView(aLabel);
I have this control:
I'm trying to create a kind of validation, that whenever the user enters text to the TextBox, the "Add" button will be Enabled, and when the text is "" (null), the "Add" button is disabled.
I dont want to use validators.
here's the code:
protected void addNewCategoryTB_TextChanged(object sender, EventArgs e)
{
if (addNewCategoryTB.Text != "")
addNewCategoryBtn.Enabled = true;
else
addNewCategoryBtn.Enabled = false;
}
The problam is, that when the user enter's text, the "Add" button doesn't changes from disabled to enabled (and vice versa)...
any ideas?
Is it Web Forms? In Web Forms the TextChanged event of the TextBox won't fire by default.
In order to fire the event, you have to set the AutoPostBack property of the TextBox to true.
BUT, this would perform a HTTP post, what is kink of ugly, or you can wrap that in an UpdatePanel
A more elegant option, is to do that using jQuery, to do that in jQuery, you'll need some code like:
$(document).ready(function() {
$("#<%= yourTextBox.ClientID %>").change(function() {
var yourButton = $("#<%= yourButton.ClientID %>")
yourButton.attr('disabled','disabled');
yourButton.keyup(function() {
if($(this).val() != '') {
yourButton.removeAttr('disabled');
}
});
});
});
You'll need to accomplish this with Javascript, since ASP.NET is incapable of performing such client-side modifications. Think about it ... every time you pressed a letter inside the text box, it would have to postback and refresh the page in order to determine if the text box was empty or not. This is one way that ASP.NET differs from Winforms/WPF.
TextChanged events will make postback on server every time. You don't need to increase those request for such task.
You can use jquery to achieve this
var myButton = $("#btnSubmit");
var myInput=$("#name");
myButton.prop("disabled", "disabled");
myInput.change(function () {
if(myInput.val().length > 0) {
myButton.prop("disabled", "");
} else {
myButton.prop("disabled", "disabled");
}
});
JS Fiddle Demo
You just need to take care of elements Id when you are using Server Controls. For that Either you can use ClientID or set property ClientIdMode="Static"
I have a textbox with a live search function. It is working all good except one problem. If I type any characters on it, it just loses its focus. If I set textbox.Focus(), the cursor goes at the beginning of the textbox.
I have tried most of solutions on the internet. Please check my codes below.
asp:TextBox ID="searchCompany" runat="server" Text="" CssClass="searchCompany" AutoPostBack="true" Width="190px" OnTextChanged="searchCompany_TextChanged"></asp:TextBox>
In page_Load
protected void Page_Load(object sender, EventArgs e)
{
//ScriptManager1.RegisterAsyncPostBackControl(Menu1);
menuDisplay();
searchCompany.Attributes.Add("onkeyup", "setTimeout('__doPostBack(\\'" + searchCompany.UniqueID + "\\',\\'\\')', 0);");
//searchCompany.Attributes.Add("onfocus", "javascript:setSelectionRange('" + "','')");
//searchCompany.Focus();
}
and I have tried javascript as below
<script type="text/javascript">
function setSelectionRange() {
var inputField = document.getElementById('searchCompany');
if (inputField != null && inputField.value.length > 0) {
if (inputField.createTextRange) {
var FieldRange = inputField.createTextRange();
FieldRange.moveStart('character',inputField.value.length);
FieldRange.collapse();
FieldRange.select();
}
}
}
</script>
I have tried to put codes on a method "searchCompany_TextChanged" which is calling if user type any characters on a textbox everytime however it is not working as well.
I saw other solutions with using Textbox.Select() but System.Windows.Control is not working in asp.net i guess.
Any idea??
There's a very simple trick that's worked for me. Basically, set the text value of the of input to itself to its own text value, and that will move the cursor to the end of the text. Then just focus it. This code uses jQuery to demonstrate that, but you should be able to do that in straight JS as well.
HTML
<input type="text" id="focusText"></input>
<button id="focusButton">Set Focus</button>
JavaScript
$("#focusButton").click(function() {
var text = $("#focusText").val();
$("#focusText").val(text).focus();
})
Here's a non jQuery example of the JavaScript, HTML should be the same:
document.getElementById("focusButton").onclick = function() {
var inputElement = document.getElementById("focusText");
var text = inputElement.value;
inputElement.value = text;
inputElement.focus();
}
Here's a fiddle demonstrating the non-jQuery version of the code: http://jsfiddle.net/C3gCa/
From within the code-behind of an ASP .NET web user-control (ascx) I need to get access (at runtime) to its parent, a div element. The aim is simple as to modify the visibility of the mentioned parent div.
I can not touch so much of the web-page code so I'd need a solution requiring only modifications in the user-control's code behind.
So in the HTML "part" of the code of the web page I have this:
<div id="parentDIV" runat="server">
<uc:MyUserControl ID="myUserControlInstance" runat="server" />
</div>
I'd like to do in the code behind of the user-control something like this:
this.Container.Visible = false;
Note that I'm not asking if it is a good practise or not to do this.
EDIT:
The user-control code behind does not "know" about the ID of the parent DIV.
I would hide it on the client. Decorate your user control container (div?) with a class like "awesomeUserControl". Then emit some javascript using the ScriptManager object to hide the parent like this:
ScriptManager.RegisterStartupScript(this, this.GetType(), "HideMyAwesomeUserControl", "$('.awesomeUserControl').parent().hide();", true);
The better way...
What you should do is to create a custom event in your user control, to which your container will subscribe - very much like subscribing to a button event, only this is your custom control. This event passes information to your container which can then discern from it what it needs, such as whether or not the div should/not be visible.
It might look something like:
protected void Page_Load(object sender, EventArgs e)
{
this.myuserControl.Update += new MyUserControlUpdateEventHandler(myuserControl_Update);
}
void myuserControl_Update(object sender, MyuserControlEventArgs e)
{
this.parentDiv.visible = !e.ShouldHideUI;
}
This method will decouple your parent with the user control, i.e. your user control doesn't have to have any knowledge at all of the parent's controls, nor should it.
If you are curious, here is a rough example of how your user control will define such an event:
public class MyuserControlEventArgs : EventArgs
{
public bool ShouldHideUI { get;set;}
public MyuserControlEventArgs (bool shouldHideUI)
{
this.ShouldHideUI = shouldHideUI;
}
}
public delegate void MyUserControlUpdateEventHandler(object sender, MyuserControlEventArgs e);
public event MyUserControlUpdateEventHandler Update;
protected void OnUpdate(MyuserControlEventArgs e)
{
if (Update!= null)
Update(this, e);
}
Your user control will simply need to call OnUpdate whenever it feels its subscribers need to know about it.
The Quick and Dirty way...
If you need quick and dirty, then try this (inside your user control):
TheParentControl parentControl = (TheParentControl)this.Parent;
parentControl.ParentDiv.Visible = true;
The key is to cast to the appropriate type (apparently your user control would know what type of parent it has), then set the parent's property. You might expose your div as a property in the parent control. Note, that parent could be ANY control (page, FooControl, BarControl, whatever) whose control collection your user control resides. Once you get a handle to the parent, you can even FindControl() to find a control by name.
You're almost there....
this.Parent.Visible = false;
When all controls get rendered, the HTML Parent child controls can be determined like below.
I am using while loop, so in case you add some other intermediate control, it may not give crash or unexpected results.
public Control ParentControl
{
get
{
Control ctl = this.Parent;
while (true)
{
if (ctl == null) break;
if (ctl.ID.Equals("parentDIV"))
{
break;
}
ctl = ctl.Parent;
}
return ctl;
}
}
if(ParentControl != null)
ParentControl.Visible = true|false;
Am I missing something, it sounds like you have a usercontrol and an aspx page (both have code behind's).
The user control appears to have been added to the aspx page, wrapped in a div. YOu've made the div control runat server (though you can still do this via htmlcontrol).
All you ned to do to manage the div is:
parentDIV.visible = false;
or whatever you need to do with the div.
Why does the UC code behind need to know about the APSX pages DIV, it doesn't.