C# creates an input form that only works with URLs.
if(e.Key==Key.Enter&!String.IsNullOrEmpty(txtUrl.Text)){
wbSample.Navigate(txtUrl.Text);
}
The above code features are available in
·When a user enters an arbitrary URL and presses the enter key, the corresponding page is displayed on the screen.
·If the user presses the Enter key without entering it, the input will be treated as invalid.
These are the correct decisions.
However, the problem is that the user enters only spaces with the space key and presses Enter to force termination.
The code below uses IsNullOrEmpty
, but if there is only a blank space in the form field, the enter key will not be disabled and will crash.
if(e.Key==Key.Enter&!String.IsNullOrEmpty(txtUrl.Text))
Is there any coding that disables the enter key when the user presses the enter key without entering it or when the user presses the enter key with only a blank space?
c#
It seems to have been self-resolved, but it seems to have been changed as follows:
Is there any coding that disables the enter key when the user presses the enter key without entering it or when the user presses the enter key with only the space key?
Debugging here
if(e.Key==Key.Enter&!String.IsNullOrEmpty(txtUrl.Text))
This line reads "Unhandled Exception System.ArgumentException: 'The value is not in the valid range.'
wbSample.Navigate(txtUrl.Text);
If you change the method used to make the decision from String.IsNullOrEmpty
to String.IsNullOrWhiteSpace
, it will work as you wish.
if (e.Key==Key.Enter&!String.IsNullOrWhiteSpace(txtUrl.Text))
String.IsNullOrEmpty (String) method
Indicates whether the specified string is null
or an empty string ("")
String.IsNullOrWhiteSpace (String) method
Indicates whether the specified string is null
or empty or consists of only blank characters.
Only the problem points are pinpointed in the question, but you can work on the following article overview or tutorial to reproduce, investigate, and verify the problem.
Microsoft Edge WebView 2 Overview
Start using WebView 2 with the WinForms app
Paste the question code into the KeyDown
event in the TextBox addressBar
of the Tutorial above and adjust it to match the Tutorial content as follows:
Then you will be able to reproduce the problem, investigate it, and confirm the correction.
private void addressBar_KeyDown (object sender, System.Windows.Forms.KeyEventArgse)
{
// When reproducing the problem: if(e.KeyCode==Keys.Enter&!String.IsNullOrEmpty(addressBar.Text))
if(e.KeyCode==Keys.Enter&&!String.IsNullOrWhiteSpace(addressBar.Text))/Modified Edition
{
webView.CoreWebView2.Navigate(addressBar.Text);
}
}
© 2024 OneMinuteCode. All rights reserved.