Hi
I have a SfTextBox element and would like to end editing when the Enter key has been pressed.
After pressing the EnterKey the ValueChanged or ValueChange should be called or I should be able to read the currently displayed text. But the Value of the text box contains old text, i.e. the text shown before I start editing.
My code is:
<SfTextBox @ref=@textBox Value="@Value" @onkeypress="@KeyPressed"/>
private SfTextBox? textBox;
public string? Value { get; set; }
public async Task KeyPressed(KeyboardEventArgs args)
{
if (args.Key == "Enter")
{
>> textBox.Value contains old text but not currently visible text
}
}
Thanks for help, Bruno
Hi Bruno,
Thank you for reaching out to us with your query regarding the SfTextBox element. After reviewing your code snippet, we have identified the issue you are experiencing. In order to obtain the currently displayed text in the textbox upon pressing Enter, we recommend using the following code snippet:
<SfTextBox @ref=@textBox @bind-Value="@Value" @onkeypress="@KeyPressed" />
@code {
private SfTextBox? textBox; public string? Value { get; set; }
public async Task KeyPressed(KeyboardEventArgs args) { if (args.Key == "Enter") { } } |
Hi Kokila
Thank you for your reply!
I loaded and run your code snipped but it doesn't work.
When I type a text and immediately press Enter - before exiting the text box - I do not get the visible text. I always get the old value.
Regards, Bruno
public async Task KeyPressed(KeyboardEventArgs args)
{
string test;
if (args.Key == "Enter")
{
test = textBox.Value;
}
}
Hi Bruno,
We apologize for any inconvenience you've experienced. Based on your scenario, we recommend using the ValueChange event instead of the OnKeyPress event in the TextBox component. By using the ValueChange event, you can achieve the desired behavior of ending editing when the Enter key is pressed or when the component loses focus. By using the ValueChange you can get the changed value using your two-way bind variable.
If you have any further questions or need additional assistance, please reach out to us.
Code snippet:
|
<SfTextBox @ref=@textBox @bind-Value="@Value" ValueChange="@ValueChangeHandler" />
@code {
private SfTextBox? textBox; public string? Value { get; set; }
private void ValueChangeHandler(ChangedEventArgs args) { string test; test = textBox.Value; }
} |
Regards,
Kokila Poovendran.
Hi Kokila
Yes, this works. KeyPressed event is really not necessary since the ValueChange event is also fired when the Enter key has been pressed.
We even don't need the two-wey binding since args.Value always contains the correct value.
Thank you very much for your valuable help!
Bruno
You're welcome! We are delighted that it worked out for you. The KeyPressed event is not necessary; the ValueChange event covers Enter key presses. If you have more questions, feel free to ask.