Retrieve text from a textbox in visual studio ( windows store app) - c#

In windows store app( express 2013 for windows), i have created a textbox. Now i want to capture or retrieve the text entered by the user for further operations ( specifically, assign the user text to a string).
I tried this :
string input = InputBox.Text;
in the event handler for textbox.But this doesn't seem to work.
Any help is welcome.
<TextBox Text="TextBox"
x:Name="InputBox"
Grid.Row="1"
HorizontalAlignment="Right"
VerticalAlignment="Center"
Width="402"
Height="48"
FontFamily="Arial Black"
FontSize="28"
FontWeight="Bold"
VerticalContentAlignment="Center"
HorizontalContentAlignment="Left" Margin="0,77,0,84"
TextAlignment="Left" TextChanged="InputBox_TextChanged"
/>
C# code follows :
private void InputBox_TextChanged(object sender, TextChangedEventArgs e)
{
string input = InputBox.Text;
}

the problem here is that you´re creating the string inside the event, so it will be erased after the event finish.
what you can do is to create a string inside the form class, and set its value on the text box event.
private string input = string.Empty;
private void InputBox_TextChanged(object sender, TextChangedEventArgs e)
{
input = InputBox.Text;
}

Remove TextChanged="InputBox_TextChanged" from xaml and use InputBox.Text wherever you want to use text of your TextBox.
InputBox_TextChanged will fire on every symbol you type in your textbox, so it is not good idea to get text in text_changed.

Related

How to update textblock with method

I have a textbox that provide user to input string. how can i pass that string to method and toUpper() it. and pass back the string to textblock in the main window that both of the box and block update in real time?
For my C# code:
public MainWindow()
{
InitializeComponent();
}
private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
{
textBlock.Text = textBox.Text +"changed";
}
it is just as simple like this.
for my xaml code:
<Grid >
<TextBox x:Name ="textBox" HorizontalAlignment="Left" Height="105" Margin="28,185,0,0" TextWrapping="Wrap" Text="HELLO" VerticalAlignment="Top" Width="300" TextChanged="TextBox_TextChanged"/>
<TextBlock x:Name="textBlock" HorizontalAlignment="Left" Height="116" Margin="114,40,0,0" TextWrapping="Wrap" Text="TextBlock" VerticalAlignment="Top" Width="328"/>
</Grid>
i want to know why the text of my textblock cannot be updated when i type something inside the textbox.
I combined the answer of #Yavor Georgiev
You are encountering a null reference exception. When the textBox control is created it will trigger the textChange event on textBox and by that point, textBlock isn't created and is therefore null. You can just change the order of the textboxes in the XAML and you will be fine.
Change the order
Grid>
<TextBlock x:Name="textBlock" HorizontalAlignment="Left" Height="116" Margin="114,40,0,0" TextWrapping="Wrap" Text="TextBlock" VerticalAlignment="Top" Width="328"/>
<TextBox x:Name ="textBox" HorizontalAlignment="Left" Height="105" Margin="28,185,0,0" TextWrapping="Wrap" Text="HELLO" VerticalAlignment="Top" Width="300" TextChanged="TextBox_TextChanged"/>
</Grid>
For the upper part i used #Yavor Georgiev answer when typing
private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
{
textBox.Text = textBox.Text?.ToUpper();
textBlock.Text = textBox.Text;
textBox.CaretIndex = textBox.Text?.Length ?? 0;
textBlock.Text = textBox.Text + "changed";
}
Do you need something like this?
private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
{
textBox.Text = textBox.Text?.ToUpper();
textBlock.Text = textBox.Text;
textBox.CaretIndex = textBox.Text?.Length ?? 0; //You need this to continue typing from the last index onwards..
}
I don't exactly understand if you need both the textBox and the textBlock to change at the same time or only the textBlock to be in UpperCase, but the concept is the same

WPF - DatePicker Masked input

