I'm using Bindings to populate a Listbox, with TextBlocks, etc.
The question is :
How do I make sure that the text bound to the the Text property of a TextBlock is of specific length, or that it is displayed trimmed at some specific character length (e.g. "some very very long t..."), so that the text doesn't "overflow" the phone screen or its container?
Since Mango SDK, there is a property call TextTrimming.
So this xaml
<TextBlock Text="aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" TextTrimming="WordEllipsis" Width="200" />
will produce somehting like "aaaaaaa....."
Tricky one! I forced myself to think that if the characters exceeds, say some 10 then i am going to append dots to it. So i added this textchanged event to the textbox and then made the code as follows:
private void TestTextBox_TextChanged(object sender, TextChangedEventArgs e)
{
string temp = TestTextBox.Text;
if (temp.Length > 10)
{
char[] charArray=temp.ToCharArray();
temp = new string(charArray, 0, 10);
temp += "...";
}
TestTextBox.Text = temp;
}
Related
I have created a Windows Forms application and I am using label_1.Visible = false; to make my label invisible.
I want to only make the first letter of the label visible.
How can I do it?
Visibility is all-or-nothing concept: if a label, or any other component for that matter, is marked invisible, none of it is going to appear on the form.
If you want to show only the first few letters of a string in a label, use Substring method to assign label's text. In order for this to work, the actual text must be stored somewhere outside the label - say, in labelText field:
private string labelText = "Quick brown fox";
...
label_1.Text = labelText.Substring(0, 1); // Only the first character is shown
Based on your answer to a comment, it sounded like you were interested in a Marquee-style display. Here's one way to do that, by storing the whole string in one variable, and then only displaying parts of it in a label.
In the example below, we have a string of text to display stored in a variable. We add a label to display the text, and a timer is used to repeatedly change the text to make it appear that it's scrolling.
To see it in action, start a new Windows Forms Application project and replace the partial form class with the following code:
public partial class Form1 : Form
{
// Some text to display in a scrolling label
private const string MarqueeText =
"Hello, this is a long string of text that I will show only a few characters at a time. ";
private const int NumCharsToDisplay = 10; // The number of characters to display
private int marqueeStart; // The start position of our text
private Label lblMarquee; // The label that will show the text
private void Form1_Load(object sender, EventArgs e)
{
// Add a label for displaying the marquee
lblMarquee = new Label
{
Width = 12 * NumCharsToDisplay,
Font = new Font(FontFamily.GenericMonospace, 12),
Location = new Point {X = 0, Y = 0},
Visible = true
};
Controls.Add(lblMarquee);
// Add a timer to control our marquee and start it
var timer = new System.Windows.Forms.Timer {Interval = 100};
timer.Tick += Timer_Tick;
timer.Start();
}
private void Timer_Tick(object sender, EventArgs e)
{
// Figure out the length of text to display.
// If we're near the end of the string, then we display the last few characters
// And the balance of characters are taken from the beginning of the string.
var startLength = Math.Min(NumCharsToDisplay, MarqueeText.Length - marqueeStart);
var endLength = NumCharsToDisplay - startLength;
lblMarquee.Text = MarqueeText.Substring(marqueeStart, startLength);
if (endLength > 0) lblMarquee.Text += MarqueeText.Substring(0, endLength);
// Increment our start position
marqueeStart++;
// If we're at the end of the string, start back at the beginning
if (marqueeStart > MarqueeText.Length) marqueeStart = 0;
}
public Form1()
{
InitializeComponent();
}
}
Strings are technically byte arrays, meaning each letter can be accessed with an index.
For example:
string x = "cat";
char y = x[0];
// y now has a value of 'c'!
Perform this on the string being used for your label and use the result for your label instead. I want to also add that you need to set label_1.Visible = true; otherwise nothing will appear at all.
Applying the above to your code, you should arrive at something like this:
label_1.Visible = true;
label_1.text = label_1.text[0].ToString();
Hope that works for you!
I have 2 comboboxes for the font and the fontsize. When I click them it changes the font size or the font in my richtextbox. Now I want it to work like in word. If the line you just moved to is in a different font or size. It should detect that and change the comboxes to match the font and size of the current line. Somoeone else asked this same question and got a result which didn't work for me. It was as follows
private void richTextBox1_SelectionChanged(object sender, EventArgs e)
{
MessageBox.Show("we got here"); // this is my added part to let me know if the code is even getting executed. It is not.
richTextBox1.SelectionStart = 1;
richTextBox1.SelectionLength = 1;
comboBox1.Text = richTextBox1.SelectionFont.ToString();
comboBox2.Text = null;
comboBox2.Text = richTextBox1.SelectionFont.Size.ToString();
}
I held out hope that it was my answer but I could not see how SelectionFont would make any difference when nothing was selected. Also the richTextBox1_SelectionChanged event seems to not be being called when I move through the document with the up/down arrows. The problem is not with the comboboxes, the problem is that as I arrow through my document I need to be able to know what font and size it is at the caret position so it can fire an event to change the combo boxes to match.
The code that you are using will always make the selection from character at index 1 and are of the length 1. instead for that you need to use which will give you the the following code without specifying the selection(so it will take the selection from the ritchTextBox).
string fontName = richTextBox1.SelectionFont.Name;
float fontsize = richTextBox1.SelectionFont.Size;
You should save the values for the new comboBox position temporarily in variables, otherwise if you do it directly
comboBox1.SelectedIndex = comboBox1.FindStringExact(richTextBox1.SelectionFont.Name);
the comboBox1_SelectedIndexChanged event will be immediately called and could affect the results.
So just try:
private void richTextBox1_SelectionChanged(object sender, EventArgs e)
{
int comboBox1Index = comboBox1.FindStringExact(richTextBox1.SelectionFont.Name);
int comboBox2Index = comboBox2.FindStringExact(richTextBox1.SelectionFont.Size.ToString());
comboBox1.SelectedIndex = comboBox1Index;
comboBox2.SelectedIndex = comboBox2Index;
}
I adapted Sujith's solution and half of Markus's solution and came up with the following which works just fine for me:
Private Sub Description_SelectionChanged(sender As Object, e As EventArgs) Handles Description.SelectionChanged
Dim fontName As String = Description.SelectionFont.Name
Dim fontSize As Single = Description.SelectionFont.Size
tbSelectFont.Text = fontName
tbSelectSize.Text = fontSize
End Sub
I'm building a Xaml based app with a C# backend.
I have data that needs to be entered by the user in a specific format (example: AAAA-BBBBBB-CCCC-DD etc). I currently have one text box that takes the whole thing, but for user experience I would prefer to break the example text into four boxes
one for AAAA
one for BBBBBB
one for CCCC
one for DD etc
So what I expect from the user would be abundantly clear. That part is easy enough with string concatenation
But I would like the four boxes to behave like a single box in a largely transparent manner.
Once the user enters 4 characters into textbox 1, the focus would shift to textbox 2 and they could continue typing. Additionally, if possible, I would like the focus shift to select all text already in the box, so they can easily overwrite without having to go to their mouse or doing a ctrl+a.
I've searched for how to change focus between texboxes, but could not get examples to work.
You can listen to TextChanged event of each TextBox, then check if text length is equal maximum length. If it is equal (or even greater) than maximum, move focus to next TextBox and select all text there. Refactor the logic to a method so you can simply call the same method in event handler function of each TextBox, hence can avoid writing similar codes repeatedly. Something like this will do :
private void textboxAAAA_TextChanged(object sender, TextChangedEventArgs e)
{
HandleTextChanged(textboxAAAA, textboxBBBBBB, 4);
}
private void textboxBBBBBB_TextChanged(object sender, TextChangedEventArgs e)
{
HandleTextChanged(textboxBBBBBB, textboxCCCC, 6);
}
private void textboxCCCC_TextChanged(object sender, TextChangedEventArgs e)
{
HandleTextChanged(textboxCCCC, textboxDD, 4);
}
private void HandleTextChanged(TextBox currentTextBox, TextBox nextTextBox, int maxLength)
{
var textLength = currentTextBox.Text.Length;
if (textLength >= maxLength)
{
nextTextBox.Focus(FocusState.Keyboard);
nextTextBox.SelectAll();
}
}
//in XAML
<StackPanel Orientation="Horizontal">
<TextBox x:Name="textboxAAAA" Width="60" TextChanged="textboxAAAA_TextChanged"/>
<TextBlock Text="-"/>
<TextBox x:Name="textboxBBBBBB" Width="60" TextChanged="textboxBBBBBB_TextChanged"/>
<TextBlock Text="-"/>
<TextBox x:Name="textboxCCCC" Width="60" TextChanged="textboxCCCC_TextChanged"/>
<TextBlock Text="-"/>
<TextBox x:Name="textboxDD" Width="60"/>
</StackPanel>
Note, that you don't consider case when user copy-paste serial number. What the program should do if user copy 7 letters text, and paste it to the first text box?
Other solution:
1.- You configure sequencial TabIndex properties in your four TextBoxes.
2.- You configure maxLength propoerties en your TextBoxes.
3.- You configure the next method in TextChanged event in your TextBoxex.
private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
{
var tb = (TextBox)sender;
if (tb.Text.Length == tb.MaxLength)
{
var nextTB = this.PrincipalGrid.Children.OfType<TextBox>().Where(t => t.TabIndex == (tb.TabIndex + 1)).FirstOrDefault();
if (nextTB != default(TextBox))
nextTB.Focus();
}
}
Why not to use one TextBox? Listen for text changes and include a dash(-) in text every time when it need. Do not allow user to type dashes (ignore them). Some small logic should be done for clipboard pasting and for the whole product key/text validation. Later you can split the Text via String.Split( new Char("-")) and you will get an array of codes (if you need it in this way).
I suppose there's a limit for the lines alowed in a TextBox with the MultiLine option set to true.
I have a program that every several minutes, checks an email account, but for control purposes i put a TextBox that indicates what's been doing.
My curiosity is, does anyone know how much lines are allowed ? And does throw an exception when reached that line ?
EDIT Sorry forgot to mention is in WinForms
EDIT 2 Perhaps, someone knows of a way to eliminate older lines, will grated appreciated
There's no limit on the number of lines that a text box can display.
There is, however, a limit on the number of characters that the control can hold. See this question for further details on this topic.
If you set the TextBox.MaxLength property to zero, the amount of text is limited only by available memory.
Another solution:
<TextBox x:Name="txtAddress"
MaxLines="6"
TextWrapping="Wrap" AcceptsReturn="True"
VerticalScrollBarVisibility="Hidden"
HorizontalScrollBarVisibility="Hidden"
TextChanged="txtAddress_TextChanged"
PreviewTextInput="txtAddress_PreviewTextInput"
PreviewKeyDown="txtAddress_PreviewTextInput"/>
//...
private void txtAddress_TextChanged(object sender, TextChangedEventArgs e)
{
TextBox txtBx = sender as TextBox;
if (txtBx.LineCount > txtBx.MaxLines)
txtAddress.Text = this._textBeforInput;
}
private string _textBeforInput = string.Empty;
private void txtAddress_PreviewTextInput(object sender, EventArgs e)
{
this._textBeforInput = txtAddress.Text;
}
There is no such limitation on Multiline TextBox both in WinForms and ASP.NET. (I have no idea of WPF :) )
I know this question is really old and has already been answered, but for those searching for an HTML/ASP.NET solution I have created a short jsFiddle http://jsfiddle.net/Z3rdZ/2/
HTML
<textarea id="limited-lines" maxlines="4"></textarea>
jQuery
$('#limited-lines').keydown(function(event){
if ( event.which == 13 ) {
var numberOfLines = $(this).val().split('\n').length;
if(numberOfLines >= $(this).attr('maxlines')){
event.preventDefault();
}
}
});
I have a textbox that I break up into an array based on "\r"
I'd like to have the line of text that is clicked on put into a string.
For instance, if I click on the 2nd line below in my textbox, I'd like "2nd line" to be entered into the string
1st line
2nd line
last line
How would I go about doing that?
This is close, but I recommend selecting text between TextBox.SelectionStart and TextBox.SelectionEnd instead of what you are trying to do.
WPF, but it might be the same
MainWindow.xaml
<TextBox
MouseDoubleClick="textBox1_MouseDoubleClick" />
MainWindow.xaml.cs
private void textBox1_MouseDoubleClick(object sender, MouseEventArgs e)
{
int characterIndex = this.textBox1.SelectionStart;
string characterIndexSubstring = this.textBox1.Text.Substring(0, characterIndex);
int lineNumber = characterIndexSubstring.Split(new string[] { "\n", "\r\n" }, StringSplitOptions.RemoveEmptyEntries).Length;
string[] lines = textBox1.Text.Split(new string[] { "\n", "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
string clickedOnValue = lines[lineNumber];
MessageBox.Show(clickedOnValue);
}
This isn't really an answer as I ended up grabbing the string out of a datagrid I was populating with data out of the textbox referenced in this post.
Link to that solution is: Silverlight C# - How to get value of row/cell clicked on in DataGrid?