Jonald Samilo Jonald Samilo - 5 months ago 14
C# Question

Add only Data in Textbox that is not empty

I'm creating an Inventory System which the user can add multiple

Products, Itemcode, Quantity.
I have
10 textbox
per columns. The user can input 10 items then save all together. But my problem is that when you leave the other textbox empty it will add also the empty value of that textbox. My question is how can I filter the textboxes that are not empty so that those will only be save on my database. Here's what I got now:

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;

I'm new on Programming so please be kind. Thank you guys.


I tried to use while statement after the
foreach statement
but it seems that it still not working

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


I replace the above code to this code and works

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


you should check if the data is empty or not, before inserting it into the db:
enter an if clause into your foreach loop that looks something like this

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

With this you exclude the empty values from inserting.