title: How to create custom delete and edit button in gridview using asp.net pt.2?
body: <p>Finally i was able to create a custom delete and edit button for my gridview. But I have noticed two problems in my gridview. Lets say i have a gridview shown below:</p>
  
  <p><a href="https://i.stack.imgur.com/cqW6v.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/cqW6v.png" alt="enter image description here"></a> </p>
  
  <p><strong>Problem 1:</strong>
  When I click the delete button for the first time, it just refresh the page and does nothing. But when i click it for the second time, it executes perfectly. Why the delete button is not working and just refreshing page when clicked for the first time and then works at the second time?<br/>
  <strong>Problem 2:</strong>
  When I click the edit button for the first time, it works fine. Then, i can update/change the database. Lets say i want to change the name "Dean" under id "7" to "Jackson". So I just simply changed it in the textbox and clicked the update button. But the website just refresh again and the name "Dean" is still in the textbox(by the way, this is still in update/cancel mode). So I need to type "Jackson" again in the textbox and click the update button for the second time. This time it works and it did update my gridview. Similar to problem 1, why the update button is not working and just refreshing page when clicked for the first time and works at the second time?</p>
  
  <p>Here is the aspx code:</p>
  
  <pre><code>    &lt;h3&gt;Guitar Brands Data:&lt;/h3&gt;
  &lt;div style="overflow:auto; width:1100px; max-height:500px;"&gt;
      &lt;asp:GridView ID="GuitarBrandsGridView" runat="server" CssClass="mydatagrid" PagerStyle-CssClass="pager" HeaderStyle-CssClass="header" RowStyle-CssClass="rows" AllowPaging="True" AllowSorting="True" AutoGenerateColumns="False" DataKeyNames="id" DataSourceID="SqlDataSource0" OnRowDataBound="GuitarBrandsGridView_RowDataBound" OnRowCancelingEdit="GuitarBrandsGridView_RowCancelingEdit" OnRowEditing="GuitarBrandsGridView_RowEditing" OnRowUpdating="GuitarBrandsGridView_RowUpdating"  OnRowDeleting="GuitarBrandsGridView_RowDeleting" Width="864px" Height="250px"&gt;
          &lt;Columns&gt;
              &lt;asp:TemplateField&gt;
                  &lt;ItemTemplate&gt;
                      &lt;asp:Button ID="GuitarBrandsGridViewBtnDelete" runat="server" CommandName="Delete" Text="Delete"/&gt;
                  &lt;/ItemTemplate&gt;
              &lt;/asp:TemplateField&gt;
              &lt;asp:TemplateField&gt;
                  &lt;ItemTemplate&gt;
                      &lt;asp:Button ID="GuitarBrandsGridViewBtnEdit" runat="server" CommandName="Edit" Text="Edit"/&gt;
                  &lt;/ItemTemplate&gt;
                  &lt;EditItemTemplate&gt;
                      &lt;asp:Button ID="GuitarBrandsGridViewBtnUpdate" runat="server" CommandName="Update" Text="Update"/&gt;
                      &lt;asp:Button ID="GuitarBrandsGridViewBtnCancel" runat="server" CommandName="Cancel" Text="Cancel"/&gt;
                  &lt;/EditItemTemplate&gt;
              &lt;/asp:TemplateField&gt;
              &lt;asp:TemplateField HeaderText="id" SortExpression="id"&gt;
                  &lt;EditItemTemplate&gt;
                      &lt;asp:Label ID="Label1" runat="server" Text='&lt;%# Eval("id") %&gt;'&gt;&lt;/asp:Label&gt;
                  &lt;/EditItemTemplate&gt;
                  &lt;ItemTemplate&gt;
                      &lt;asp:Label ID="Label2" runat="server" Text='&lt;%# Bind("id") %&gt;'&gt;&lt;/asp:Label&gt;
                  &lt;/ItemTemplate&gt;
              &lt;/asp:TemplateField&gt;
              &lt;asp:TemplateField HeaderText="type" SortExpression="type"&gt;
                  &lt;EditItemTemplate&gt;
                      &lt;asp:TextBox ID="TextBox1" runat="server" Text='&lt;%# Bind("type") %&gt;'&gt;&lt;/asp:TextBox&gt;
                  &lt;/EditItemTemplate&gt;
                  &lt;ItemTemplate&gt;
                      &lt;asp:Label ID="Label3" runat="server" Text='&lt;%# Bind("type") %&gt;'&gt;&lt;/asp:Label&gt;
                  &lt;/ItemTemplate&gt;
              &lt;/asp:TemplateField&gt;
              &lt;asp:TemplateField HeaderText="name" SortExpression="name"&gt;
                  &lt;EditItemTemplate&gt;
                      &lt;asp:TextBox ID="TextBox2" runat="server" Text='&lt;%# Bind("name") %&gt;'&gt;&lt;/asp:TextBox&gt;
                  &lt;/EditItemTemplate&gt;
                  &lt;ItemTemplate&gt;
                      &lt;asp:Label ID="Label4" runat="server" Text='&lt;%# Bind("name") %&gt;'&gt;&lt;/asp:Label&gt;
                  &lt;/ItemTemplate&gt;
              &lt;/asp:TemplateField&gt;
              &lt;asp:TemplateField HeaderText="image" SortExpression="image"&gt;
                  &lt;EditItemTemplate&gt;
                      &lt;asp:TextBox ID="TextBox3" runat="server" Text='&lt;%# Bind("image") %&gt;'&gt;&lt;/asp:TextBox&gt;
                  &lt;/EditItemTemplate&gt;
                  &lt;ItemTemplate&gt;
                      &lt;asp:Label ID="Label5" runat="server" Text='&lt;%# Bind("image") %&gt;'&gt;&lt;/asp:Label&gt;
                  &lt;/ItemTemplate&gt;
              &lt;/asp:TemplateField&gt;
          &lt;/Columns&gt;
          &lt;HeaderStyle CssClass="header"&gt;&lt;/HeaderStyle&gt;
          &lt;PagerStyle CssClass="pager"&gt;&lt;/PagerStyle&gt;
          &lt;RowStyle CssClass="rows"&gt;&lt;/RowStyle&gt;
      &lt;/asp:GridView&gt;
      &lt;/div&gt;
      &lt;asp:SqlDataSource ID="SqlDataSource0" runat="server" ConnectionString="&lt;%$ ConnectionStrings:brandsConnection %&gt;" DeleteCommand="DELETE FROM [guitarBrands] WHERE [id] = @id" InsertCommand="INSERT INTO [guitarBrands] ([id], [type], [name], [image]) VALUES (@id, @type, @name, @image)" SelectCommand="SELECT [id], [type], [name], [image] FROM [guitarBrands]" UpdateCommand="UPDATE [guitarBrands] SET [type] = @type, [name] = @name, [image] = @image WHERE [id] = @id"&gt;
          &lt;DeleteParameters&gt;
              &lt;asp:Parameter Name="id" Type="Int32" /&gt;
          &lt;/DeleteParameters&gt;
          &lt;InsertParameters&gt;
              &lt;asp:Parameter Name="id" Type="Int32" /&gt;
              &lt;asp:Parameter Name="type" Type="String" /&gt;
              &lt;asp:Parameter Name="name" Type="String" /&gt;
              &lt;asp:Parameter Name="image" Type="String" /&gt;
          &lt;/InsertParameters&gt;
          &lt;UpdateParameters&gt;
              &lt;asp:Parameter Name="type" Type="String" /&gt;
              &lt;asp:Parameter Name="name" Type="String" /&gt;
              &lt;asp:Parameter Name="image" Type="String" /&gt;
              &lt;asp:Parameter Name="id" Type="Int32" /&gt;
          &lt;/UpdateParameters&gt;
      &lt;/asp:SqlDataSource&gt;
      &lt;br/&gt;
  </code></pre>
  
  <p>Here is the aspx.cs code:</p>
  
  <pre><code>protected void Page_Load(object sender, EventArgs e)
  {
      BindGridViewDataList.GetItemsLoad();
  }
  
  //Start of Gridview Code for Guitar Brands
  private void bindgridviewguitarbrands()
  {
      con1.Open();
      cmd1.CommandText = "SELECT * FROM [guitarBrands]";
      cmd1.Connection = con1;
      SqlDataAdapter da1 = new SqlDataAdapter(cmd1);
      da1.Fill(ds1);
      con1.Close();
      GuitarBrandsGridView.DataBind();
  }
  
  protected void GuitarBrandsGridView_RowDataBound(object sender, GridViewRowEventArgs e)
  {
      if (e.Row.RowType == DataControlRowType.DataRow)
      {
          string name = Convert.ToString(DataBinder.Eval(e.Row.DataItem, "Name"));
          Button button = (Button)e.Row.FindControl("GuitarBrandsGridViewBtnDelete");
          button.Attributes.Add("onclick", "JavaScript:return ConfirmationBox('" + name + "' )");
      }
  }
  
  protected void GuitarBrandsGridView_RowDeleting(object sender, GridViewDeleteEventArgs e)
  {
  
      int id = Convert.ToInt32(GuitarBrandsGridView.DataKeys[e.RowIndex].Value.ToString());
      Label name = (Label)GuitarBrandsGridView.Rows[e.RowIndex].FindControl("Label4");
  
      con1.Open();
      cmd1.CommandText = "DELETE FROM [guitarBrands] WHERE id=" + id;
      cmd1.Connection = con1;
      int a = cmd1.ExecuteNonQuery();
      con1.Close();
      if (a &gt; 0)
      {
          bindgridviewguitarbrands();
      }
  
      RemoveCodeToGuitarFile.RemoveAddGuitarClass(name.Text);
      RemoveCodeToGuitarFile.RemoveConnectionClassGuitarItems(name.Text);
      RemoveCodeToGuitarFile.RemoveOverviewGuitarDataASPX(name.Text);
      RemoveCodeToGuitarFile.RemoveOverviewGuitarDataCode(name.Text);
      File.Delete(@"C:\Users\User1\Documents\Visual Studio 2015\WebSites\MusicStore\Pages\GuitarItems" + id + ".aspx");
      File.Delete(@"C:\Users\User1\Documents\Visual Studio 2015\WebSites\MusicStore\Pages\GuitarItems" + id + ".aspx.cs");
      ConnectionClassGuitarBrands.RemoveGuitarBrandsDatabase(name.Text);
  
  }
  
  protected void GuitarBrandsGridView_RowEditing(object sender, GridViewEditEventArgs e)
  {
      string id = GuitarBrandsGridView.DataKeys[e.NewEditIndex].Value.ToString();
      Label name = (Label)GuitarBrandsGridView.Rows[e.NewEditIndex].FindControl("Label4");
  
      RemoveCodeToGuitarFile.RemoveAddGuitarClass(name.Text);
      RemoveCodeToGuitarFile.RemoveConnectionClassGuitarItems(name.Text);
      RemoveCodeToGuitarFile.RemoveOverviewGuitarDataASPX(name.Text);
      RemoveCodeToGuitarFile.RemoveOverviewGuitarDataCode(name.Text);
      File.Delete(@"C:\Users\User1\Documents\Visual Studio 2015\WebSites\MusicStore\Pages\GuitarItems" + id + ".aspx");
      File.Delete(@"C:\Users\User1\Documents\Visual Studio 2015\WebSites\MusicStore\Pages\GuitarItems" + id + ".aspx.cs");
      ConnectionClassGuitarBrands.RemoveGuitarBrandsDatabase(name.Text);
  
      GuitarBrandsGridView.EditIndex = e.NewEditIndex;
      bindgridviewguitarbrands();
  }
  // row update event
  protected void GuitarBrandsGridView_RowUpdating(object sender, GridViewUpdateEventArgs e)
  {
      string id = GuitarBrandsGridView.DataKeys[e.RowIndex].Value.ToString();
      TextBox type = (TextBox)GuitarBrandsGridView.Rows[e.RowIndex].FindControl("TextBox1");
      TextBox name = (TextBox)GuitarBrandsGridView.Rows[e.RowIndex].FindControl("TextBox2");
      TextBox image = (TextBox)GuitarBrandsGridView.Rows[e.RowIndex].FindControl("TextBox3");
  
      cmd1 = new SqlCommand("UPDATE [guitarBrands] SET Type = '" + type + "', Name = '" + name + "', Image = '" + image + "' WHERE ID = " + id, con1);
      con1.Open();
      cmd1.ExecuteNonQuery();
      con1.Close();
  
      int ID = Convert.ToInt32(id);
      ConnectionClassGuitarBrands.CreateGuitarBrandsDatabase(name.Text);
      AddCodeToGuitarFile.AddGuitarClassCode(name.Text, ID);
      AddCodeToGuitarFile.AddConnectionClassGuitarItems(name.Text);
      AddCodeToGuitarFile.AddOverviewGuitarDataASPX(name.Text, ID);
      AddCodeToGuitarFile.AddOverviewGuitarDataASPXCode(name.Text);
      AddASPXAndCSFileForGuitarBrands.AddFile(name.Text, ID);
  
      GuitarBrandsGridView.EditIndex = -1;
      bindgridviewguitarbrands();  
  }
  // cancel row edit event
  protected void GuitarBrandsGridView_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
  {
      string id = GuitarBrandsGridView.DataKeys[e.RowIndex].Value.ToString();
      TextBox name = (TextBox)GuitarBrandsGridView.Rows[e.RowIndex].FindControl("TextBox2");
  
      int ID = Convert.ToInt32(id);
      ConnectionClassGuitarBrands.CreateGuitarBrandsDatabase(name.Text);
      AddCodeToGuitarFile.AddGuitarClassCode(name.Text, ID);
      AddCodeToGuitarFile.AddConnectionClassGuitarItems(name.Text);
      AddCodeToGuitarFile.AddOverviewGuitarDataASPX(name.Text, ID);
      AddCodeToGuitarFile.AddOverviewGuitarDataASPXCode(name.Text);
      AddASPXAndCSFileForGuitarBrands.AddFile(name.Text,ID);
  
      GuitarBrandsGridView.EditIndex = -1;
      bindgridviewguitarbrands();
  }
  
  //End of Gridview Code for Guitar Brands
  </code></pre>
  
  <p>Hope you guys can help me on this one. Also, this is only for practice. I will implement better security in my website soon.</p>
  
  <p><strong>ADDED CODE: code is too long so i have removed some parts in AddCodeToGuitarFile</strong></p>
  
  <p>Here is the ConnectionClassGuitarBrands.cs:</p>
  
  <pre><code>using System;
  using System.Collections;
  using System.Collections.Generic;
  using System.Configuration;
  using System.Data.SqlClient;
  using System.Linq;
  using System.Web;
  
  /// &lt;summary&gt;
  /// Summary description for ConnectionClassGuitarBrands
  /// &lt;/summary&gt;
  public static class ConnectionClassGuitarBrands
  {
  private static SqlConnection conn;
  private static SqlCommand command;
  static ConnectionClassGuitarBrands()
  {
      string connectionString =
      ConfigurationManager.ConnectionStrings["brandsConnection"].ToString();
      conn = new SqlConnection(connectionString);
      command = new SqlCommand("", conn);
  }
  
  public static void CreateGuitarBrandsDatabase(string brand)
  {
      SqlConnection createBrandData = new SqlConnection(@"Data Source=Y560\SQLEXPRESS;Initial Catalog=GuitarItemsDB;Integrated Security=True");
      createBrandData.Open();
      SqlCommand cmdBrandData = new SqlCommand("CREATE TABLE guitarItem" + brand + "(id int,type char(50),model char(50),price float,image1 char(255),image2 char(255),description text, [neck type] char(100), body char(100), fretboard char(100), fret char(50), bridge char(100),[neck pickup] char(100), [bridge pickup] char(100), [hardware color] char(50)); ", createBrandData);
      cmdBrandData.ExecuteNonQuery();
      createBrandData.Close();
  }
  
  public static void RemoveGuitarBrandsDatabase(string brand)
  {
      SqlConnection removeBrandData = new SqlConnection(@"Data Source=Y560\SQLEXPRESS;Initial Catalog=GuitarItemsDB;Integrated Security=True");
      removeBrandData.Open();
      SqlCommand cmdBrandData = new SqlCommand("DROP TABLE guitarItem"+brand+";" , removeBrandData);
      cmdBrandData.ExecuteNonQuery();
      removeBrandData.Close();
  }
  
  public static ArrayList GetBrandsByType(string brandType)
  {
      ArrayList list = new ArrayList();
      string query = string.Format("SELECT * FROM guitarBrands WHERE type LIKE '{0}'", brandType);
  
      try
      {
          conn.Open();
          command.CommandText = query;
          SqlDataReader reader = command.ExecuteReader();
  
          while (reader.Read())
          {
              int id = reader.GetInt32(0);
              string name = reader.GetString(1);
              string type = reader.GetString(2);
              string image = reader.GetString(3);
  
  
              Brands brand = new Brands(id, name, type, image);
              list.Add(brand);
          }
      }
      finally
      {
          conn.Close();
      }
  
      return list;
  }
  
  public static void AddGuitarBrands(Brands brands)
  {
      string query = string.Format(@"INSERT INTO guitarBrands VALUES ('{0}','{1}','{2}','{3}')", brands.Id, brands.Type, brands.Name, brands.Image);
      command.CommandText = query;
  
      try
      {
          conn.Open();
          command.ExecuteNonQuery();
      }
      finally
      {
          conn.Close();
      }
  
    }
  
  
  
   }
  </code></pre>
  
  <p>Here is the AddCodeToGuitarFile.cs:</p>
  
  <pre><code>using System;
  using System.Collections.Generic;
  using System.IO;
  using System.Linq;
  using System.Web;
  
  /// &lt;summary&gt;
  /// Summary description for AddCodeToGuitarFile
  /// &lt;/summary&gt;
  public static class AddCodeToGuitarFile
  {
    static AddCodeToGuitarFile()
    {
  
    }
  
  public static void AddGuitarClassCode(string brand_name, int brand_number)
  {
      int counter = 0;
      string line;
  
      // Read the file and display it line by line.
      System.IO.StreamReader file = new System.IO.StreamReader(@"C:\Users\User1\Documents\Visual Studio 2015\WebSites\MusicStore\App_Code\AddGuitarClass.cs");
      while ((line = file.ReadLine()) != null)
      {
          if (line.Contains("            default:"))
          {
              break;
          }
          counter += 1;
      }
      file.Close();
  
      var addGuitarLines = File.ReadAllLines(@"C:\Users\User1\Documents\Visual Studio 2015\WebSites\MusicStore\App_Code\AddGuitarClass.cs");
      var _addGuitarLines = new List&lt;string&gt;(addGuitarLines);
      int index = counter;
      index -= 1;
  
      _addGuitarLines.Insert(index++, "            case \"" + brand_name + "\":");
      _addGuitarLines.Insert(index++, "                    string query" + brand_number + " = string.Format(\"INSERT INTO guitarItem" + brand_name + " VALUES ('{0}','{1}','{2}',@itemprice,'{3}','{4}','{5}','{6}','{7}','{8}','{9}','{10}','{11}','{12}','{13}')\",");
      _addGuitarLines.Insert(index++, "                       gItems.Id, gItems.Brand, gItems.Model, gItems.Image1, gItems.Image2, gItems.Description, gItems.NeckType, gItems.Body,");
      _addGuitarLines.Insert(index++, "                       gItems.Fretboard, gItems.Fret, gItems.Bridge, gItems.NeckPickup, gItems.BridgePickup, gItems.HardwareColor);");
      _addGuitarLines.Insert(index++, "");
      _addGuitarLines.Insert(index++, "                       command1.CommandText = query" + brand_number + ";");
      _addGuitarLines.Insert(index++, "                       command1.Parameters.Add(new SqlParameter(\"itemprice\", gItems.Price));");
      _addGuitarLines.Insert(index++, "");
      _addGuitarLines.Insert(index++, "                       try");
      _addGuitarLines.Insert(index++, "                       {");
      _addGuitarLines.Insert(index++, "                           conn1.Open();");
      _addGuitarLines.Insert(index++, "                           command1.ExecuteNonQuery();");
      _addGuitarLines.Insert(index++, "                       }");
      _addGuitarLines.Insert(index++, "                       finally");
      _addGuitarLines.Insert(index++, "                       {");
      _addGuitarLines.Insert(index++, "                           conn1.Close();");
      _addGuitarLines.Insert(index++, "                           command1.Parameters.Clear();");
      _addGuitarLines.Insert(index++, "                       }");
      _addGuitarLines.Insert(index++, "                break;");
      _addGuitarLines.Insert(index++, "");
  
      addGuitarLines = _addGuitarLines.ToArray();
      File.WriteAllLines(@"C:\Users\User1\Documents\Visual Studio 2015\WebSites\MusicStore\App_Code\AddGuitarClass.cs", addGuitarLines);
  
  }
   }
  </code></pre>