2017-02-20 66 views
0

我有問題做數學運算在datagridview像女士Excel,更具體的是我想減去行[2]和行[3]列關閉,結果我將保存在列向上。如何使用c#在datagridview中進行數學運算?

//假設該表的指數從1號

This is data image

開始我會告訴我的代碼

 private void button3_Click(object sender, EventArgs e) 
     { 
      conn = new SqlConnection("Server=TSANAARSYANI;Data Source= TSANAARSYANI; Database = dbSaham;Integrated Security = SSPI"); 
      conn.Open(); 
      ds = new DataSet(); 
      da = new SqlDataAdapter("Select * From hargaRSI", conn); 
      da.Fill(ds,"hargaRSI"); 
      dataGridView2.ReadOnly = true; 
      dataGridView2.AllowUserToAddRows = false; 
      dataGridView2.AllowUserToDeleteRows = false; 
      dataGridView2.SelectionMode = DataGridViewSelectionMode.FullRowSelect; 
      dataGridView2.DataSource = ds.Tables["hargaRSI"]; 
      object value1 = dataGridView2[2, 2].Value; 
      object value2 = dataGridView2[3, 2].Value; 
      float val1, val2; 
      if(float.TryParse(value1.ToString(),out val1)&&float.TryParse(value2.ToString(),out val2)) 
      { 
       dataGridView2[3, 2].Value = val2 - val1; 
      } 
      else 
      { 
       MessageBox.Show("cannot substract, invalid inputs."); 
      } 
      dataGridView2.Visible = true; 
     } 

注:我使用SQL Server,然後檢索datagridview的數據不dataTable

+0

什麼你想減去值,你想從接近柱減去日期列或日期列密切列,也是爲什麼你要那麼做網格內的計算,爲什麼不執行這些你的數據表中的計算並將它們與網格綁定? –

+0

請查看[how-to-ask](http://stackoverflow.com/help/how-to-ask)。請不要鏈接到數據,在這裏發佈。 – swe

+0

我想在列[2]和列[1]列之間減去(例如:900.00-900.00),然後結果我列入 – phoenix95

回答

0

只是循環遍歷行。那麼你可以做你想做的數學運算。檢查:

private void setResultOnDataGridView() 
{ 
    //dont calculate anything if source is null 
    if (dataGridView1.DataSource == null) return; 

    //get row numbers count 
    var rowLen = dataGridView1.Rows.Count; 

    //loop through rows of your GridView 
    foreach (DataGridViewRow dr in dataGridView1.Rows) 
    { 
     //at last row. done 
     if (dr.Index + 1 == rowLen) break; 

     //get next row. 
     var nextRow = dataGridView1.Rows[dr.Index + 1]; 

     string col1 = dr.Cells["Close"].Value.ToString(); 
     string col2 = nextRow.Cells["Close"].Value.ToString(); 

     float val1=0, val2=0; 
     if (float.TryParse(col1, out val1) && float.TryParse(col2, out val2)) 
     { 
      dr.Cells["Up"].Value = val2 - val1; 
     } 
    } 

} 
+0

它確實有效,非常感謝您的幫助! – phoenix95

0

試試這個

float value1=float.parse(dataGridView2.row[2].cells[3].value.toString()); 
float value2=float.parse(dataGridView2.row[3].cells[2].value.toString()); 
float sub=value2-value1; 
(dataGridView2.row[3].cells[2].value=sub.toString(); 
+0

謝謝你的建議,我已經嘗試過了,它不能很好地工作,有一個錯誤消息說,我不能轉換細胞[3]串起來。 – phoenix95

+0

可能是單元格索引或行索引錯誤。 –

相關問題