Set Validation at TextBox - c#

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";
}
}

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

selected value cannot be set

I have a combobox which gets its Items from some scan function.
If the user select an element, in the next time, the user's chosen item should be selected (if it is present on the scan function output). The problem is that I cannot select it.
Here is the declaration of the ComboBox:
<ComboBox Grid.Column="1" Grid.Row="0" Margin="5" Name="SerialPortNames" Text="{Binding Name}" IsEditable="False"/>
and here what I have tried so far:
private void Window_Loaded(object sender, RoutedEventArgs e)
{
string portNameSetting = Settings.Default["SerialPortName"].ToString();
SerialPortNames.ItemsSource = SerialPort.GetPortNames();
foreach (string SerialPortNameItem in SerialPortNames.Items)
{
if (SerialPortNameItem == portNameSetting)
{
SerialPortNames.Text = SerialPortNameItem; // why this is not working
break;
}
}
}
by debugging this, I get the item selected in the combobox, but it seems that something override it and it is empty!
In your code you Binded the Text propery and also setting it from code behind
Remove Text="{Binding Name}" from the combobox
<ComboBox Width="200" Height="200" Grid.Column="1" Grid.Row="0" Margin="5" Name="SerialPortNames" IsEditable="False"/>

C# & XAML how to get button to respond on first click

