ASP.NET - Databases - Update Records
Here is an example of updating records in an Access database using C# and ASP.NET:
Assuming you have a table named "Students" with columns "ID", "Name", and "Age" in your Access database:
HTML code for the form:
<!DOCTYPE html>
<html>
<head>
<title>Update Student Record</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<label>Enter ID of student to update:</label>
<input type="text" id="txtID" name="txtID" />
<br />
<label>Enter new name:</label>
<input type="text" id="txtName" name="txtName" />
<br />
<label>Enter new age:</label>
<input type="text" id="txtAge" name="txtAge" />
<br />
<input type="submit" id="btnUpdate" name="btnUpdate" value="Update" />
</div>
</form>
</body>
</html>
C# code for updating record in code-behind file:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
// Set initial form state
txtID.Text = "";
txtName.Text = "";
txtAge.Text = "";
}
}
protected void btnUpdate_Click(object sender, EventArgs e)
{
// Get connection string from web.config file
string connectionString = ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
// Create SQL statement to update record
string sql = "UPDATE Students SET Name = @Name, Age = @Age WHERE ID = @ID";
// Create connection object and open connection
using (OleDbConnection conn = new OleDbConnection(connectionString))
{
conn.Open();
// Create command object and set parameters
using (OleDbCommand cmd = new OleDbCommand(sql, conn))
{
cmd.Parameters.AddWithValue("@Name", txtName.Text);
cmd.Parameters.AddWithValue("@Age", txtAge.Text);
cmd.Parameters.AddWithValue("@ID", txtID.Text);
// Execute command
int rowsAffected = cmd.ExecuteNonQuery();
// Check if update was successful
if (rowsAffected > 0)
{
Response.Write("Record updated successfully.");
}
else
{
Response.Write("Update failed.");
}
}
}
}
Note: Make sure to replace "MyConnectionString" in the C# code with the actual name of the connection string in your web.config file.