title: Details View Insert/update data through Coding
body: <p>I'm trying to insert or update data into a database from detailsview through coding. Without giving a datasource to details view, because it is very easy. I want to do it programmatically.</p>
  
  <p>As I said I didn't give the datasource directly. I did it on page load. </p>
  
  <pre><code>static string conn = ConfigurationManager.ConnectionStrings["AptechConnectionString"].ConnectionString;
  SqlConnection con = new SqlConnection(conn);
  
  protected void Page_Load(object sender, EventArgs e)
  {
      DetailsView1.AutoGenerateInsertButton = true;
      DetailsView1.AutoGenerateEditButton = true;
      DetailsView1.AutoGenerateDeleteButton = true;
      Data_Bind();
  }
  
  public void Data_Bind()
  {
      string query = "select * from students";
      SqlCommand cmd = new SqlCommand(query, con);
      SqlDataAdapter da = new SqlDataAdapter(cmd);
      DataTable dt = new DataTable();
      da.Fill(dt);
  
      DetailsView1.DataSource = dt;
      DetailsView1.DataBind();
      ViewState["Data"] = dt;
  }
  </code></pre>
  
  <p>I tried to do like we did in gridview</p>
  
  <pre><code>protected void DetailsView1_ItemInserting(object sender, DetailsViewInsertEventArgs e)
  {
      try
      {
          id = (TextBox)DetailsView1.Rows[0].Cells[1].FindControl("TextBox1");
          name = (TextBox)DetailsView1.Rows[0].Cells[1].FindControl("TextBox2");
          batch = (TextBox)DetailsView1.Rows[0].Cells[1].FindControl("TextBox3");
          enrolled = (TextBox)DetailsView1.Rows[0].Cells[1].FindControl("TextBox4");
          teacher = (TextBox)DetailsView1.Rows[0].Cells[1].FindControl("TextBox5");
      }
      catch (Exception ex)
      {
          Label1.Text = ex.Message;
          Label1.Visible = true;
      }
  }
  
  protected void DetailsView1_ItemCommand(object sender, DetailsViewCommandEventArgs e)
  {
      switch (e.CommandName.ToString())
      {
          case "New":
              DetailsView1.ChangeMode(DetailsViewMode.Insert);
              Data_Bind();
              break;
      }
  }
  </code></pre>
  
  <p>But, when I click Edit or insert link button it gives me this error</p>
  
  <blockquote>
    <p>The DetailsView 'DetailsView1' fired event ModeChanging which wasn't handled."</p>
  </blockquote>
  
  <p>What I'm missing?</p>