文字列型セル(TextBoxCell)でバイト単位で入力文字数を制限する方法

文書番号 : 40509     文書種別 : 使用方法     登録日 : 2017/07/26     最終更新日 : 2017/07/26
文書を印刷する
対象製品
MultiRow for Windows Forms 10.0J
詳細
次のコードは、TextBoxCellで入力可能文字数を6バイトに設定する例です。

[Visual Basic]
Imports System.Text
Imports GrapeCity.Win.MultiRow

Private Sub GcMultiRow1_EditingControlShowing(ByVal sender As System.Object, ByVal e As EditingControlShowingEventArgs) Handles GcMultiRow1.EditingControlShowing
    If TypeOf e.Control Is TextBoxEditingControl Then
        Dim textBox As TextBoxEditingControl = TryCast(e.Control, TextBoxEditingControl)
        If textBox IsNot Nothing Then
            RemoveHandler textBox.TextChanged, AddressOf Me.textBox_TextChanged
            AddHandler textBox.TextChanged, AddressOf Me.textBox_TextChanged
        End If
    End If
End Sub

Private Sub textBox_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs)
    Dim textBox As TextBox = TryCast(sender, TextBox)
    Dim sjis As Encoding = Encoding.GetEncoding("Shift-JIS")
    Dim maxLengthAsByte As Integer = 6
    Dim sourceText() As Byte = sjis.GetBytes(textBox.Text.ToCharArray())

    If sourceText.Length > maxLengthAsByte Then
        Array.Resize(Of Byte)(sourceText, maxLengthAsByte)
        textBox.Text = sjis.GetString(sourceText)
        textBox.SelectionStart = textBox.Text.Length
    End If
End Sub

[C#]
using GrapeCity.Win.MultiRow;

private void gcMultiRow1_EditingControlShowing(object sender, EditingControlShowingEventArgs e)
{
    if (e.Control is TextBoxEditingControl)
    {
        TextBoxEditingControl textBox = e.Control as TextBoxEditingControl;
        if (textBox != null)
        {
            textBox.TextChanged -= new EventHandler(textBox_TextChanged);
            textBox.TextChanged += new EventHandler(textBox_TextChanged);
        }
    }
}

private void textBox_TextChanged(object sender, EventArgs e)
{
    TextBox textBox = sender as TextBox;
    Encoding sjis = Encoding.GetEncoding("Shift-JIS");
    int maxLengthAsByte = 6;
    byte[] sourceText = sjis.GetBytes(textBox.Text.ToCharArray());

    if (sourceText.Length > maxLengthAsByte)
    {
        Array.Resize<byte>(ref sourceText, maxLengthAsByte);
        textBox.Text = sjis.GetString(sourceText);
        textBox.SelectionStart = textBox.Text.Length;
    }
}

参考:
  • InputManCellのGcTextBoxCellを使用すると、バイト単位で入力文字数を簡単に指定できます。(GcTextBoxCell.MaxLengthUnitプロパティ)