I'm currently working on a project where I've been asked to work on a WPF with the following requirements:
- Allow the user to be able to add more textboxes in a stack panel
- Save the user input (as string/nvarchar) in each textbox as a new record in the database
The idea behind this is that if we receive multiple packages, each shipment is typically split up into multiple locations and we'd need to located where each component is.
I've included a sample of my code below, its barebones and will probably have more than just the one 'Records' field things will be inserted into. I've set the RecordID field to being an identity field so I'm not worried about declaring the ID field. It's not included in the sample but each record is linked to a ShipmentID.
I'd appreciate any help as I've been having trouble implementing it (and have hit a wall with my research) as my code runs into a:
'System.InvalidOperationException' occurred in System.Data.dll' with the CommandText Property not initialized error, when I try I try to save the record. I've unfortunately found only vague tidbits how to solve my issue (or maybe I'm just terrible at research).
private void StackAddTB(object sender, RoutedEventArgs e)
{
TextBox NewBox = new TextBox() { Margin = new Thickness(0, 10, 0, 0), Width = 100, Height = 20 };
StackBoxes.Children.Add(NewBox);
}
private void SaveMulti(object sender, RoutedEventArgs e)
{
string CStr = Manifesting.Properties.Settings.Default.PSIOpsSurfaceCS;
SqlConnection Connection = new SqlConnection(CStr);
string Query = "INSERT INTO TestLoop (Record), Values (Record)";
SqlCommand Command = new SqlCommand(Query, Connection)
foreach (TextBox TestTB in StackBoxes.Children.OfType<TextBox>())
{
try
{
Connection.Open();
Command = Connection.CreateCommand();
Command.Parameters.AddWithValue("@Record", TestTB.Text );
Command.ExecuteNonQuery();
}
catch (SqlException ex)
{
MessageBox.Show(ex.ToString());
}
finally
{
Connection.Close();
}
}
Edit: I've checked through the Looping Through Textbox question (as per mr. reds comment), and while I've found some things useful from the other post it does not go into detail in how those values are saved in a db.