简体   繁体   中英

DataGridView TextBox Cell Validating in C#?

I have two DataGridViewTextbox Column in my Form. I want to compare one textbox with another textbox value.

See the image the information is provided there...,

which are in blue color they are readonly ......I tried and i get the answer

try this

if (DataGridView.Rows[0].Cells["Quantity"].Value > DataGridView.Rows[0].Cells["other"].Value)
{
//do something
}

Attach your grid to CellValidating event:

private void GridCellValidating(object sender, DataGridViewCellValidatingEventArgs e)
{
    if (e.ColumnIndex == ColQuantityIssues.Index)  // Quantity Issues TextBox value has changed
    {
        int quantityIssued = 0;

        if (!Int32.TryParse(e.FormattedValue.ToString(), out quantityRequired))  //value is not a valid number
        {
            e.Cancel = true;
        }

        int quantityRequired = Int32.Parse(dgv.Rows[e.RowIndex].Cells[ColQuantityRequired.Index].Value.ToString());

        if (quantityRequired < quantityIssued)
        {
            e.Cancel = true;
        }
    }
}

Event args has FormattedValue which is the new value user has entered. Setting e.Cancel to true won't allow user to leave current cell as long as value is not valid one.

You may change my ColQuantityIssues and ColQuantityRequired to access them by name (ie dgv.Rows[e.RowIndex].Cells["Required"]) but that should work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM