i am working with a winform application , and in the richbox_textchange i would like to detect whether the entered text is English or not because if it is english i`ll perform LeftToRight typing else RightToLeft typing .
I used that code :
private void richTextBox1_TextChanged(object sender, EventArgs e)
{
if (CultureInfo.CurrentCulture.TextInfo.IsRightToLeft)
{
label1.Text = "RTL";
}
else
{
label1.Text = "LTR";
}
}
but i always get : LTR only , label1 never change text to RTL even if i typed arabic !!!
EDIT : ANSWERED !!
Firstly Thanks to everybody for helping me here and especially Oded , here is the solution i could figure out
private void richTextBox1_TextChanged(object sender, EventArgs e)
{
if (InputLanguage.CurrentInputLanguage.Culture.TextInfo.IsRightToLeft)
{
label1.Text = "RTL";
}
else
{
label1.Text = "LTR";
}
}
You need to add the correct namespace to the top of your class:
using System.Globalization;
At this point the CultureInfo and TextInfo classes will be available directly.
Update:
It appears that you are trying to find out the current input language. Take a look at the InputLanguage class and its methods. It is in the System.Windows.Forms namespace.
InputLanguage.CurrentInputLanguage.Culture.TextInfo.IsRightToLeft
The problem is that CultureInfo.CurrentCulture.TextInfo.IsRightToLeft is returning information about the current system setting, not the specific text that was typed into the textbox.
It has no idea if you've typed English, or Arabic, or Cyrillic into the textbox, and it doesn't care. All it cares about is what your computer is configured to display, that's why it never changes.
Unfortunately, I don't believe it's possible to obtain the language of a particular string of text. You might have some luck with the Text.EncodingInfo.CodePage property, but it's unlikely that anything will tell you the language of text with absolute certainty. Another possible approach is to iterate through the characters in the string, checking them for information. Something like that is described here.
All things considered, it's probably better to just ask the user. What do other applications do that support multiple input languages?
Related
I am using below Property example to make some calculation on textbox and if textbox is null I am assigning zero to it so calculation won't fail as you can see I am using Math.Round and I want to make several checks on these textbox input like
textbox that only accepts numbers I searched and found method 1
I want my textbox to be formated I searched and found Method 2
Now my question is ..
Is there any way to mareg all these method in the property method I am using
so my code won't be like "spaghetti code" ?
is there any better ways to do these checks ?
Thank you in advance
Property example
public double ItemPriceResult
{
get
{
return Math.Round(ItemCost * RevenuePercentage / 100 + ItemCost, 0);
}
}
Method 1
private void textBox1_TextChanged(object sender, EventArgs e)
{
if (System.Text.RegularExpressions.Regex.IsMatch(textBox1.Text, "[^0-9]"))
{
MessageBox.Show("Please enter only numbers.");
textBox1.Text = textBox1.Text.Remove(textBox1.Text.Length - 1);
}
}
Method 2
textBox1.Text = string.Format(System.Globalization.CultureInfo.GetCultureInfo("id-ID"), "{0:#,##0.00}", double.Parse(textBox1.Text));
UPDATE after some answers
MaskedTextBox seems fit my needs I read and searched and below some question
if you kindly would like to help me
I need to use MaskedTextBox because I can set it to accept
number and I can also force number formating so
also I need to make number textboxs easer to read for users
so 1000 will be come 1,000
and 10000 will be come 10,000
then according to Microsoft Docs formating MaskedTextBox to fit my needs
Masked MaskedTextBox with 999,999,999,
second I do not want the PromptCharto be visible I google it but none of search result did it
Try this , it will accept only numbers and u can format the string as u want using regex.
public static string ToMaskedString(this String value)
{
var pattern = "^(/d{2})(/d{3})(/d*)$";
var regExp = new Regex(pattern);
return regExp.Replace(value, "$1-$2-$3");
}
You have a TextBox. Alas you don't tell what kind of TextBox you use. System.Windows.Forms.TextBox? System.Web.UI.MobileControls.TextBox?
You write "if text box is null I am assigning zero to it". I assume that you mean that if no text is entered in the text box you assume that 0 is entered.
Furthermore you want to format the output of the text box whenever the text is changed. So while the operator is typing text you want to change this text? For the operator this is very annoying.
Wouldn't you prefer that the operator is obliged to type his text in the format you desire, helping him visually. For this you may use the class MaskedTextBox
The MaskedTextBox has a property Mask, which forces the operator to type in a certain format. I'm not really familiar with what you do with the format {0:#,##0.00}, but I assume you want the output double in a real format with two digits after the decimal point using the decimal point and the thousand separator as common in the current culture.
via the designer put in initialize component:
this.maskedTextBox1.Mask = "99990.00";
after adding the event for text changed:
private void maskedtextBox1_TextChanged(object sender, EventArgs e)
{
double enteredValue = 0.0; // value to use when empty text box
if (!String.IsNullOrEmpty(this.maskedtextBox1.Text))
{
enteredValue = double.Parse(maskedTextBox1.Text, myFormatProvider)
}
ProcessEnteredValue(enteredValue);
}
}
After your edit, the specifications have changed.
While entering the number in the text box, the operator should not have any visual feedback of the formatting of his number.
The operator is free to enter the real number in any commonly used format.
The value of the text box should not be used while the operator is editing the text box.
Only after editing is finished, the value of the text box should be interpreted for correctness, and if correct it should be used.
The actually used value should be displayed in the text box in a defined format.
The desire not to show any visual feedback while entering is understandable. After all, the program doesn't care whether the operator types 1000, 1000.00, or even 1.0E3.
The MaskedTextBox is especially used to force the operator to enter his number in a given format. Since this is not desired, my advise would be to use a TextBox instead of aMaskedTextBox.
However, because you give the operator the freedom to enter his number in any way he wants, including copy-paste, repairing typing errors, etc. you'll have to add the possibility for the user to express to the program that he has finished entering the number.
An often used method in the windows UI would be a Button. Another possibility would be the enter button. Be aware though that this is not really standard within windows. It might make learning your program a little bit more difficult.
So after the operator notified that he finished editing and the corresponding event function is called, your code could be:
// Get the numberformat to use, use current culture, or your own format
private readonly IFormatProvider myNumberFormat = CultureInfo.CurrentCulture.NumberFormat
private void OperatorFinishedEditing(TextBox box)
{
// read the text and try to parse it to a double
// accepting all common formats of real numbers in the current culture
bool valueOk = true;
double resultValue = 0;
if (!String.IsNullOrEmpty(box.Text))
{
bool valueOk = Double.TryParse(box.Text, out resultValue);
}
if (valueOk)
{
box.Text = FormatResultValue(resultValue);
ProcessValue(resultValue);
}
else
{
ShowInputProblem();
}
}
Hi I want to create a small program to change windows default language while spell check the user input in any text area in windows. I know too many programs like MS Word or Word Pad, specially these online text editors have spell check so no need to write it from 0 to 100 right?
My primary language for this project is English but I don't know can I use spell check for other languages like French, Arabic, Turkish etc.
I have this for changing language :
public struct LanguageHelper
{
public static void SetLanguage2English()
{
InputLanguage.CurrentInputLanguage = InputLanguage.FromCulture(new CultureInfo("en-US"));
}
public static void SetLanguage2French()
{
InputLanguage.CurrentInputLanguage = InputLanguage.FromCulture(new CultureInfo("Fr-FR"));
}
}
I don't any new lead to use it for this project. Thanks in Advance for every hint or new lead that can help me to complete my project.
I am new in Visual Studio and using visual Studio 2008.
In a project I want to make all text in uppercase while typed by the user without pressing shift key or caps lock on.
I have used this code
TextBox1.Text = TextBox1.Text.ToUpper();
but it capitalize characters after pressing Enter key.
I just want that characters appear in uppercase while typing by the user without pressing shift key or without caps lock on.
Total page code is as...
public partial class Test : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void TextBox1_TextChanged(object sender, EventArgs e)
{
TextBox1.Text = TextBox1.Text.ToUpper();
}
}
Have any one any solution, please guide me.
There is a specific property for this. It is called CharacterCasing and you could set it to Upper
TextBox1.CharacterCasing = CharacterCasing.Upper;
In ASP.NET you could try to add this to your textbox style
style="text-transform:uppercase;"
You could find an example here: http://www.w3schools.com/cssref/pr_text_text-transform.asp
Edit (for ASP.NET)
After you edited your question it's cler you're using ASP.NET. Things are pretty different there (because in that case a roundtrip to server is pretty discouraged). You can do same things with JavaScript (but to handle globalization with toUpperCase() may be a pain) or you can use CSS classes (relying on browsers implementation). Simply declare this CSS rule:
.upper-case
{
text-transform: uppercase
}
And add upper-case class to your text-box:
<asp:TextBox ID="TextBox1" CssClass="upper-case" runat="server"/>
General (Old) Answer
but it capitalize characters after pressing Enter key.
It depends where you put that code. If you put it in, for example, TextChanged event it'll make upper case as you type.
You have a property that do exactly what you need: CharacterCasing:
TextBox1.CharacterCasing = CharacterCasing.Upper;
It works more or less but it doesn't handle locales very well. For example in German language ß is SS when converted in upper case (Institut für Deutsche Sprache) and this property doesn't handle that.
You may mimic CharacterCasing property adding this code in KeyPress event handler:
e.KeyChar = Char.ToUpper(e.KeyChar);
Unfortunately .NET framework doesn't handle this properly and upper case of sharp s character is returned unchanged. An upper case version of ß exists and it's ẞ and it may create some confusion, for example a word containing "ss" and another word containing "ß" can't be distinguished if you convert in upper case using "SS"). Don't forget that:
However, in 2010 the use of the capital sharp s became mandatory in official documentation when writing geographical names in all-caps.
There isn't much you can do unless you add proper code for support this (and others) subtle bugs in .NET localization. Best advice I can give you is to use a custom dictionary per each culture you need to support.
Finally don't forget that this transformation may be confusing for your users: in Turkey, for example, there are two different versions of i upper case letter.
If text processing is important in your application you can solve many issues using specialized DLLs for each locale you support like Word Processors do.
What I usually do is to do not use standard .NET functions for strings when I have to deal with culture specific issues (I keep them only for text in invariant culture). I create a Unicode class with static methods for everything I need (character counting, conversions, comparison) and many specialized derived classes for each supported language. At run-time that static methods will user current thread culture name to pick proper implementation from a dictionary and to delegate work to that. A skeleton may be something like this:
abstract class Unicode
{
public static string ToUpper(string text)
{
return GetConcreteClass().ToUpperCore(text);
}
protected virtual string ToUpperCore(string text)
{
// Default implementation, overridden in derived classes if needed
return text.ToUpper();
}
private Dictionary<string, Unicode> _implementations;
private Unicode GetConcreteClass()
{
string cultureName = Thread.Current.CurrentCulture.Name;
// Check if concrete class has been loaded and put in dictionary
...
return _implementations[cultureName];
}
}
I'll then have an implementation specific for German language:
sealed class German : Unicode
{
protected override string ToUpperCore(string text)
{
// Very naive implementation, just to provide an example
return text.ToUpper().Replace("ß", "ẞ");
}
}
True implementation may be pretty more complicate (not all OSes supports upper case ẞ) but take as a proof of concept. See also this post for other details about Unicode issues on .NET.
if you can use LinqToObjects in your Project
private YourTextBox_TextChanged ( object sender, EventArgs e)
{
return YourTextBox.Text.Where(c=> c.ToUpper());
}
An if you can't use LINQ (e.g. your project's target FW is .NET Framework 2.0) then
private YourTextBox_TextChanged ( object sender, EventArgs e)
{
YourTextBox.Text = YourTextBox.Text.ToUpper();
}
Why Text_Changed Event ?
There are few user input events in framework..
1-) OnKeyPressed fires (starts to work) when user presses to a key from keyboard after the key pressed and released
2-) OnKeyDown fires when user presses to a key from keyboard during key presses
3-) OnKeyUp fires when user presses to a key from keyboard and key start to release (user take up his finger from key)
As you see, All three are about keyboard event..So what about if the user copy and paste some data to the textbox?
if you use one of these keyboard events then your code work when and only user uses keyboard..in example if user uses a screen keyboard with mouse click or copy paste the data your code which implemented in keyboard events never fires (never start to work)
so, and Fortunately there is another option to work around : The Text Changed event..
Text Changed event don't care where the data comes from..Even can be a copy-paste, a touchscreen tap (like phones or tablets), a virtual keyboard, a screen keyboard with mouse-clicks (some bank operations use this to much more security, or may be your user would be a disabled person who can't press to a standard keyboard) or a code-injection ;) ..
No Matter !
Text Changed event just care about is there any changes with it's responsibility component area ( here, Your TextBox's Text area) or not..
If there is any change occurs, then your code which implemented under Text changed event works..
**/*Css Class*/**
.upCase
{
text-transform: uppercase;
}
<asp:TextBox ID="TextBox1" runat="server" Text="abc" Cssclass="upCase"></asp:TextBox>
I use to do this thing (Code Behind) ASP.NET using VB.NET:
1) Turn AutoPostBack = True in properties of said Textbox
2) Code for Textbox (Event : TextChanged)
Me.TextBox1.Text = Me.TextBox1.Text.ToUpper
3) Observation
After entering the string variables in TextBox1, when user leaves TextBox1,
AutoPostBack fires the code when Text was changed during "TextChanged" event.
I had the same problem with Visual Studio 2008 and solved adding the following event handler to the textbox:
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if ((e.KeyChar >= 'a') && (e.KeyChar <= 'z'))
{
int iPos = textBox1.SelectionStart;
int iLen = textBox1.SelectionLength;
textBox1.Text = textBox1.Text.Remove(iPos, iLen).Insert(iPos, Char.ToUpper(e.KeyChar).ToString());
textBox1.SelectionStart = iPos + 1;
e.Handled = true;
}
}
It works even if you type a lowercase character in a textbox where some characters are selected.
I don't know if the code works with a Multiline textbox.
set your CssClass property in textbox1 to "cupper", then in page content create new css class :
<style type="text/css">.cupper {text-transform:uppercase;}</style>
Then, enjoy it ...
I tried:
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
streamWriter.Write(e.Key.ToString());
}
But I don't know how to convert a Key to string correctly. I also tried:
private void textBox1_TextInput(object sender, TextCompositionEventArgs e)
{
streamWriter.Write(e.Text);
}
But this event is not called. The farthest I went was:
private string previous = string.Empty;
private void textBox1_TextChanged(object sender, TextChangedEventArgs e)
{
var text = textBox1.Text.Substring(previous.Length);
streamWriter.Write(text);
previous = textBox1.Text;
}
But this has problems with character deletion, and many other cases.
What should I do?
The easiest option is to use KeyPress instead of KeyDown.
KeyPressEventArgs.KeyChar provides the actual char, already translated appropriately. Just write this char to your stream directly.
Edit:
After seeing in the comments that this is WPF, not Windows Forms (as tagged), the above will not exist.
That being said, I question your goal here - using a textbox to write to a stream, in a character by character fashion, is always going to be problematic. This is due to what you wrote in your last sentence:
But this has problems with character deletion, and many other cases.
Personally, I would take one of two different approaches:
Use a TextBox as a "buffer", and only send the entire contents to the stream when the focus is lost, etc. This way, the user can delete, etc, as needed, and you always have a complete "string" to work with. This would probably be my first choice, if you want the behavior to be similar to what you're after now.
Don't use a TextBox for this. Use some other control which allows text entry, but not deletion or selection. If you must use a TextBox, and must handle key-by-key streaming, then you should restrict the input (via a behavior or attached property) to only the character you wish, which means disabling deletion.
I'm using the following code to decide if a '.' (full stop) has been entered into a webbrowser control:
private void body_KeyUp(object sender, HtmlElementEventArgs e)
{
if (e.KeyPressedCode == '.')
{
// Do something
}
}
According to msdn KeyPressedCode returns an ASCII value. What I get by breakpointing is '190' if I enter a '.' however. This is not even listed in the standard ASCII table.
Obviously I could simply test for 190 but I fear that KeyPressedCode might return different values on different systems with different code pages, languages and so on.
So can you please explain me why KeyPressedCode returns '190' instead of '46' and how I can manage this problem 'safely'?
Interestingly enough the return value for ' ' (space) is always correct ('32').
Playing with System.Text.Encoding.GetEncoding and different code pages didn't solve the problem, I don't have much experience with code pages however.
You were likely using a wired keyboard, because keycode 190 is an OEM number keycode of .. If you were using a laptop it would behave as you expected.
Just a wild guess, but have you checked the values of e.AltKeyPressed , e.CtrlKeyPressed and e.ShiftKeyPressed ? Hope you see what I'm getting at...