Here’s the code to insert a record into your table using ASP.NET and C# in your aspx.cs
file. This assumes you have input fields in your .aspx
page with IDs txtUsername
, txtEmail
, txtPhone
, txtArea
, txtCity
, txtCountry
, txtPostalCode
, and txtFullName
.
Code in YourPage.aspx.cs
using System;
using System.Data.SqlClient;
using System.Configuration;
public partial class YourPage : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
// Code for any Page_Load events
}
protected void btnSave_Click(object sender, EventArgs e)
{
// Fetch the connection string from Web.config
string connectionString = ConfigurationManager.ConnectionStrings["doctopsdbConnectionString"].ConnectionString;
// Insert SQL query
string query = "INSERT INTO user_master (username, email, phone, area, city, country, postalcode, fullname) " +
"VALUES (@Username, @Email, @Phone, @Area, @City, @Country, @PostalCode, @FullName)";
// Using block to ensure proper disposal of resources
using (SqlConnection conn = new SqlConnection(connectionString))
{
using (SqlCommand cmd = new SqlCommand(query, conn))
{
// Define parameters and assign values from text boxes
cmd.Parameters.AddWithValue("@Username", txtUsername.Text);
cmd.Parameters.AddWithValue("@Email", txtEmail.Text);
cmd.Parameters.AddWithValue("@Phone", txtPhone.Text);
cmd.Parameters.AddWithValue("@Area", txtArea.Text);
cmd.Parameters.AddWithValue("@City", txtCity.Text);
cmd.Parameters.AddWithValue("@Country", txtCountry.Text);
cmd.Parameters.AddWithValue("@PostalCode", txtPostalCode.Text);
cmd.Parameters.AddWithValue("@FullName", txtFullName.Text);
try
{
// Open the connection
conn.Open();
// Execute the command
int rowsAffected = cmd.ExecuteNonQuery();
if (rowsAffected > 0)
{
// Record was successfully inserted
lblMessage.Text = "Record inserted successfully!";
}
else
{
lblMessage.Text = "No record inserted.";
}
}
catch (Exception ex)
{
// Display error message
lblMessage.Text = "Error: " + ex.Message;
}
}
}
}
}
Explanation:
- Connection String: Retrieves the connection string from
Web.config
. - SQL Command: Uses a parameterized SQL query to prevent SQL injection.
- Parameters: Parameters like
@Username
,@Email
, etc., match the column names in the database. - Exception Handling: Catches any exceptions and displays the error message in
lblMessage
.
Notes:
- Ensure that the button triggering the
btnSave_Click
event is defined in your.aspx
file. lblMessage
is aLabel
control used to display success or error messages. Make sure to add it to the.aspx
page.