Home > Blockchain >  How to only add in database the textbox that has value
How to only add in database the textbox that has value

Time:05-23

This is my code when adding value in my database but my problem is the , is showing and I only want to add the value of the textbox that has value

SqlConnection con = new SqlConnection(@"Data Source = MAAAYYK; Initial Catalog = dbFoodReservation; Integrated Security = True");

SqlCommand cm = new SqlCommand();
cm = new SqlCommand("Insert into tbl_Reservation(Food)Values(@Food)", con);
cm.Parameters.AddWithValue("@Food", txtboxfood1.Text   ","   txtboxfood2.Text   ","   txtboxfood3.Text   ","   txtboxfood4.Text);

CodePudding user response:

There are couple of ways of doing this, you can try string.Join:

var foodValues = new List<string>()
{
    txtboxfood1.Text, txtboxfood2.Text, txtboxfood3.Text , txtboxfood4.Text
}

var foodText = string.Join(",", foodValues.Where(s => !string.IsNullOrEmpty(s)));

...
cm.Parameters.AddWithValue("@Food", foodText);
  •  Tags:  
  • c#
  • Related