星期五, 6月 16, 2017

[C#] DataGridView - 輸入強制大寫

實務上有需求,了解一下如何在 DataGridViewTextBoxColumn 輸入時或輸入後,把內容通通變成大寫,有兩個方向可以做到
  • EditingControlShowing Event 內
  • CellEndEdit Event 內
簡易 Layout 設計

[C#] DataGridView - 輸入強制大寫-1



相關 Code
namespace dgvUpper
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

            dataGridView1.AutoGenerateColumns = false;
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            DataTable dt = new DataTable("Demo");
            dt.Columns.Add("Data" , typeof(string));
            dt.Columns.Add("Data2", typeof(string));
            dataGridView1.DataSource = dt;

            dataGridView1.EditingControlShowing += DataGridView1_EditingControlShowing;
            dataGridView1.CellEndEdit += DataGridView1_CellEndEdit;
        }

        // 輸入時就已經是大寫
        private void DataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
        {
            if (e.Control is DataGridViewTextBoxEditingControl txt)
            {
                if (sender is DataGridView dgv
                    && dgv.CurrentCell.ColumnIndex == 0)
                {
                    txt.CharacterCasing = CharacterCasing.Upper;
                }
                else
                {
                    txt.CharacterCasing = CharacterCasing.Normal;
                }
            }
        }

        // 輸入結束後才會轉為大寫
        private void DataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            int ColumnIndex = e.ColumnIndex;

            if (sender is DataGridView dgv 
                && dgv.Columns[e.ColumnIndex].GetType() == typeof(DataGridViewTextBoxColumn) 
                && ColumnIndex == 1)
            {
                int RowIndex = e.RowIndex;
                DataGridViewCell cell = dgv.Rows[RowIndex].Cells[ColumnIndex];
                cell.Value = cell.Value.ToString().ToUpper();
            }
        }
    }
}

EditingControlShowing Event 內建立大寫功能,輸入時就會全部是大寫

[C#] DataGridView - 輸入強制大寫-2

在網路上有看見 DataGridViewEditingControlShowingEventArgs.Control 轉為 TextBox,查了一下 MSDN 發現原來 DataGridViewTextBoxEditingControl 是從 TextBox 繼承來的

[C#] DataGridView - 輸入強制大寫-4

CellEndEdit Event 內建立大寫功能,輸入結束後才會是大寫

[C#] DataGridView - 輸入強制大寫-3

沒有留言:

張貼留言