I'm developing an WPF application and I got two datepicks input where use
can select the date, But I am having some problem with these inputs cause the user can write whatever they want on it as in the image bellow
Is there some way to mask this inputs ? as dd/mm/yyy to only allow users to write dates and it automatically inserts the / slash ?
I tried follow this example but didn't work as it only formate the date after the user choose it from the calendar
I know that there are some "masked inputs" but they don't work with datepicker input
Thanks in Advance.
EDIT
here is my xaml code
<Border Grid.Column="0" Grid.Row="1" Margin="10 0 0 0" Style="{StaticResource InputBorder}" Height="30" VerticalAlignment="Top">
<DatePicker x:Name="EDT_DATA_INICIAL"></DatePicker>
</Border>
<Border Grid.Column="1" Grid.Row="1" Margin="10 0 10 0" Style="{StaticResource InputBorder}" Height="30" VerticalAlignment="Top">
<DatePicker x:Name="EDT_DATA_FINAL"></DatePicker>
</Border>
Just complementing the #Tronald's answer I'am using his event PreviewTextInput
and I complementend it using this code in a keyUp event
private void SetDateFormat(object sender, KeyEventArgs e)
{
DatePicker dt = (DatePicker)sender;
string justNumbers = new String(dt.Text.Where(Char.IsDigit).ToArray());
if (justNumbers.Length == 8)
{
string newDate = justNumbers.Insert(2, "/").Insert(5, "/");
try
{
dt.SelectedDate = DateTime.Parse(newDate);
}catch(Exception ex)
{
dt.text = "";
}
}
}
That format the date when use only digite numbers or
ex : 18061993 > 18/06/1993 and when the date is incorrect it clears the input preventing errors
Create a PreviewTextInput event in your DatePicker and handle the logic in there. The below example will restrict input to numbers and "/" only. You will have to figure out how to automatically input the "/" on your own if you wish to do that.
Maybe loop through each character of the string as it's built and determine if you need to add the "/" at a certain point. You can e.Handled = true to block the user input then set the DatePicker.Text as required. This should be enough to get you started.
private void DatePicker_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
DatePicker dp = (DatePicker)sender;
Regex regex = new Regex("[^0-9/]"); //regex that matches allowed text
e.Handled = regex.IsMatch(e.Text);
}
Regex reference isSystem.Text.RegularExpressions

How to move text from one Textblock to another Textblock using Drag and Drop in a Universal Windows Application?

I know how to set properties like CanDrag and AllowDrop and define DragOver method and Drop method.
I just don't know what to write inside the Drop method.
How to move text from one Textblock to another Textblock using Drag and Drop
We can define DragStarting event for the source Textblock and save the text of the source Textblock in DragStartingEventArgs for transfer during dragging. And accept the text when drop at target Textblock. Read the text from DragEventHandler and set it to the target Textblock.
I wrote a simple sample here, move the text from txtsource to append to txttarget.
XAML code:
<StackPanel Background="{ThemeResource ApplicationPageBackgroundThemeBrush}" Padding="30">
<Border BorderBrush="Azure" BorderThickness="2">
<TextBlock x:Name="txtsource" Text="I'm the first textblock" CanDrag="True" DragStarting="txtsource_DragStarting" />
</Border>
<Border BorderBrush="Azure" BorderThickness="2" Margin="20" AllowDrop="True" >
<TextBlock x:Name="txttarget" Text="I'm the second textblock" Drop="txttarget_Drop" Height="50" Width="400" AllowDrop="True" DragEnter="txttarget_DragEnter"/>
</Border>
</StackPanel>
Code behind
private void txtsource_DragStarting(UIElement sender, DragStartingEventArgs args)
{
args.Data.SetText(txtsource.Text);
}
private async void txttarget_Drop(object sender, DragEventArgs e)
{
bool hasText = e.DataView.Contains(StandardDataFormats.Text);
e.AcceptedOperation = hasText ? DataPackageOperation.Copy : DataPackageOperation.None;
if (hasText)
{
var text = await e.DataView.GetTextAsync();
txttarget.Text +="\n"+ text;
}
}
private void txttarget_DragEnter(object sender, DragEventArgs e)
{
bool hasText = e.DataView.Contains(StandardDataFormats.Text);
e.AcceptedOperation = hasText ? DataPackageOperation.Copy : DataPackageOperation.None;
if (hasText)
{
e.DragUIOverride.Caption = "Drop here to insert text";
}
}
I use DragOver event to help define which area can be drop. More details please reference the scenario 2 of the official sample.

