2016-08-18 4 views
1

ユーザーが複数を追加できる在庫システムを作成していますProducts, Itemcode, Quantity.私は10 textboxを1列に持っています。ユーザーは10個の項目を入力し、すべて一緒に保存することができます。しかし、私の問題は、他のテキストボックスを空のままにすると、そのテキストボックスの空の値も追加されるということです。私の質問は、空ではないテキストボックスをどのようにフィルタリングして、それらがデータベースにのみ保存されるようにすることです。ここに私が今持っているものは次のとおりです:空ではないテキストボックスにデータのみを追加します

var rows = new[] 
    { 
    new {Item = txtItem.Text, Product = txtProduct.Text, Quantity = txtQuantity.Text}, 
    new {Item = txtItem2.Text, Product = txtProduct2.Text, Quantity = txtQuantity2.Text}, 
    new {Item = txtItem3.Text, Product = txtProduct3.Text, Quantity = txtQuantity3.Text}, 
    new {Item = txtItem4.Text, Product = txtProduct4.Text, Quantity = txtQuantity4.Text}, 
    new {Item = txtItem5.Text, Product = txtProduct5.Text, Quantity = txtQuantity5.Text}, 
    new {Item = txtItem6.Text, Product = txtProduct6.Text, Quantity = txtQuantity6.Text}, 
    new {Item = txtItem7.Text, Product = txtProduct7.Text, Quantity = txtQuantity7.Text}, 
    new {Item = txtItem8.Text, Product = txtProduct8.Text, Quantity = txtQuantity8.Text}, 
    new {Item = txtItem9.Text, Product = txtProduct9.Text, Quantity = txtQuantity9.Text}, 
    new {Item = txtItem10.Text, Product = txtProduct10.Text, Quantity = txtQuantity10.Text} 
    }; 
    foreach (var row in rows) 
       { 
    OleDbCommand cmdInsert = new OleDbCommand(
     @"insert into TblInventory (ItemCode,ProductName,Quantity,DateAndTime) values (@ItemCode,@ProductName,@Quantity,@DateAndTime)"); 
     cmdInsert.Parameters.AddWithValue("ItemCode", row.Item); 
     cmdInsert.Parameters.AddWithValue("ProductName", row.Product); 
     cmdInsert.Parameters.AddWithValue("Quantity", row.Quantity.ToString()); 

     cmdInsert.Connection = con; 
     cmdInsert.ExecuteNonQuery(); 

私はプログラミングの初心者です。君たちありがとう。

EDIT

私はforeach statement後while文を使用しようとしたが、私がこのコードに上記のコードを置き換え、それはまだ

while(row.Item != null && row.Product != null && row.Quantity != null) 

ANSWER

を動作していないようです作品は

if (!String.IsNullOrEmpty(row.Item) && !String.IsNullOrEmpty(row.Product) && !String.IsNullOrEmpty(row.Quantity)) 
+1

あなたのforeachループでString.IsNullOrEmpty()のItem、Product、およびQuantityをチェックし、この行を挿入しないようにすることをお勧めします。 –

+0

上記の@MarcelTheis –

+0

の編集を参照してください。文字列がある場合は、nullをチェックするだけではすべてが取得されません。 IsNullOrEmpty()をチェックする必要があります。これは文字列クラスによって提供され、しばらく使用しないでください。if文を使用します。 –

答えて

1


データをDBに挿入する前に、空であるかどうかをチェックする必要があります
この

if (!String.IsNullOrEmpty(row.Item.Trim() &&  
!String.IsNullOrEmpty(row.Product.Trim()) && 
!String.IsNullOrEmpty(row.Quantity.ToString().Trim())) 
{ 
    // insert into db 
} 


でのようになりますあなたのforeachループにif節を入力します。これは空の値を挿入から除外します。

+0

ありがとう:) –

関連する問題