I actually got the bulk of my code to work. I appreciate the input, it pointed me in the correct direction. The problem I am having now is getting the buttons to work on the first click.
I appreciate any input that would help me improve my code.
Below are my XAML (MainPage.xaml) & C# (MainPage.xaml.cs) code.
<Page
x:Class="Calculator_Application.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:Calculator_Application"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<Grid>
<TextBlock x:Name="textBlock_title" TextWrapping="Wrap" Text="Calculator Application" VerticalAlignment="Top" Height="58" Width="252" Margin="86,30,0,0" SelectionChanged="textBlock_SelectionChanged" HorizontalAlignment="Left" FontSize="24" RenderTransformOrigin="-0.039,0.549" FontFamily="Calibri" Foreground="#FFBCB7B6"/>
<Button x:Name="button_info" Content="Information" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="135,561,0,0" Click="button_Click" FontFamily="Global User Interface" Foreground="#FFF05D5D"/>
<TextBox x:Name="textBox_number1" HorizontalAlignment="Left" Margin="29,191,0,0" TextWrapping="Wrap" Text="" VerticalAlignment="Top" TextChanged="textBox_number1_TextChanged"/>
<TextBox x:Name="textBox_number2" HorizontalAlignment="Left" Margin="29,387,0,0" TextWrapping="Wrap" Text="" VerticalAlignment="Top"/>
<TextBlock x:Name="textBlock_info" HorizontalAlignment="Left" TextWrapping="Wrap" Text="Please input numbers to calculate:" VerticalAlignment="Top" Height="30" Width="252" FontSize="16" FontStyle="Italic" Margin="29,134,0,0" SelectionChanged="textBlock_info_SelectionChanged" Foreground="#FFE5957F"/>
<Button x:Name="button_add" Content="+" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="29,278,0,0" MinWidth="25" Height="20" FontSize="24" FontFamily="Global User Interface" Width="39" Background="Black"/>
<Button x:Name="button_subtract" Content="-" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="106,278,0,0" MinWidth="25" Height="20" FontSize="24" FontFamily="Global User Interface" Width="39"/>
<Button x:Name="button_multiply" Content="*" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="179,278,0,0" MinWidth="25" Height="20" FontSize="24" FontFamily="Global User Interface" Width="39"/>
<Button x:Name="button_divide" Content="/" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="257,278,0,0" MinWidth="25" Height="20" FontSize="24" FontFamily="Global User Interface" Width="39"/>
<TextBlock x:Name="textBlock_equals" HorizontalAlignment="Left" TextWrapping="Wrap" Text="=" VerticalAlignment="Top" Height="39" Width="38" Margin="164,387,0,0" FontSize="36"/>
<TextBlock x:Name="textBlock_answer" HorizontalAlignment="Left" TextWrapping="Wrap" Text="answer" VerticalAlignment="Center" Height="23" Width="139" Margin="207,387,0,230" FontSize="22"/>
</Grid>
</Page>
Here is the C#
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
// Added to ensure popup is availible
using Windows.UI.Popups;
// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=391641
namespace Calculator_Application
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class MainPage : Page
{
private double valHolder1 = 0;
private double valHolder2 = 0;
private double answer = 0;
public MainPage()
{
this.InitializeComponent();
this.NavigationCacheMode = NavigationCacheMode.Required;
}
/// <summary>
/// Invoked when this page is about to be displayed in a Frame.
/// </summary>
/// <param name="e">Event data that describes how this page was reached.
/// This parameter is typically used to configure the page.</param>
protected override void OnNavigatedTo(NavigationEventArgs e)
{
// TODO: Prepare page for display here.
// TODO: If your application contains multiple pages, ensure that you are
// handling the hardware Back button by registering for the
// Windows.Phone.UI.Input.HardwareButtons.BackPressed event.
// If you are using the NavigationHelper provided by some templates,
// this event is handled for you.
}
private void textBlock_SelectionChanged(object sender, RoutedEventArgs e)
{
}
private void textBlock_info_SelectionChanged(object sender, RoutedEventArgs e)
{
}
private async void button_Click(object sender, RoutedEventArgs e)
{
//Creating instance for the MessageDialog Class
//and passing the message in it's Constructor
MessageDialog msgbox = new MessageDialog("Page Lynn Potter, MBL 410, 05-15-2017, Robin Deitsch");
//Calling the Show method of MessageDialog class
//which will show the MessageBox
await msgbox.ShowAsync();
}
private void textBox_number1_TextChanged(object sender, TextChangedEventArgs e)
{
}
private void button_add_Click(object sender, RoutedEventArgs e)
{
//Make sure out text box has a value
if (textBox_number1.Text.Length != 0)
{
//Assign the value in text box to holder
valHolder1 = System.Double.Parse(textBox_number1.Text);
//Empty the text box
textBox_number1.Text = string.Empty;
if (textBox_number2.Text.Length != 0)
{
//Assign the value in text box to holder
valHolder2 = System.Double.Parse(textBox_number2.Text);
//Empty the text box
textBox_number2.Text = string.Empty;
}
}
else
{
//Calculate answer
answer = valHolder1 + valHolder2;
//Assign answer to text block
textBlock_answer.Text = answer.ToString();
}
}
private void button_subtract_Click(object sender, RoutedEventArgs e)
{
//Make sure out text box has a value
if (textBox_number1.Text.Length != 0)
{
//Assign the value in text box to holder
valHolder1 = System.Double.Parse(textBox_number1.Text);
//Empty the text box
textBox_number1.Text = string.Empty;
if (textBox_number2.Text.Length != 0)
{
//Assign the value in text box to holder
valHolder2 = System.Double.Parse(textBox_number2.Text);
//Empty the text box
textBox_number2.Text = string.Empty;
}
}
else
{
//Calculate answer
answer = valHolder1 - valHolder2;
//Assign answer to text block
textBlock_answer.Text = answer.ToString();
}
}
private void button_multiply_Click(object sender, RoutedEventArgs e)
{
//Make sure out text box has a value
if (textBox_number1.Text.Length != 0)
{
//Assign the value in text box to holder
valHolder1 = System.Double.Parse(textBox_number1.Text);
//Empty the text box
textBox_number1.Text = string.Empty;
if (textBox_number2.Text.Length != 0)
{
//Assign the value in text box to holder
valHolder2 = System.Double.Parse(textBox_number2.Text);
//Empty the text box
textBox_number2.Text = string.Empty;
}
}
else
{
//Calculate answer
answer = valHolder1 * valHolder2;
//Assign answer to text block
textBlock_answer.Text = answer.ToString();
}
}
private void button_divide_Click(object sender, RoutedEventArgs e)
{
//Make sure out text box has a value
if (textBox_number1.Text.Length != 0)
{
//Assign the value in text box to holder
valHolder1 = System.Double.Parse(textBox_number1.Text);
//Empty the text box
textBox_number1.Text = string.Empty;
if (textBox_number2.Text.Length != 0)
{
//Assign the value in text box to holder
valHolder2 = System.Double.Parse(textBox_number2.Text);
//Empty the text box
textBox_number2.Text = string.Empty;
}
}
else
{
//Calculate answer
answer = valHolder1 / valHolder2;
//Assign answer to text block
textBlock_answer.Text = answer.ToString();
}
}
}
}
You have an event handler configured for the button_info button.
<Button x:Name="button_info" Content="Information"
HorizontalAlignment="Left" VerticalAlignment="Top"
Margin="135,561,0,0"
FontFamily="Global User Interface" Foreground="#FFF05D5D"
Click="button_Click"/>
I don't see where you've configured handlers for the other buttons.
There should be something like this in the XAML.
<Button x:Name="button_add" Click = "button_add_Click" />
<Button x:Name="button_subtract" Click = "button_subtract_Click" />
<Button x:Name="button_multiply" Click = "button_multiply_Click" />
<Button x:Name="button_divide"Click = "button_divide_Click" />

Listpicker tap event in fullscreen mode not working correctly

