2016-09-02 4 views
0

数量と価格の値の乗算を実行するときに、グリッド列の値をチェックします。私はこれをして、それは完全に動作します!Datagridview乗算2列とチェック値

しかし、数量列に文字列値を入力するときや、列を編集して空のままにしておくと問題が発生します。私はエラーを取得しています:

enter image description here

は、どのように私はフィードバックをMessageBoxを示し、値を確認し、ときに、ユーザーのタイプの文字列、文字や空白の入力ができますか?

private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e) 
     { 
      int price, quantity, total;   

      quantity= int.Parse(dataGridView1.Rows[e.RowIndex].Cells["Quantity"].Value.ToString()); 
      cena = int.Parse(dataGridView1.Rows[e.RowIndex].Cells["Price"].Value.ToString()); 
      total = quantity * price ; 

      dataGridView1.Rows[e.RowIndex].Cells["Total"].Value = total; 
     } 

私は整数すべてがOK働く入力

...

+2

を読むことができます

 void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e){ int price, quantity, total; try { quantity= int.Parse(dataGridView1.Rows[e.RowIndex].Cells["Quantity"].Value.ToString()); cena = int.Parse(dataGridView1.Rows[e.RowIndex].Cells["Price"].Value.ToString()); total = quantity * price ; dataGridView1.Rows[e.RowIndex].Cells["Total"].Value = total; } catch(NullReferenceException) { ... } } 

のtry ... catchブロックのコードを使用しますあなたができるデータテーブルで自動的に合計を乗算する式の列。そうでない場合、これは欺瞞です – Plutonix

+1

[NullReferenceExceptionとは何か、それを修正するにはどうすればいいですか?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do- i-fix-it) – Plutonix

+0

私はその例外が何であるか知っています。どのタイプの値がセルに入力されているかをチェックする方法が必要です – Ivan

答えて

0

はこれを試してみてください、そして入力がintに変換することができない場合は、いくつかの値を割り当てます。

は、ここに私のコードです。

private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e) 
      { 
       int price, quantity, total;   

    if(dataGridView1.Rows[e.RowIndex].Cells["Quantity"].Value != null) 
    { 
     if(!int.TryParse(dataGridView1.Rows[e.RowIndex].Cells["Quantity"].Value.ToString(), out quantity)) 
      { 
       quantity= 0; 
      } 
    }else 
    { 
     quantity= 0; 
    }  
          price = int.Parse(dataGridView1.Rows[e.RowIndex].Cells["Price"].Value.ToString()); 

        total = quantity * price ; 

        dataGridView1.Rows[e.RowIndex].Cells["Total"].Value = total; 
       } 
+0

これは両方の場合にいくつかのエラーを返します文字列とブランコセル – Ivan

+0

値を空白のまままたは何か文字列値を入力するとエラー? – Vijai

+0

文字列を入力するとエラーが発生します。編集モードのセルに入力して空のままにするとエラーが発生する – Ivan

0

あなたは

int? price, quantity, total; 

をNULL可能タイプを行うと、あなたのデータであった場合、ここで

https://msdn.microsoft.com/en-us/library/b3h1hf19(v=vs.110).aspx

+0

colが空ではあるが、 'char'や' string'を入力するときにsloveでないときの問題です。私がcharまたはstringを入力すると、 'mscorlib.dllでSystem.FormatException '型の未処理の例外が発生しました'追加情報:入力文字列が正しい形式ではありません。' – Ivan

+0

System.FormatExceptionはコードが文字列を整数に変換する、Int32.Parse(...) – Jack1987