blah blah blah is here! blah blah » Close

up0down
link

I wanted the user to input values in "dd MMM yyyy" format Only, I'm using dataGridView1.Columns["Rel_Date"].DefaultCellStyle.Format = "dd MMM yyyy"; in Form_Load.........

But somehow it's not working. I can still enter anything in the cell/column. anything like:

  • sdfsfasfsf
  • or
  • 1345345
  • etc.

    last answered one year ago

    2 answers

    up1down
    link

    data grid views are dynamic controls used to render a variety of data. cells some how represent disparate data types, and therefor use a "Format" string to call datum's ToString() method passing in this format string.

    If you wish to restrict what is entered into a cell, handle the CellValidating and or CellEndEdit events:

    http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.cellvalidating%28v=VS.100%29.aspx

    http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.cellendedit%28v=VS.100%29.aspx

    gsvirdi
    412

    Thx MH for guidance, let me look into this thing also.... :)

    up0down
    link

    When DataGrid is populated set the format of the column, so this code comes into my Form1_Load event.....
    dataGridView1.Columns["Rel_Date"].DefaultCellStyle.Format = "dd MMM yyyy";


    In DataGridView's CellValidating event use this code:

    DateTime temp;
    if (dataGridView1.Rows[e.RowIndex].IsNewRow)
    return;
    string format = "dd MMM yyyy";
    if (!DateTime.TryParseExact(e.FormattedValue.ToString(), format, null,0, out temp))
    {
    e.Cancel = true;
    dataGridView1.Rows[e.RowIndex].ErrorText = "The date entered should be in \"dd MMM yyyy\" format only.";
    }

    Feedback