Writing form data to SQL DB with C#

In having to convert my current VB projects into C#, I ran into an issue trying to write to a DB from a form.  This blog opened my eyes to how this is accomplished and here is the code I used to get the unsubscribe feature to work.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;

namespace Taleo_UnsubscribeJPN
{
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
DateTime tstamp = DateTime.Now;
String email = Request.QueryString["email"];
String atsid = Request.QueryString["atsid"];
lblEmail.Text = email;

}

protected void btnRemove_Click(object sender, EventArgs e)
{
String strBrowserInfo = (Server.HtmlEncode(Request.UserAgent));
String strIPAddress = (Server.HtmlEncode(Request.UserHostAddress));
String atsid = Request.QueryString["atsid"];
string connection_string = "Data Source=DB_Server;Initial Catalog=TaleoData;Persist Security Info=True;User ID=tdowner;Password=password";
string query = "insert into OptOutEmail (email, tstamp, processed, atsid, remote_addr, http_user_agent) values ('" + lblEmail.Text + "', '" + DateTime.Now + "', " + 0 + ", '" + atsid + "', '" + strIPAddress + "', '" + strBrowserInfo + "')";
SqlConnection connection1 = new SqlConnection(connection_string);

SqlCommand insertCommand = new SqlCommand(query, connection1);

connection1.Open();

insertCommand.ExecuteNonQuery();

connection1.Close();

Server.Transfer("Confirmation.aspx?email=" + lblEmail.Text);

}
}
}

Comments are closed.