Class SfTextBox
Represents the Toolkit TextBox component for Blazor applications, which provides an enhanced input element that allows users to enter and edit text values with advanced features like floating labels, input validation, clear button functionality, and various styling options.
Implements
Inherited Members
Namespace: Syncfusion.Blazor.Toolkit.Inputs
Assembly: Syncfusion.Blazor.Toolkit.dll
Syntax
public class SfTextBox : SfInputBase<string>, IAsyncDisposable
Remarks
The SfTextBox component extends the standard HTML input element with additional functionality including:
- Support for floating labels (Auto, Always, Never)
- Built-in clear button with customizable behavior
- Input validation with visual feedback
- Accessibility features with ARIA support
- Integration with Blazor's EditForm validation
- Persistence support for maintaining state across browser sessions
- Customizable styling and theming options
Examples
The following code example demonstrates how to create a basic TextBox with floating label and clear button:
<SfTextBox @bind-Value="@textValue"
Placeholder="Enter your name"
FloatLabelType="FloatLabelType.Auto"
ShowClearButton="true">
</SfTextBox>
@code {
private string textValue = "";
}
Constructors
SfTextBox()
Declaration
public SfTextBox()
Properties
Autocomplete
Gets or sets a value indicating whether the browser should automatically complete or suggest values for the SfTextBox component.
Declaration
public AutoComplete Autocomplete { get; set; }
Property Value
| Type | Description |
|---|---|
| AutoComplete | An AutoComplete enumeration value specifying the autocomplete behavior. The default value is On. |
Remarks
This property controls the HTML autocomplete attribute behavior. When enabled, browsers may display a dropdown list of previously entered values for the same field.
Possible values:
Examples
<SfTextBox Autocomplete="AutoComplete.Off" Placeholder="Enter password"></SfTextBox>
Created
Gets or sets the event callback that is invoked when the SfTextBox component is created.
Declaration
public EventCallback<object> Created { get; set; }
Property Value
| Type | Description |
|---|---|
| Microsoft.AspNetCore.Components.EventCallback<System.Object> | An Microsoft.AspNetCore.Components.EventCallback<> that is invoked when the TextBox component is successfully created and rendered. The callback receives an System.Object parameter. |
Remarks
The Created event is triggered after the TextBox component has been fully initialized and rendered in the DOM.
This event is useful for performing initialization tasks, setting up additional configurations, or integrating with JavaScript interop that requires the component to be fully rendered.
Examples
<SfTextBox Placeholder="Enter text" Created="@OnCreated">
</SfTextBox>
@code{
private void OnCreated(object args)
{
// Component initialization logic
Console.WriteLine("TextBox component created successfully");
}
}
Destroyed
Gets or sets the event callback that is invoked when the SfTextBox component is destroyed.
Declaration
public EventCallback<object> Destroyed { get; set; }
Property Value
| Type | Description |
|---|---|
| Microsoft.AspNetCore.Components.EventCallback<System.Object> | An Microsoft.AspNetCore.Components.EventCallback<> that is invoked when the TextBox component is being destroyed or removed from the DOM. The callback receives an System.Object parameter. |
Remarks
The Destroyed event is triggered when the TextBox component is being disposed or removed from the component tree.
This event provides an opportunity to perform cleanup operations, such as removing event listeners, clearing timers, canceling pending operations, or releasing resources that were allocated during the component's lifecycle.
This event occurs only once, at the end of the component's lifecycle, just before it is removed from the DOM.
Examples
<SfTextBox Placeholder="Enter text" Destroyed="@OnDestroyed">
</SfTextBox>
@code{
private void OnDestroyed(object args)
{
// Cleanup logic
Console.WriteLine("TextBox component destroyed");
}
}
FloatLabelType
Gets or sets the floating label behavior of the SfTextBox component. The Placeholder text acts as a floating label.
Declaration
public FloatLabelType FloatLabelType { get; set; }
Property Value
| Type | Description |
|---|---|
| FloatLabelType | A FloatLabelType enumeration value specifying how the Placeholder text behaves as a floating label. The default value is Never. |
Remarks
The floating label behavior determines how the placeholder text is displayed:
Examples
<SfTextBox FloatLabelType="FloatLabelType.Auto" Placeholder="Enter a value"></SfTextBox>
HtmlAttributes
Gets or sets a collection of additional HTML attributes that will be applied to the outer wrapper element of the SfTextBox component.
Declaration
public Dictionary<string, object> HtmlAttributes { get; set; }
Property Value
| Type | Description |
|---|---|
| System.Collections.Generic.Dictionary<System.String, System.Object> | A System.Collections.Generic.Dictionary<, > of System.String keys and System.Object values representing HTML attributes to be applied to the wrapper element. The default value is null. |
Remarks
This property allows adding custom HTML attributes to the TextBox wrapper element, such as:
class- Additional CSS classesstyle- Inline CSS stylestitle- Tooltip textdata-*- Custom data attributes- Other standard HTML attributes
Note: If both a component property and its equivalent HTML attribute are configured, the component property takes precedence.
Examples
<SfTextBox HtmlAttributes="@customAttributes">
</SfTextBox>
@code {
Dictionary<string, object> customAttributes = new Dictionary<string, object>()
{
{ "title", "Enter your full name" },
{ "class", "custom-textbox" },
{ "data-testid", "name-input" }
};
}
InputAttributes
Gets or sets a collection of additional HTML attributes that will be applied directly to the input element of the SfTextBox component.
Declaration
public Dictionary<string, object> InputAttributes { get; set; }
Property Value
| Type | Description |
|---|---|
| System.Collections.Generic.Dictionary<System.String, System.Object> | A System.Collections.Generic.Dictionary<, > of System.String keys and System.Object values containing attribute names and values to be applied to the input element. The default value is an empty dictionary. |
Remarks
This property captures unmatched attributes and applies them directly to the HTML input element. Common attributes include:
maxlength- Maximum number of characters allowedminlength- Minimum number of characters requiredpattern- Regular expression pattern for validationautocomplete- Browser autocomplete behaviorspellcheck- Spellcheck functionalitydata-*- Custom data attributes
Attributes can be specified using inline attributes or the @attributes directive.
Note: If both a component property and its equivalent HTML attribute are configured, the component property takes precedence.
Examples
<!-- Using @attributes directive -->
<SfTextBox Placeholder="Enter PIN" @attributes="@_inputAttributes">
</SfTextBox>
<!-- Using inline attributes -->
<SfTextBox Placeholder="Enter email" maxlength="50" pattern="[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}$">
</SfTextBox>
@code {
Dictionary<string, object> _inputAttributes = new Dictionary<string, object>()
{
{ "maxlength", "4" },
{ "pattern", "[0-9]{4}" },
{ "autocomplete", "one-time-code" }
};
}
Multiline
Gets or sets a value indicating whether the SfTextBox operates in multiline mode (textarea).
Declaration
public bool Multiline { get; set; }
Property Value
| Type | Description |
|---|---|
| System.Boolean | A System.Boolean value indicating whether multiline mode is enabled. When true, the component renders as a textarea element; when false, it renders as a single-line input element. The default value is false. |
Remarks
When multiline mode is enabled, the TextBox transforms into a textarea element that supports:
- Multiple lines of text input
- Line breaks and paragraph formatting
- Scrolling when content exceeds the visible area
- Resizable functionality (browser-dependent)
This mode is particularly useful for capturing longer text content such as comments, descriptions, addresses, or any scenario requiring multi-line input.
Examples
<SfTextBox @bind-Value="@description"
Multiline="true"
Placeholder="Enter your description"
FloatLabelType="FloatLabelType.Auto">
</SfTextBox>
@code {
private string description = "";
}
OnBlur
Gets or sets the event callback that is invoked when the SfTextBox loses focus.
Declaration
public EventCallback<FocusOutEventArgs> OnBlur { get; set; }
Property Value
| Type | Description |
|---|---|
| Microsoft.AspNetCore.Components.EventCallback<FocusOutEventArgs> | An Microsoft.AspNetCore.Components.EventCallback<> that is invoked when the TextBox loses focus. The callback receives a FocusOutEventArgs containing event data. |
Remarks
The OnBlur event is triggered when the user clicks outside the TextBox or navigates away from it using keyboard navigation (such as pressing the Tab key).
This event is useful for performing validation, saving changes, or updating the UI when the user finishes interacting with the TextBox.
Examples
<SfTextBox Placeholder="Enter your name" OnBlur="@OnBlur">
</SfTextBox>
@code{
private void OnBlur(FocusOutEventArgs args)
{
// Perform validation or other actions when TextBox loses focus
Console.WriteLine("TextBox lost focus");
}
}
OnFocus
Gets or sets the event callback that is invoked when the SfTextBox receives focus.
Declaration
public EventCallback<FocusInEventArgs> OnFocus { get; set; }
Property Value
| Type | Description |
|---|---|
| Microsoft.AspNetCore.Components.EventCallback<FocusInEventArgs> | An Microsoft.AspNetCore.Components.EventCallback<> that is invoked when the TextBox receives focus. The callback receives a FocusInEventArgs containing event data. |
Remarks
The OnFocus event is triggered when the user clicks on the TextBox, navigates to it using keyboard navigation (such as the Tab key), or when focus is programmatically set to the component.
This event is useful for highlighting the TextBox, showing additional UI elements such as tooltips or help text, selecting all text, or preparing the component for user input.
Examples
<SfTextBox Placeholder="Enter your email" OnFocus="@OnFocus">
</SfTextBox>
@code{
private void OnFocus(FocusInEventArgs args)
{
// Perform actions when TextBox gains focus
Console.WriteLine("TextBox gained focus");
}
}
OnInput
Gets or sets the event callback that is invoked when the user types, pastes, or modifies text in the SfTextBox.
Declaration
public EventCallback<InputEventArgs> OnInput { get; set; }
Property Value
| Type | Description |
|---|---|
| Microsoft.AspNetCore.Components.EventCallback<InputEventArgs> | An Microsoft.AspNetCore.Components.EventCallback<> of InputEventArgs that is invoked during real-time text input. |
Remarks
The OnInput event is triggered whenever the user interacts with the TextBox by typing, pasting, cutting, or using any input method to modify the content. It provides real-time updates as the user enters text, allowing actions or validation based on the changing input.
This event fires frequently during user input, potentially with each keystroke, making it suitable for real-time updates, character counting, or dynamic filtering. For performance-sensitive operations, consider using the ValueChange event instead, which fires only when the TextBox loses focus.
The InputEventArgs parameter provides access to both the Value and PreviousValue properties, enabling incremental change tracking.
Examples
<SfTextBox Placeholder="Enter a value" OnInput="@OnInput">
</SfTextBox>
@code{
private void OnInput(InputEventArgs args)
{
var TextValue = args.Value;
}
}
Placeholder
Gets or sets the placeholder text that is displayed when the SfTextBox has no value.
Declaration
public string Placeholder { get; set; }
Property Value
| Type | Description |
|---|---|
| System.String | A System.String representing the placeholder text displayed when the TextBox has no value. The default value is null. |
Remarks
The placeholder text provides a hint to users about what should be entered in the TextBox.
The behavior of the placeholder depends on the FloatLabelType property:
- When FloatLabelType is Never, the placeholder text disappears when the TextBox gains focus.
- When FloatLabelType is Auto or Always, the placeholder text acts as a floating label.
Examples
<SfTextBox Placeholder="Enter your email address" FloatLabelType="FloatLabelType.Auto"></SfTextBox>
ReadOnly
Gets or sets a value indicating whether the SfTextBox is read-only and prevents user input.
Declaration
public bool ReadOnly { get; set; }
Property Value
| Type | Description |
|---|---|
| System.Boolean | A System.Boolean value indicating whether the TextBox is read-only. When true, the component cannot be edited by the user; when false, the component is editable. The default value is false. |
Remarks
When the TextBox is set to read-only mode, users can view and select the text content but cannot modify it.
The component will still participate in form submission and data binding operations.
Examples
<SfTextBox @bind-Value="@readOnlyValue" ReadOnly="true" Placeholder="Read-only text"></SfTextBox>
ShowClearButton
Gets or sets a value indicating whether the clear button is displayed in the SfTextBox component.
Declaration
public bool ShowClearButton { get; set; }
Property Value
| Type | Description |
|---|---|
| System.Boolean | A System.Boolean value indicating whether the clear button should be shown. When true, the clear button is displayed; when false, it is hidden. The default value is false. |
Remarks
The clear button appears when the TextBox has a value and allows users to quickly clear the entire content with a single click.
The button is typically displayed as an 'X' icon on the right side of the TextBox.
Examples
<SfTextBox @bind-Value="@textValue" ShowClearButton="true" Placeholder="Enter text"></SfTextBox>
TabIndex
Gets or sets the tab order of the SfTextBox component in the tab navigation sequence.
Declaration
public int TabIndex { get; set; }
Property Value
| Type | Description |
|---|---|
| System.Int32 | An System.Int32 value representing the tab index of the TextBox component. The default value is |
Remarks
The TabIndex property determines the order in which components receive focus when the user navigates using the Tab key.
- A value of
0means the component participates in the default tab order. - A positive value specifies the explicit tab order position.
- A negative value removes the component from the tab navigation sequence.
Examples
<SfTextBox TabIndex="1" Placeholder="First in tab order"></SfTextBox>
<SfTextBox TabIndex="2" Placeholder="Second in tab order"></SfTextBox>
Type
Gets or sets the input type behavior of the SfTextBox component, such as text, password, email, and more.
Declaration
public InputType Type { get; set; }
Property Value
| Type | Description |
|---|---|
| InputType | An InputType enumeration value specifying the type of input element to render. The default value is Text. |
Remarks
The input type determines the behavior, validation, and appearance of the TextBox:
- Text - Standard text input
- Password - Password input with masked characters
- Email - Email input with built-in validation
- Number - Numeric input with spinner controls
- Tel - Telephone number input
- URL - URL input with validation
- Search - Search input with search-specific styling
Different input types may trigger different virtual keyboards on mobile devices and provide built-in browser validation.
Examples
<SfTextBox Type="InputType.Email" Placeholder="Enter your email"></SfTextBox>
<SfTextBox Type="InputType.Password" Placeholder="Enter your password"></SfTextBox>
<SfTextBox Type="InputType.Tel" Placeholder="Enter your phone number"></SfTextBox>
ValueChange
Gets or sets the event callback that is invoked when the SfTextBox content has changed and the component loses focus.
Declaration
public EventCallback<ChangedEventArgs> ValueChange { get; set; }
Property Value
| Type | Description |
|---|---|
| Microsoft.AspNetCore.Components.EventCallback<ChangedEventArgs> | An Microsoft.AspNetCore.Components.EventCallback<> that is invoked when the TextBox content changes and loses focus. The callback receives a ChangedEventArgs containing the previous and current values. |
Remarks
The ValueChange event is triggered only when the TextBox loses focus and the value has actually changed from its previous state.
This differs from the OnInput event, which fires on every keystroke during real-time input. Use ValueChange for final value processing, validation, or when comparing the old and new values is required.
Examples
<SfTextBox Placeholder="Enter a value" ValueChange="@OnChange">
</SfTextBox>
@code{
private void OnChange(ChangedEventArgs args)
{
var TextValue = args.Value;
var PreviousValue = args.PreviousValue;
// Process the changed value
}
}
Width
Gets or sets the width of the SfTextBox component.
Declaration
public string Width { get; set; }
Property Value
| Type | Description |
|---|---|
| System.String | A System.String representing the width in pixels, percentage, or other CSS units. The default value is null, which renders as 100%. |
Remarks
The width can be specified using various CSS units such as pixels (px), percentages (%), em, rem, etc.
If not specified, the component will take the full width of its container.
Examples
<SfTextBox Width="300px"></SfTextBox>
<SfTextBox Width="50%"></SfTextBox>
<SfTextBox Width="20rem"></SfTextBox>
Methods
AddIconAsync(String, String, Dictionary<String, Object>)
Adds icons to the SfTextBox component at the specified position.
Declaration
public Task AddIconAsync(string position, string icons, Dictionary<string, object> events = null)
Parameters
| Type | Name | Description |
|---|---|---|
| System.String | position | A System.String specifying the position where icons should be added. Valid values are |
| System.String | icons | A System.String containing the CSS classes representing the icons to be added to the icon element. Multiple classes can be specified as space-separated values. |
| System.Collections.Generic.Dictionary<System.String, System.Object> | events | An optional System.Collections.Generic.Dictionary<, > of System.String keys and System.Object values containing icon events to be added. The dictionary key represents the event type (e.g., "ontouchstart"), and the value represents the event handler method. The default value is null. |
Returns
| Type | Description |
|---|---|
| System.Threading.Tasks.Task | A System.Threading.Tasks.Task representing the asynchronous operation that completes when the icons have been added. |
Remarks
This method allows dynamic addition of icons to the TextBox component either before (prepend) or after (append) the input field.
The icons parameter accepts CSS class names that define the visual appearance of the icons. When providing the events parameter, use the event type as the key and the event handler method as the value in the dictionary.
If the position parameter is null or empty, no icons will be added.
Icons are typically rendered as span elements with the specified CSS classes, allowing customization through styling.
Examples
The following code demonstrates adding a prepended icon with a touch event handler:
<SfTextBox @ref="textBoxRef" Placeholder="Enter Date"></SfTextBox>
@code {
SfTextBox textBoxRef;
private async Task AddDateIcon()
{
var iconEvents = new Dictionary<string, object>()
{
{ "onclick", new Action(OnIconClick) },
{ "ontouchstart", new Action(OnIconTouch) }
};
await textBoxRef.AddIconAsync("prepend", "e-date-icon", iconEvents);
}
private void OnIconClick()
{
// Handle icon click
}
private void OnIconTouch()
{
// Handle icon touch
}
}
BuildRenderTree(RenderTreeBuilder)
Declaration
protected override void BuildRenderTree(RenderTreeBuilder __builder)
Parameters
| Type | Name | Description |
|---|---|---|
| Microsoft.AspNetCore.Components.Rendering.RenderTreeBuilder | __builder |
FocusAsync()
Sets the focus to the SfTextBox component to enable user interaction.
Declaration
public Task FocusAsync()
Returns
| Type | Description |
|---|---|
| System.Threading.Tasks.Task | A System.Threading.Tasks.Task representing the asynchronous operation that completes when focus has been set. |
Remarks
This method programmatically moves the keyboard focus to the TextBox input element, allowing users to immediately start typing.
When called, the TextBox receives focus and displays the focus indicator (typically a border highlight or cursor). This is useful for improving user experience by automatically focusing important input fields or implementing custom navigation flows.
Examples
<SfTextBox @ref="textBoxRef" Placeholder="Enter your text here"></SfTextBox>
@code {
SfTextBox textBoxRef;
private async Task SetFocusToTextBox()
{
await textBoxRef.FocusAsync();
}
}
FocusOutAsync()
Removes the focus from the SfTextBox component if it is currently in focus state.
Declaration
public Task FocusOutAsync()
Returns
| Type | Description |
|---|---|
| System.Threading.Tasks.Task | A System.Threading.Tasks.Task representing the asynchronous operation that completes when focus has been removed. |
Remarks
This method programmatically removes keyboard focus from the TextBox input element, causing it to blur.
When called, the TextBox loses focus and hides the focus indicator, and any validation or change events may be triggered. This is useful for implementing custom form validation, navigation flows, or when programmatically shifting focus to other elements.
If the TextBox is not currently focused, this method has no effect.
Examples
<SfTextBox @ref="textBoxRef" Placeholder="Enter your text here"></SfTextBox>
@code {
SfTextBox textBoxRef;
private async Task RemoveFocusFromTextBox()
{
await textBoxRef.FocusOutAsync();
}
}
GetPersistDataAsync()
Retrieves the properties to be maintained in the persisted state from local storage.
Declaration
public Task<string> GetPersistDataAsync()
Returns
| Type | Description |
|---|---|
| System.Threading.Tasks.Task<System.String> | A System.Threading.Tasks.Task<> of System.String containing the persisted component state as a JSON-formatted string, or null if persistence is disabled or no previously saved state exists. The returned JSON includes properties such as Value, Enabled state, ReadOnly state, and other user-modified settings. |
Remarks
This method accesses the browser's local storage to retrieve previously saved component state using the component's ID as the key.
The persisted data typically includes user-modified properties such as the current value, enabled state, and other configurable settings. This functionality supports the component's state persistence feature, allowing the TextBox to restore its previous state across browser sessions.
The returned string is in JSON format and can be deserialized to restore the component's state using the corresponding persistence methods.
Persistence is only enabled if the EnablePersistence property is set to true and a unique component ID is assigned.
Examples
<SfTextBox @ref="textBoxRef" ID="myTextBox" EnablePersistence="true" Placeholder="Enter your text here"></SfTextBox>
@code {
SfTextBox? textBoxRef;
private async Task GetPersistedData()
{
if (textBoxRef != null)
{
string? persistedData = await textBoxRef.GetPersistDataAsync();
if (!string.IsNullOrEmpty(persistedData))
{
// Parse and process the persisted data
Console.WriteLine($"Persisted data: {persistedData}");
// Example: deserialize JSON to extract specific properties
}
}
}
}