如何在datagridview中将日期列更新为自定义格式? - C#

时间:2015-03-05 13:27:32

标签: c# date datetime datagridview

在datagridview中,我显示了MySql数据库中的几个字段。

其中一个字段是DATE类型。 我将DATE列显示为自定义格式,即datagridview

中的dd / MM / yyyy
        dataGridView1.Columns["DATE"].DefaultCellStyle.Format = "dd/MM/yyyy";

这里我使用CommandBuilder从datagridview更新数据库。

当我想编辑日期列时,我以MM / dd / yyyy格式输入日期。它有效。

但我需要从datagridview以dd / MM / yyyy格式更新日期列。 如果我这样做,我会从datagridview

获得以下异常
The following exception occurred in the DataGridView


System.FormatException: String was not recognized as a valid DateTime.

at System.DateTimeParse.Parse(String s, DateTimeFormat dtfi,DateTimeStyles styles)

at System.DateTime.Parse(String s, IFormatProvider provider)

如何处理此异常以从datagridview接受日期字符串为“dd / MM / yyyy”?

提前致谢。

2 个答案:

答案 0 :(得分:2)

在日期列中,在datagridview中添加d​​atetimepicker控件并根据需要更改格式。在这里,我选择将日期格式化为dd / MM / yyyy

//Declare this variable     
    DateTimePicker dtp = new DateTimePicker();  //DateTimePicker  
    Rectangle _Rectangle;  

    public Form1()
    {
        InitializeComponent();

        dtp.Visible = false;  //  
        dtp.Format = DateTimePickerFormat.Custom;  
    }

    private void dtp_TextChange(object sender, EventArgs e)
    {
        dataGridView1.CurrentCell.Value = dtp.Value.ToString();  //
    }

    private void dtp_CloseUp(object sender, EventArgs e)
    {
        dtp.Visible = false;
    }


    private void button1_Click(object sender, EventArgs e)
    {
        try
        {
            connection.ConnectionString = "datasource=localhost;port=3306;username=root;password=root";
            string sql = "SELECT * FROM database.table";
            dataAdapter = new MySqlDataAdapter(sql, connection);
            dataTable = new DataTable();
            connection.Open();
            dataAdapter.Fill(dataTable);
            connection.Close();

            dataGridView1.DataSource = dataTable;
            dataGridView1.Columns["DATE"].DefaultCellStyle.Format = "dd/MM/yyyy";
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }
    private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
    {
            if (e.ColumnIndex == 2)  // here 2 is the date column in datagridview1
            {
                dataGridView1.Controls.Add(dtp);  
                dtp.Value =Convert.ToDateTime(dataGridView1.CurrentCell.Value.ToString());
                dtp.CustomFormat = "dd/MM/yyyy";    // change the custom format here to display on the datetimepicker
                dtp.TextChanged += new EventHandler(dtp_TextChange); //dtp_TextChange
                dtp.Visible = true;  //  


                _Rectangle = dataGridView1.GetCellDisplayRectangle(e.ColumnIndex, e.RowIndex, true); //  
                dtp.Size = new Size(_Rectangle.Width, _Rectangle.Height); //  
                dtp.Location = new Point(_Rectangle.X, _Rectangle.Y); //  

                dtp.CloseUp+=new EventHandler(dtp_CloseUp);

            }
            else
                dtp.Visible = false;  
    }

    private void dataGridView1_ColumnWidthChanged(object sender, DataGridViewColumnEventArgs e)
    {
        dtp.Visible = false;  
    }

    private void dataGridView1_Scroll(object sender, ScrollEventArgs e)
    {
        dtp.Visible = false;  
    }

这对我来说很有效。如果您收到任何错误,请告诉我。

答案 1 :(得分:0)

我的建议是,您必须手动检查每个单元格的格式。使用CellValueChanged事件。

在你的主要课程中:

String msg="";
private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
    string value = dataGridView1.CurrentCell.Value.ToString();
    dataGridView1.Rows[dataGridView1.CurrentCell.RowIndex].Cells["DATE"].Value = trapInputs(value);
    MessageBox.Show(msg);
}

public string trapInputs(string value)
{
    DateTime val = DateTime.Now;
            try
            {
                val = Convert.ToDateTime(value);
            }
            catch
            {
                if (value.Split('/').Length == 3)
                {
                    string[] arr = value.Split('/');
                    try
                    {
                        if (Convert.ToInt32(arr[1]) > Convert.ToInt32(arr[0]))
                        {
                            val = Convert.ToDateTime(arr[1] + "/" + arr[0] + "/" + arr[2]);
                        }
                    }
                    catch
                    {
                        msg = "Invalid date.";
                    }
                }
                else if(value.Split('-').Length==3)
                {
                    string[] arr = value.Split('-');
                    try
                    {
                        if (Convert.ToInt32(arr[1]) > Convert.ToInt32(arr[0]))
                        {
                            val = Convert.ToDateTime(arr[1] + "-" + arr[0] + "-" + arr[2]);
                        }
                    }
                    catch
                    {
                        msg = "Invalid date.";
                    }
                }
                else
                {
                    msg = "Invalid date.";
                }
            }
            value = String.Format("{0:yyyy-MM-dd}", val);
}