2014-07-17 64 views
0

我有一個包含3個文本框的面板,在每個文本框中用戶可以輸入一個年齡段。一切似乎正常工作,除了它停止的部分,如果用戶在兩個或更多文本域中輸入數字(循環正在工作,它只是不會將下一個文本域值插入到數據庫中)這是場景:C#插入多個TextField值到SQL Server

Depdent 1 Age: 10 
Depdent 1 Age: 12 
Depdent 1 Age: 14 

我想插入我的表是以下

ID  age 
1  10 
2  12 
3  14 

,當我點擊提交,它只是插入那麼先將記錄拋出一個錯誤,我知道錯誤是試圖插入兩個文本框的原因值到數據庫中的單元格,但我不知道如何解決它,我的表有一個ID字段,這是一個主鍵和自動增量。任何建議表示讚賞。謝謝。

這裏是我的代碼:

const string query = "INSERT INTO deductible (age) VALUES (@age)"; 
using (var command = new SqlCommand(query, conn)) 
{ 
foreach (TextBox tb in Panel1.Controls.OfType<TextBox>()) 
{ 
    if (tb.Text != "0") 
    { 
     command.Parameters.AddWithValue("@age", tb.Text); 
     command.ExecuteNonQuery(); 
    } 
} 

回答

2

使用SqlParameterCollection.Clear執行查詢之後方法:

if (tb.Text != "0") 
{ 
    command.Parameters.AddWithValue("@age", tb.Text); 
    command.ExecuteNonQuery(); 
    command.Parameters.Clear(); 
} 
+0

我需要的,謝謝主席先生。 – user3345212