1
votes

I have a DataTable which is populated by Lists (which are populated from a csv file, not really important though). This DataTable is rendered by a DataGridView and the user is allowed to edit it.

        // Initialise DataTable
        DataTable dt = new DataTable();

        // Add columns to DataTable
        dt.Columns.Add("Weight Category");
        dt.Columns.Add("United Kingdom");
        dt.Columns.Add("Rest of Europe");
        dt.Columns.Add("World Wide");

        // Add rows to DataTable
        dt.Rows.Add(weightCategory[0], ukCosts[0], roeCosts[0], wwCosts[0]);
        dt.Rows.Add(weightCategory[1], ukCosts[1], roeCosts[1], wwCosts[1]);
        dt.Rows.Add(weightCategory[2], ukCosts[2], roeCosts[2], wwCosts[2]);
        dt.Rows.Add(weightCategory[3], ukCosts[3], roeCosts[3], wwCosts[3]);
        dt.Rows.Add(weightCategory[4], ukCosts[4], roeCosts[4], wwCosts[4]);
        dt.Rows.Add(weightCategory[5], ukCosts[5], roeCosts[5], wwCosts[5]);

        return dt;

Changes will then be saved to the original csv file. I would like to validate the cells so that the user can only type digits/1 decimal point. I currently do this with the following CellValidating event which prevents the user leaving a cell. The issue is that my first column contains text. This column is read only and I don't want it to be validated at all, is there any way to skip it / suppress validation? Otherwise I get locked into not being able to leave those cells.

    private void dgvDeliveryCosts_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
    {
        double output;

        if (!double.TryParse(e.FormattedValue.ToString(), out output))
        {
            MessageBox.Show("Please enter a numeric value.");
            e.Cancel = true;
        }

        if (string.IsNullOrEmpty(e.FormattedValue.ToString()))
        {
            MessageBox.Show("Cell cannot be left blank.");
            e.Cancel = true;
        }
    }
1
Can't you just make this column ReadOnly?jHilscher
The CellValidating check still validates on it even thought the cell is Read Only: dgvDeliveryCosts.Columns[0].ReadOnly = true;Jack Orr

1 Answers

0
votes

Add a check on the column index:

private void dgvDeliveryCosts_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
{
    if (e.ColumnIndex == 0) // zero-based
    { 
          return;
    }

    // Validate..