作成日: 2025/09/01 最終更新日: 2025/09/01
文書種別
使用方法
詳細
編集状態でセルに文字列を入力していくときに、そのカーソル位置を取得し、指定した位置に任意の文字を追加することができます。
例えば4文字入力後に"/"を自動的に追加するには、まず、C1FlexGridのStartEditイベントでエディタ(実態はTextBox)を取得します。次いで、そのTextChangedイベントでTextBoxのText.Lengthが4かどうかを確認し、該当する場合に "/” を追加します。
なおこのとき、TextBoxのSelectionStartメソッドを用いて、マウスカーソルを "/” の直後に移動することができます。
以下に簡単な設定例を記載します。
◎サンプルコード(VB)
Public Class Form1
Dim _inserting As Boolean = False
Private Sub C1FlexGrid1_StartEdit(sender As Object, e As C1.Win.C1FlexGrid.RowColEventArgs) Handles C1FlexGrid1.StartEdit
' FlexGrid が内部で使うエディタ (TextBox) を取得
Dim tb As TextBox = TryCast(C1FlexGrid1.Editor, TextBox)
If tb IsNot Nothing Then
' 多重登録防止
RemoveHandler tb.TextChanged, AddressOf Editor_TextChanged
AddHandler tb.TextChanged, AddressOf Editor_TextChanged
End If
End Sub
Private Sub Editor_TextChanged(sender As Object, e As EventArgs)
If _inserting Then Return ' 再帰呼び出し回避
Dim tb As TextBox = TryCast(sender, TextBox)
If tb Is Nothing Then Return
' 4 桁入力された時点で “/” が入っていなければ自動挿入
If tb.Text.Length = 4 AndAlso Not tb.Text.Contains("/") Then
_inserting = True
Dim caret As Integer = tb.SelectionStart ' 直前のカーソル位置を保持
tb.Text &= "/" ' “/” を追加
tb.SelectionStart = caret + 1 ' カーソルを “/” の直後へ
tb.SelectionLength = 0
_inserting = False
End If
End Sub
End Class◎サンプルコード(C#)
bool _inserting = false;
private void c1FlexGrid1_StartEdit(object sender, C1.Win.C1FlexGrid.RowColEventArgs e)
{
// FlexGrid が内部で使うエディタ (TextBox) を取得
if (c1FlexGrid1.Editor is TextBox tb)
{
// 多重登録防止
tb.TextChanged -= Editor_TextChanged;
tb.TextChanged += Editor_TextChanged;
}
}
private void Editor_TextChanged(object sender, EventArgs e)
{
if (_inserting) return; // 再帰呼び出し回避
var tb = sender as TextBox;
if (tb == null) return;
// 4 桁入力された時点で “/” が入っていなければ自動挿入
if (tb.Text.Length == 4 && !tb.Text.Contains("/"))
{
_inserting = true;
int caret = tb.SelectionStart; // 直前のカーソル位置を保持
tb.Text += "/"; // “/” を追加
//tb.SelectionStart = caret + 1; // カーソルを “/” の直後へ
tb.SelectionLength = 0;
_inserting = false;
}
}