I'm developing windows phone 8 application.
I'm using ListPicker option.
My Listpicker code
<toolkit:ListPicker x:Name="LPfilter" Foreground="White" BorderThickness="0" Margin="300,0,0,0" Height="80" Width="50" Visibility="Visible">
<toolkit:ListPicker.Background>
<ImageBrush ImageSource="/Assets/Images/filters.png"/>
</toolkit:ListPicker.Background>
<toolkit:ListPicker.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding name}" Visibility="Collapsed" Foreground="Red"/>
</DataTemplate>
</toolkit:ListPicker.ItemTemplate>
<toolkit:ListPicker.FullModeItemTemplate>
<DataTemplate>
<TextBlock Tap="TextBlock_Tap">
<Run Text="{Binding name}"/>
</TextBlock>
</DataTemplate>
</toolkit:ListPicker.FullModeItemTemplate>
</toolkit:ListPicker>
values bind to listpicker using webservice (json format).
Json result comes like this
[
-{
id: "9",
name: "Pizza",
root_id: "4",
level: "1",
},
-{
id: "10",
name: "Fine Dinind",
root_id: "4",
level: "1",
},
-{
id: "11",
name: "Fast Food",
root_id: "4",
level: "1",
},
....
]
c# code for bind values
public void businesscatbind()
{
string bus_caturl = "http://xxxxx.com/Service/filterquery.php?rootid=" + bus_catval;
WebClient bus_catwc = new WebClient();
bus_catwc.DownloadStringAsync(new Uri(bus_caturl), UriKind.Relative);
bus_catwc.DownloadStringCompleted += bus_catwc_DownloadStringCompleted;
}
void bus_catwc_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
var bus_catdata = e.Result;
var bus_catvalue = JsonConvert.DeserializeObject<List<bus_catbinddata>>(bus_catdata);
LPfilter.ItemsSource = bus_catvalue;
}
Problem occur in this event
private void TextBlock_Tap(object sender, System.Windows.Input.GestureEventArgs e)
{
bus_catbinddata elements = LPfilter.SelectedItem as bus_catbinddata;
int val = LPfilter.SelectedIndex;
filterid = int.Parse(elements.id);
MessageBox.Show(filterid.ToString());
}
My problem
First time i click pizza it's show the value = Id value 9 in msgbox
next i click Fine Dining it's show the value = Id value 9 in msgbox
next i click Fast Food it's show the value =10 in msgbox (10 Is the idvalue of FineDining)
next i click Italian it's show the value = 11 in msgbox (11 is the Idvalue of Fastfood)
previews selected item value is show in alert
Output
How to solve this issue.
Use Listpicker SelectionChanged event instead
<toolkit:ListPicker x:Name="LPfilter" Foreground="White" BorderThickness="0" Margin="300,0,0,0" Height="80" Width="50" Visibility="Visible" SelectionChanged="listPicker_SelectionChanged>
in Xaml page
<toolkit:ListPicker x:Name="listPicker" Foreground="White" BorderThickness="0" Margin="300,0,0,0" Height="80" Width="50" Visibility="Visible" SelectionChanged="listPicker_SelectionChanged" >
<toolkit:ListPicker.Background>
<ImageBrush ImageSource="/Assets/Images/filters.png"/>
</toolkit:ListPicker.Background>
<toolkit:ListPicker.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding name}" Visibility="Collapsed" Foreground="Red"/>
</DataTemplate>
</toolkit:ListPicker.ItemTemplate>
<toolkit:ListPicker.FullModeItemTemplate>
<DataTemplate>
<TextBlock Tap="TextBlock_Tap">
<Run Text="{Binding name}"/>
</TextBlock>
</DataTemplate>
</toolkit:ListPicker.FullModeItemTemplate>
</toolkit:ListPicker>
In .cs File
void listPicker_SelectionChanged(object sender, SelectionChangedEventArgs args)
{
if (this.listPicker.SelectedItems != null && this.listPicker.SelectionMode == SelectionMode.Multiple)
{
for (int i = 0; i < this.listPicker.SelectedItems.Count; i++)
{
string str = ((Items)(this.listPicker.SelectedItems[i])).Name;
if (i == 0)
{
MessageBox.Show("Selected Item(s) is " + str);
}
else
{
//Some Code
}
}
}
else if (this.listPicker.SelectionMode == SelectionMode.Single)
{
MessageBox.Show("Selected Item is " + ((Items)this.listPicker.SelectedItem).Name);
}
}
It seems that the "TextBlock_Tap" event fires up before the "ListPicker" changes its selection.
You can try to use the "SelectionChanged" event of the ListPicker - although it seems that you are not using it because you might want to select the same option twice. In that case, you can add a dummy item to the top of your list saying something like "Select Item" and in the "SelectionChanged" event in the end set the selected item of list picker to your dummy item.
EDIT:
In this method -
void bus_catwc_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
var bus_catdata = e.Result;
var bus_catvalue = JsonConvert.DeserializeObject<List<bus_catbinddata>>(bus_catdata);
LPfilter.ItemsSource = bus_catvalue;
}
add a new "bus_catbinddata" to the "var bus_catvalue" - it is a list - insert your dummy itme at index 0. then in selection changed event of list picker, add a condition if(ListPicker.SelectedIndex > 0) and only if this condition is true, the code will execute.
I haven't tried this specifically with ListPicker's full mode item template, but you can try to get corresponding model for tapped TextBlock from DataContext :
private void TextBlock_Tap(object sender, System.Windows.Input.GestureEventArgs e)
{
TextBlock textBlock = (TextBlock)sender;
bus_catbinddata elements = textBlock.DataContext as bus_catbinddata;
filterid = int.Parse(elements.id);
MessageBox.Show(filterid.ToString());
}

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

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.

Categories