I am using C# to create a Windows form application. How do I create a local database table to save the data described below? Currently my data table consists of the columns of \
I am assuming you are saving the data to an SQL database. Your invoice and item tables share a many to many relationship, so you should use a third table to link them together.
The InvoiceItem table has foreign keys to the other two. This way you keep your invoice and item data separate and clean; there's no mucking about with 10 different "pen" items because 10 different orders included a pen.
Note that you can calculate Invoice.subtotal by selecting all the items from that invoice and calculating the sum of quantity * price. I recommend including it on the Invoice table for convenience's sake.
To get the order into the database, you want something like this:
private void StoreData()
{
int invoiceID;
using(var con = new SqlConnection( @"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\oo\Documents\Data.mdf;Integrated Security=True;Connect Timeout=30"))
{
con.Open();
using(var cmd = con.CreateCommand())
{
cmd.CommandText = @"insert into Invoice(subtotal,tax,total) values (@subtotal,@tax,@total); select SCOPE_IDENTITY() as InvoiceID;";
cmd.Parameters.AddWithValue("@subtotal",subtotal);
cmd.Parameters.AddWithValue("@tax",tax);
cmd.Parameters.AddWithValue("@total",total);
using(var reader = cmd.ExecuteReader())
{
if(reader.Read())
invoiceID = cmd.GetInt32("InvoiceID");
}
}
foreach(var item in orderItems)
{
using(var cmd = con.CreateCommand())
{
cmd.CommandText = @"insert into InvoiceItem(InvoiceID,ItemID,quantity) values (@InvoiceID,@ItemID,@quantity);";
cmd.Parameters.AddWithValue("@InvoiceID",invoiceID);
cmd.Parameters.AddWithValue("@ItemID",item.ItemID);
cmd.Parameters.AddWithValue("@quantity",item.Quantity);
cmd.ExecuteNonQuery();
}
}
}
}
Please understand this is a rudimentary, bare-bones idea of what you need to do. I've also written it without actually checking it in an IDE, so there might be a mistake or two. Importantly, it's not compatible with your existing code. Here's what you need to do to work this in:
orderItems
. Each item in this collection should be some kind of object that represents a line in your ListBox. Note that your OrderItems struct is not sufficient to represent a single item (can you tell why?). Right now you're passing things around as strings of data. You need to be working with genuine objects to get a handle on the power of OOP.using
blocks ensure a limited lifetime and that the object gets closed and disposed of properly. If you're using this object elsewhere (e.g. to get a list of items to show your user), then you need to modify that code to use this pattern.There are a lot of improvements that can be made, both to the code I've posted and to what you have already. This is meant only to be enough for basic functionality. Here are things that I leave to you as an exercise, but which you should do: