Mohammad Qasim
Mohammad Qasim

Reputation: 105

Trying to insert data into a table of a database through c#/asp.net

This code, upon the sql commands succession should take me to a page and upon failure would show me the error page. Whenever i insert the values through the form it takes me to the error page. Somehow my items are not being inserted. Help would be appreciated

public partial class StudentManage : System.Web.UI.Page
{
    protected void Add_Click(object sender, EventArgs e)
    {
         SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Database"].ConnectionString);
         con.Open();

         // here added "@" to write continuous strind in new line
         SqlCommand cmd = new SqlCommand(@"INSERT INTO ManageStudents(StudentName, StudentEmail, StudentAddress, StudentCity) VALUES(@name, @email, @address, @city)",con);
         cmd.Parameters.AddWithValue("@name", txtStudentName.Text);
         cmd.Parameters.AddWithValue("@email", txtStudentEmail.Text);
         cmd.Parameters.AddWithValue("@address", txtStudentAddress.Text);
         cmd.Parameters.AddWithValue("@city", txtStudentCity.Text);

         SqlDataAdapter da1 = new SqlDataAdapter(cmd);
         DataTable dt2 = new DataTable();
         da1.Fill(dt2);

         if (dt2.Rows.Count > 0)
         {
            Response.Write("Table Updated");
            Response.Redirect("StudentManage.aspx");
         }
         else
         {
            Response.Redirect("Error.aspx");
            //ClientScript.RegisterStartupScript(Page.GetType(), "validation", "<script language='javascript'>alert('Invalid Username and Password')</script>");
         }
    }
}

Upvotes: 0

Views: 126

Answers (2)

freedeveloper
freedeveloper

Reputation: 4082

I suppose that it is a test project, because your code has three major problem,

  • You should create a using or try finally to close the connection
  • put the data with call to the UI in the same layer it is not a good practice.
  • Last Fill only make a select, does not update the table. Use command.ExecuteNotQuery instead

I hope that this help you

Upvotes: 0

Ryan
Ryan

Reputation: 4313

To execute INSERT, UPDATE, or DELETE statements you need to use the ExecuteNonQuery() method instead of a DataTable.

var result = cmd.ExeuteNonQuery();
if(result > 0)
{
    Response.Write("Table Updated");
    Response.Redirect("StudentManage.aspx");
}
// ...

Upvotes: 3

Related Questions