2014-03-03 61 views
0

我有一個表有3行,我試圖插入數據到前兩行使用數據表,但它是這樣插入數據,而不是插入前兩行它是插入在其它行無法使用數據表在表中插入數據

    price qty total 
       -------------------- 
        5  10 - 

        5  12 - 

        -  - 50 

        -  - 60 

,但我想

    price qty total 
       -------------------- 
        5  10 50 

        5  12 60 

我已經用於從表中選擇的數據比將數據插入表下面的代碼,它是正確地表示的數據,但在錯誤的行

只是插入
int sp; 
public DataTable bind1() 
{ 
    SqlConnection con = new SqlConnection("cnnection"); 
    con.Open(); 
    SqlCommand cmd; 
    cmd = new SqlCommand("select * from [order]", con);  
    DataTable dt = new DataTable(); 
    SqlDataAdapter da = new SqlDataAdapter(cmd); 
    da.Fill(dt); 
    con.Close(); 
    return dt; 
} 
public DataTable bind2() 
{ 
    SqlConnection con = new SqlConnection("cnnection"); 
    con.Open(); 
    SqlCommand cmd; 
    cmd = new SqlCommand("insert into [order](total) values(@total)", con); 
    cmd.Parameters.AddWithValue("@total", sp); 
    DataTable dt = new DataTable(); 
    SqlDataAdapter da = new SqlDataAdapter(cmd); 
    da.Fill(dt); 
    con.Close(); 
    return dt; 
}  
public void gbind() 
    { 
     DataTable dt = new DataTable(); 
     dt = bind1(); 
     DataTable dt1 = new DataTable(); 
     DataColumn dc = new DataColumn("total"); 
     dt1.Columns.Add(dc);   
     foreach(DataRow drow in dt.Rows) 
      { 
      int s1 = Convert.ToInt16(drow["price"]); 
      int s2 = Convert.ToInt16(drow["qty"]); 
      int s3 = s1 * s2; 
      DataRow dr = dt1.NewRow(); 
      dr["total"] = s3; 
      dt1.Rows.Add(dr); 
      }   
     foreach (DataRow row in dt1.Rows) 
      { 
      string s1 = row["total"].ToString(); 
      for (int i = 0; i < dt.Rows.Count; i++) 
       { 
       sp = Convert.ToInt16(s1); 
       dt = bind2(); 
       } 
      } 

我已經試過這樣也但還是同樣的問題

public void gbind() 
    { 
     DataTable dt = new DataTable(); 
     dt = bind1();  
     foreach (DataRow drow in dt.Rows) 
     { 
      int s1 = Convert.ToInt16(drow["price"]); 
      int s2 = Convert.ToInt16(drow["qty"]); 
      int s3 = s1 * s2;      
      drow["total"] = s3; 
      sp = s3; 
      dt = bind2();    
     } 
    } 
+0

什麼是你在執行INSERT之前在你的表中有三行? –

+0

我認爲你需要使用更新,而不是插入 – Angelo

回答

0

在gbind方法的foreach循環,我不認爲你應該添加一個新行「總」,它會需要成爲一個專欄。而dt1.Rows.Add(dr)應該是dt1.Columns.Add(dr)。嘗試重寫您的代碼來添加一列。讓我知道這是否有幫助。

+0

它的另一個datatable dt1,我在其列中添加行,並試圖插入行數據datatable dt – vikas

0

在您的代碼中註釋這兩行。刪除代碼以添加額外的行。你只需要更新列值。

foreach(DataRow drow in dt.Rows) 
      { 
      int s1 = Convert.ToInt16(drow["price"]); 
      int s2 = Convert.ToInt16(drow["qty"]); 
      int s3 = s1 * s2; 
      //DataRow dr = dt1.NewRow(); 
      dr["total"] = s3; 
      //dt1.Rows.Add(dr); 
      }   
+0

仍然沒有什麼,我在另一列添加行datatable dt1需要在datatable dt中複製其行 – vikas

相關問題