I tried to insert data into sql server from my website build in vs 2008.For that I used button click event .I tried code shown in youtube but the code doesn't work .It shows error in my website.
The code in .aspx.cs file is
public partial class _Default : System.Web.UI.Page
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
protected void Page_Load(object sender, EventArgs e)
{
conn.Open();
}
protected void btnInsert_Click(object sender, EventArgs e)
{
SqlCommand cmd = new SqlCommand("insert into Insert values('"+txtCity.Text+"','"+txtFName.Text+"','"+txtLName.Text+"')",conn);
cmd.ExecuteNonQuery();
conn.Close();
Label1.Visible =true;
Label1.Text = "Your data inserted successfully";
txtCity.Text = "";
txtFName.Text = "";
txtLName.Text = "";
}
} `
Okay, let's fix this code up just a little. You're getting there:
var cnnString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
var cmd = "insert into Insert values(@City,@FName,@LName)";
using (SqlConnection cnn = new SqlConnection(cnnString))
{
using (SqlCommand cmd = new SqlCommand(cmd, cnn))
{
cmd.Parameters.AddWithValue("@City",txtCity.Text);
cmd.Parameters.AddWithValue("@FName",txtFName.Text);
cmd.Parameters.AddWithValue("@LName",txtLName.Text);
cnn.Open();
cmd.ExecuteNonQuery();
}
}
A couple things to note about the modified code.
using statement to ensure that resources are properly disposed.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With