본문 바로가기
소소한 C# 지식

[C#] c# Winform Text 박스 - 글자수 제한, 리셋

by 해뤼맘 2022. 7. 9.
728x90
반응형

안녕하세요

C#에서 사용하는 Text 박스 글자수 제한 및 Text 박스 리셋하는 간단한 코드 입니다.

1. Text Box MaxLenght Check

public string CheckBytesTextBox(int maxLength,TextBox txtContents)
        {
            string contents = txtContents.Text;
            Byte[] contentsByte = Encoding.Default.GetBytes(contents);
            if (contentsByte.Length > maxLength)
            {
                 MessageBox.Show($"{maxLength} Bytes를 초과하여 입력하실 수 없습니다.");

                while (contentsByte.Length > maxLength)
                {
                    //한글자씩 줄여나감.
                    contents = contents.Substring(0, contents.Length - 1);
                    contentsByte = Encoding.Default.GetBytes(contents);
                }

                txtContents.Text = contents;
                txtContents.Focus();
                txtContents.SelectionStart = contents.Length;
            }

            return $"{contentsByte.Length} Bytes / {maxLength} Bytes";
        }

2. Text Box Reset

 public void ResetTextBox(Control.ControlCollection controlCollection)
        {
            foreach (Control c in controlCollection)
            {
                if (c.Controls.Count > 0)
                {
                    //Recursive Calll
                    ResetTextBox(c.Controls);
                }

                if (c.GetType() == typeof(TextBox))
                {
                    ((TextBox)c).Text = string.Empty;
                }
            }
        }
728x90
반응형

댓글