!! NO NO NO !
NEVER EVER
build an SQL command by cobbling a bunch of user input into a string- it is the reason why SQL Injection is still in the Top 10 application vulnerabilities 2 decades after it was identified.
The proper way to create commands and place values into them is going to be through
Parameters
Update: Little busy so I didn't get the time I wanted for this... This will be a guideline and may have some syntax errors..
Part 1 is going to build up an Address class to define what an address is along with methods to create and save the list
1a. Create an
Address class that parallels the data in your database table
public class Addressee {
string FormCode { get; set; }
int Version { get; set; }
string AddresseeCode { get; set; }
string Main { get; set; }
DateTime Created { get; set; }
string CreatedBy { get; set; }
public Addressee() { }
}
1b. Add an overloaded construct for easy population
public Addressee(string formCode, int version, string addresseecode, string main, DateTime created, string createdBy) {
FormCode = formCode;
Version = version;
AddresseeCode = addresseecode;
Created = created;
CreatedBy = createdBy;
}
1c. Add a method to save a address. (I skipped this)
1d. Add a method to save a list of addresses
public void SaveAddressList(List<Addressee> addressees) {
if ((addressees != null) && (addressees.Count > 0)) {
string strSqlConnection = "placeholder";
string Query = "INSERT INTO EFILE.FORM_ADDRESSEE_TO (form_code, version, addressee_code, main, created_dt,created_by) ";
Query += "VALUES (@form_code, @version, @addressee_code, @main, @created_dt, @created_by";
using (SqlConnection conn = new SqlConnection(strSqlConnection)) {
using (SqlCommand cmd = new SqlCommand(Query, conn)) {
conn.Open();
foreach (Addressee a in addressees) {
cmd.Parameters.AddWithValue("@form_code", a.FormCode);
cmd.Parameters.AddWithValue("@addressee_code", a.AddresseeCode);
cmd.Parameters.AddWithValue("@version", a.Version);
cmd.Parameters.AddWithValue("@main", a.Main);
cmd.Parameters.AddWithValue("@created_dt", a.CreatedDt);
cmd.Parameters.AddWithValue("@created_by", a.CreatedBy);
cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
}
conn.Close();
}
}
}
}
The second part is going to be modifications to the form and code behind calling this class
2a. Add a List of addresses to the class
2b. Populate the list in your existing routine
2c. Call the "save" method whenever you get that far.
private List<addressee> AddressList = new List<addressee>();
protected void AddRowToAddressee_Click(object sender, EventArgs e) {
if ((Address == null) ||(AddressList == null)) { Address = new Addressee(); AddressList = new List<addressee>(); }
try {
AddressList.Add(GetAddress());
}
catch (Exception ex) {
Console.WriteLine(ex.Message);
}
}
protected void SaveAddressListRows(object sender, EventArgs e) {
Address.SaveAddressList(AddressList);
}