Pages

Monday, February 20, 2012

GridView Update All Rows At Once in asp.net

private void Update()
{
StringBuilder sb = new StringBuilder();
// build the query
foreach (GridViewRow row in GridView1.Rows)
{
sb.Append("UPDATE Users SET FirstName = '");
sb.Append((row.FindControl("txtFirstName") as TextBox).Text);
sb.Append("',");
sb.Append("LastName = '");
sb.Append((row.FindControl("txtLastName") as TextBox).Text);
sb.Append("', ");
sb.Append("ClassCode = '");
sb.Append((row.FindControl("txtClassCode") as TextBox).Text);
sb.Append("'");
sb.Append(" WHERE UserID = ");
sb.Append(Convert.ToInt32((row.FindControl("lblUserID") as Label).Text));
sb.Append(" ");
}
string connectionString =
"Server=HCUBE008;Database=School;Trusted_Connection=true";
SqlConnection myConnection = new SqlConnection(connectionString);
SqlCommand myCommand = new SqlCommand(sb.ToString(), myConnection);
myConnection.Open();
myCommand.ExecuteNonQuery();
myConnection.Close();
}

No comments:

Post a Comment