2017-10-21 50 views
0

我連接我的應用程序的「百分比」列使用的值小於1(即15%在數據庫中存儲爲0.15),所以我使用Format =「.00%」以顯示DataGrid列中的值。在驗證過程中更改DataGrid單元值

問題是如何正確讓用戶插入大於1的值 - 即在單元格中寫入50或50% - 並將其轉換爲數據庫中的0,5。

我一直在尋找DataGridViewCellValidatingEventHandler並添加事件levDGV_PercentCellValidating,但我不知道如何改變這些值...

private void levDGV_PercentCellValidating(object sender, DataGridViewCellValidatingEventArgs e) 
{ 

    string dataPropertyName = levDGV.Columns[e.ColumnIndex].DataPropertyName; // deliveryProcent 
    // Abort validation if cell is not in the "deliveryProcent" column. 
    if (!dataPropertyName.Equals("deliveryProcent")) return; 
    levDGV.Rows[e.RowIndex].ErrorText = ""; 

    string testValue = e.FormattedValue.ToString(); 
    char lastChar = testValue[testValue.Length - 1]; 
    if (lastChar == (char)37) 
    { 
     //TODO: Remove % character from entered string 
    } 
    //TODO: divide the value by 100 and set as currentCell value 
} 

如何輸入的值轉換到正確驗證一個(除以100 )?

+0

看完這個:https://stackoverflow.com/questions/4742960/datagridview-validation-changing-cell-value我想我會去參加CellParsing ... – mallorn

回答

0

離開他人的解決方案,解析這似乎爲我工作:

private void levDGV_CellParsing(object sender, DataGridViewCellParsingEventArgs e) 
     { 
      string dataPropertyName = levDGV.Columns[e.ColumnIndex].DataPropertyName; 
      if (dataPropertyName.Equals("deliveryProcent")) 
      { 
       if (e.Value != null) 
       { 
        try 
        { 
         string testValueStr = e.Value.ToString(); 
         char lastChar = testValueStr[testValueStr.Length - 1]; 
         if (lastChar == (char)37) 
         { 
          //Remove % character from entered string 
          testValueStr = testValueStr.Substring(0, testValueStr.Length - 1); 
         } 
         //divide the value by 100 and set as currentCell value 
         double testValue = (Convert.ToDouble(testValueStr))/100; 
         e.Value = testValue; 
         e.ParsingApplied = true; 
        } 
        catch (FormatException) 
        { 
         // Set to false in case another CellParsing handler 
         // wants to try to parse this DataGridViewCellParsingEventArgs instance. 
         e.ParsingApplied = false; 
        } 
       } 

      } 
     } 
相關問題