Quantcast
Channel: Windows Forms Data Controls and Databinding forum
Viewing all articles
Browse latest Browse all 2535

C# DataGridView host a control in the current DataGridViewCell for editing - PROBLEM

$
0
0

Hello

I have DataGridView with DataTable as source

dt = new DataTable();
dt.Columns.Add(new DataColumn("testString", typeof(String)));
dt.Columns.Add(new DataColumn("testDate", typeof(DateTime)));
dataGridView1.DataSource = dt;

For the second column "testDate" i try to use hosted MaskedTextBox for editing

but in any cases i reseive error (e.Exception.Message) "String was not recognized as valid DateTime" even if it is valid date

If i press ESC key if string is valid date value is accepted but still the same cell is focused.

Also if i click first the cell with mouse and edit after that than is ok.

Please for sugestions,

Best regards,

My Code

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Globalization;

namespace TestDGV
{
    public partial class Form1 : Form
    {
        DataGridView dataGridView1;
        DataTable dt;

        MaskedTextBox maskedTextBoxForEditing;
        bool IsKeyPressHandled = false;

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            // New DataGridView
            dataGridView1 = new DataGridView();
            dataGridView1.Dock = DockStyle.Fill;

            this.Controls.Add(dataGridView1);

            // New DataTable
            dt = new DataTable();
            dt.Columns.Add(new DataColumn("testString", typeof(String)));
            dt.Columns.Add(new DataColumn("testDate", typeof(DateTime)));
            dataGridView1.DataSource = dt;

            // MaskedTextBox
            this.maskedTextBoxForEditing = new MaskedTextBox();
            this.maskedTextBoxForEditing.Mask = "00/00/0000";
            this.maskedTextBoxForEditing.PromptChar = ' ';
            // Hide the MaskedTextBox
            this.maskedTextBoxForEditing.Visible = false;
            // Add the MaskedTextBox to the DataGridView's control collection
            this.dataGridView1.Controls.Add(this.maskedTextBoxForEditing);


            // the current editing cell
            this.dataGridView1.CellBeginEdit +=
                new DataGridViewCellCancelEventHandler(dataGridView1_CellBeginEdit);

            // Handle the CellEndEdit event to hide the MaskedTextBox when
            // editing completes.
            this.dataGridView1.CellEndEdit += new DataGridViewCellEventHandler(dataGridView1_CellEndEdit);

            // Handle the Scroll event to adjust the location of the MaskedTextBox as it is showing
            // when scrolling the DataGridView
            this.dataGridView1.Scroll += new ScrollEventHandler(dataGridView1_Scroll);

            // Handle the EditingControlShowing event to pass the focus to the
            // MaskedTextBox when begin editing with keystrokes
            this.dataGridView1.EditingControlShowing +=
                new DataGridViewEditingControlShowingEventHandler(dataGridView1_EditingControlShowing);

            // Attach the DataError event to the corresponding event handler.
            this.dataGridView1.DataError +=
                new DataGridViewDataErrorEventHandler(dataGridView1_DataError);
        }

        #region For MaskedTextBox

        void dataGridView1_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
        {
            // If the current cell is on the "MaskColumn", we use the MaskedTextBox control
            // for editing instead of the default TextBox control;
            if (e.ColumnIndex == this.dataGridView1.Columns["testDate"].Index)
            {
                // Calculate the cell bounds of the current cell
                Rectangle rect = this.dataGridView1.GetCellDisplayRectangle(
                    e.ColumnIndex, e.RowIndex, true);
                // Adjust the MaskedTextBox's size and location to fit the cell
                this.maskedTextBoxForEditing.Size = rect.Size;
                this.maskedTextBoxForEditing.Location = rect.Location;

                // Set value for the MaskedTextBox
                if (this.dataGridView1.CurrentCell.Value != null)
                {
                    this.maskedTextBoxForEditing.Text = this.dataGridView1.CurrentCell.Value.ToString();
                }

                // Show the MaskedTextBox
                this.maskedTextBoxForEditing.Visible = true;
            }
        }

        void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            // When finish editing on the "MaskColumn", we replace the cell value with
            // the text typed in the MaskedTextBox, and hide the MaskedTextBox;
            if (e.ColumnIndex == this.dataGridView1.Columns["testDate"].Index)
            {
                this.dataGridView1.CurrentCell.Value = this.maskedTextBoxForEditing.Text;
                // this.dataGridView1.CurrentCell.Value = Convert.ToDateTime(this.maskedTextBoxForEditing.Text);

                this.maskedTextBoxForEditing.Text = "";
                this.maskedTextBoxForEditing.Visible = false;
            }
        }

        void dataGridView1_Scroll(object sender, ScrollEventArgs e)
        {
            if (this.dataGridView1.IsCurrentCellInEditMode == true)
            {
                // Adjust the location for the MaskedTextBox while scrolling
                Rectangle rect = this.dataGridView1.GetCellDisplayRectangle(
                    this.dataGridView1.CurrentCell.ColumnIndex,
                    this.dataGridView1.CurrentCell.RowIndex, true);

                /*
                Console.WriteLine(rect.ToString());
                Console.WriteLine(this.dataGridView1.CurrentCellAddress.ToString());
                Console.WriteLine("");
                */

                if (rect.X <= 0 || rect.Y <= 0)
                {
                    this.maskedTextBoxForEditing.Visible = false;
                }
                else
                {
                    this.maskedTextBoxForEditing.Location = rect.Location;
                }
            }
        }

        void dataGridView1_EditingControlShowing(object sender,
            DataGridViewEditingControlShowingEventArgs e)
        {
            if (!this.IsKeyPressHandled
                && this.dataGridView1.CurrentCell.ColumnIndex ==
                this.dataGridView1.Columns["testDate"].Index)
            {
                TextBox tb = e.Control as TextBox;
                tb.KeyPress += new KeyPressEventHandler(tb_KeyPress);
                this.IsKeyPressHandled = true;
            }
        }

        void tb_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (this.dataGridView1.CurrentCell.ColumnIndex ==
                this.dataGridView1.Columns["testDate"].Index)
            {
                // Prevent the key char to be input in the editing control
                // e.Handled = true;

                // Set focus to the MaskedTextBox for editing.
                this.maskedTextBoxForEditing.SelectionStart = 0;
                this.maskedTextBoxForEditing.Focus();

                this.maskedTextBoxForEditing.SelectionStart = 0;

                // SendKeys.Send(e.KeyChar.ToString());
            }
        }

        void dataGridView1_DataError(object sender,
            DataGridViewDataErrorEventArgs e)
        {
            // If the data source raises an exception when a cell value is
            // commited, display an error message.

            if (e.Exception != null)
            {
                MessageBox.Show("Data error !" + "\n\n" + e.Exception.Message);
            }
        }

        #endregion

    }
}



Viewing all articles
Browse latest Browse all 2535

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>