Set Validation at TextBox

How to set Validation error on textbox?
For example if user insert less than 12 word it will display.
If user insert number it will display
Validation I want to display is at Label
<TextBox HorizontalAlignment="Left" Height="23" Margin="41,69,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="200" Grid.Column="1"/>
<Label Content="Label" HorizontalAlignment="Left" Margin="40,176,0,0" VerticalAlignment="Top"/>
use text changed event of Textbox control. you will get the number of words entered in text box using the following code
private void textbox1_TextChanged(object sender, TextChangedEventArgs e)
{
string[] arrWords = textbox1.Text.Split(new char[] { ' ' });
int count = arrWords.Length.ToString();
if(count<12)
{
label1.Content="enter your error message";
}
}

WPF, sibling selection like jQuery?

I have the following XAML code as an example in my WPF application
<StackPanel Height="23" Name="MSpanel" Orientation="Horizontal" Width="138" Margin="37,13,0,0" VerticalAlignment="Top" HorizontalAlignment="Left" >
<TextBox Height="23" Name="MTBox" Width="120" Text="0" />
<ScrollBar Height="23" Name="MSBar" Width="18" TouchUp="SBar_TouchUp" />
</StackPanel>
<StackPanel Height="23" Name="CSPanel" Orientation="Horizontal" Width="138" Margin="37,41,0,0" VerticalAlignment="Top" HorizontalAlignment="Left">
<TextBox Height="23" Name="CTBox" Width="120" Text="0" />
<ScrollBar Height="23" Name="CSBar" Width="18" TouchUp="SBar_TouchUp" />
</StackPanel>
I have this function:
private void SBar_TouchUp(object sender, TouchEventArgs e)
{
//what goes here?
//siblings.getFirst('textbox').text += 1;
}
What I was hoping to do, is have 1 function that controls these "Psudo" numeric up downs in WPF. If there was some way to have a unified function that could, reference the sibling textbox, so I only have to write it once. That would be ideal.
I'm very familiar with jQuery, and XAML looks like an HTML DOM, ... Is there a way to browse the tree?
I realize there are existing Numeric Up Downs available to download. This idea I believe would be good to know for the future in other endeavors as well. Thanks.
The solution that worked!
private void SBar_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
{
if (e.NewValue == 0) return; //abort here, no change
ScrollBar sb = (ScrollBar)sender;
StackPanel sp = (StackPanel)sb.Parent;
TextBox tb = (TextBox)sp.Children[0];
int change = e.NewValue < 0 ? 1 : -1;
sb.Value = 0; //this will invoke this function again
tb.Text = (Convert.ToInt32(tb.Text) + change).ToString();
}
Each element in the visual tree has a Parent and VisualParent property - as all elements are based on UIElement - either should give you the parent object.
In this case the parent of the ScrollBar is the StackPanel. You can then use the Children property of the StackPanel to get the collection of child objects. You know which is the ScrollBar (it's the sender) so the other must be the TextBox.
You can do something like this:
private void SBar_TouchUp(object sender, TouchEventArgs e)
{
//siblings.getFirst('textbox').text += 1;
var siblings = ((sender as FrameworkElement).Parent as Panel).Children;
var textbox = siblings.OfType<TextBox>().First();
textbox.Text = (int.Parse(textbox.Text) + 1).ToString();
}
but I would suspect that there are probably better ways to do what you want, like data binding or naming elements in attached properties.
Yeah, there are many properties for both Logical and Visual trees.
Like FrameworkElement.Parent or Panel.Children.
I don't think there is directly method to get sibling, but its not that hard to get index in list of children of parent and getting next item.

Categories