简体   繁体   中英

How to retain original value on cell edit of datagridview column?

I am having a grid which shows list of products with following columns :

ProductId,ProductName,MRP,FinalAmount

Now I have kept MRP as editable so that user can change it based on discount on some products.I have kept validation on MRP column to not allow user to enter null value but the problem is when I raised the validation message original MRP value is LOST .

So what I am trying to do is when user enter negative/null value then I want to show message and retain last MRP value.

Code :

private void grdProductList_CellEndEdit_1(object sender, DataGridViewCellEventArgs e)
        {
                if (grdProductList.CurrentCell == null ||
                            grdProductList.CurrentCell.Value == null ||
                            e.RowIndex == -1) return;

                if (grdProductList.CurrentCell.ColumnIndex.Equals(3))//MRP
                {
                    if(string.IsNullOrEmpty(grdProductList.Rows[grdProductList.CurrentRow.Index].Cells["MRP"].Value.ToString()))
                    {
                        MessageBox.Show("MRP cannot be empty.Please provide value", "Error");
                        return;
                    }

                    decimal.TryParse(grdProductList.Rows[grdProductList.CurrentRow.Index].Cells["MRP"].Value.ToString(), out decimal mrp);
                    if(mrp < 0)
                    {
                        MessageBox.Show("MRP cannot have negative value", "Error");
                        return;
                    }
                    grdProductList.Rows[grdProductList.CurrentRow.Index].Cells["FinalAmount"].Value = mrp;
                    //calculation code based on mrp
                }
       }

I have found that DataGridView provides a method called CancelEdit which discards the changes and also helps to retain original value.

I just need to call this method like below and got the expected behaviour :

if(string.IsNullOrEmpty(grdProductList.Rows[grdProductList.CurrentRow.Index].Cells["MRP"].Value.ToString()))
                    {
                        MessageBox.Show("MRP cannot be empty.Please provide value", "Error");
                        grdProductList.CancelEdit();
                        return;
                }

MRP原始值存储在临时变量中,如果用户输入空值或负值,则将临时值恢复到当前网格单元格中

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