2017-03-09 6 views
0

最後に、私は自分のグリッドビュー用のカスタムの削除と編集ボタンを作成することができました。しかし、私はグリッドビューに2つの問題があることに気付きました。asp.net pt.2を使用してgridviewでカスタムの削除と編集ボタンを作成する方法は?

enter image description here

問題1:私が最初に削除ボタンをクリックすると 、それだけでページを更新し、何もしない、私は以下のようにGridViewを持って言うことができます。しかし、2回目にクリックすると、完全に実行されます。なぜ、削除ボタンが機能しないのですか?初めてクリックしたときにページを更新するだけで、2回目には動作します。
問題2: 初めて編集ボタンをクリックすると正常に動作します。その後、私はデータベースを更新/変更することができます。私はid "7"の下で "Dean"という名前を "Jackson"に変更したいと言います。だから、私は単にテキストボックスでそれを変更し、更新ボタンをクリックしました。しかし、ウェブサイトはちょうど再びリフレッシュされ、 "Dean"という名前はまだテキストボックスに残っています(ところで、まだ更新/キャンセルモードです)。だから、もう一度テキストボックスに "Jackson"と入力して、もう一度更新ボタンをクリックする必要があります。今回はそれが動作し、それは私のgridviewを更新しました。問題1と同様に、なぜ更新ボタンが機能していないので、初めてクリックしたときにページを更新するだけで、2回目に動作しますか?ここで

は、ASPXコードである:ここで

<h3>Guitar Brands Data:</h3> 
<div style="overflow:auto; width:1100px; max-height:500px;"> 
    <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"> 
     <Columns> 
      <asp:TemplateField> 
       <ItemTemplate> 
        <asp:Button ID="GuitarBrandsGridViewBtnDelete" runat="server" CommandName="Delete" Text="Delete"/> 
       </ItemTemplate> 
      </asp:TemplateField> 
      <asp:TemplateField> 
       <ItemTemplate> 
        <asp:Button ID="GuitarBrandsGridViewBtnEdit" runat="server" CommandName="Edit" Text="Edit"/> 
       </ItemTemplate> 
       <EditItemTemplate> 
        <asp:Button ID="GuitarBrandsGridViewBtnUpdate" runat="server" CommandName="Update" Text="Update"/> 
        <asp:Button ID="GuitarBrandsGridViewBtnCancel" runat="server" CommandName="Cancel" Text="Cancel"/> 
       </EditItemTemplate> 
      </asp:TemplateField> 
      <asp:TemplateField HeaderText="id" SortExpression="id"> 
       <EditItemTemplate> 
        <asp:Label ID="Label1" runat="server" Text='<%# Eval("id") %>'></asp:Label> 
       </EditItemTemplate> 
       <ItemTemplate> 
        <asp:Label ID="Label2" runat="server" Text='<%# Bind("id") %>'></asp:Label> 
       </ItemTemplate> 
      </asp:TemplateField> 
      <asp:TemplateField HeaderText="type" SortExpression="type"> 
       <EditItemTemplate> 
        <asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("type") %>'></asp:TextBox> 
       </EditItemTemplate> 
       <ItemTemplate> 
        <asp:Label ID="Label3" runat="server" Text='<%# Bind("type") %>'></asp:Label> 
       </ItemTemplate> 
      </asp:TemplateField> 
      <asp:TemplateField HeaderText="name" SortExpression="name"> 
       <EditItemTemplate> 
        <asp:TextBox ID="TextBox2" runat="server" Text='<%# Bind("name") %>'></asp:TextBox> 
       </EditItemTemplate> 
       <ItemTemplate> 
        <asp:Label ID="Label4" runat="server" Text='<%# Bind("name") %>'></asp:Label> 
       </ItemTemplate> 
      </asp:TemplateField> 
      <asp:TemplateField HeaderText="image" SortExpression="image"> 
       <EditItemTemplate> 
        <asp:TextBox ID="TextBox3" runat="server" Text='<%# Bind("image") %>'></asp:TextBox> 
       </EditItemTemplate> 
       <ItemTemplate> 
        <asp:Label ID="Label5" runat="server" Text='<%# Bind("image") %>'></asp:Label> 
       </ItemTemplate> 
      </asp:TemplateField> 
     </Columns> 
     <HeaderStyle CssClass="header"></HeaderStyle> 
     <PagerStyle CssClass="pager"></PagerStyle> 
     <RowStyle CssClass="rows"></RowStyle> 
    </asp:GridView> 
    </div> 
    <asp:SqlDataSource ID="SqlDataSource0" runat="server" ConnectionString="<%$ ConnectionStrings:brandsConnection %>" 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"> 
     <DeleteParameters> 
      <asp:Parameter Name="id" Type="Int32" /> 
     </DeleteParameters> 
     <InsertParameters> 
      <asp:Parameter Name="id" Type="Int32" /> 
      <asp:Parameter Name="type" Type="String" /> 
      <asp:Parameter Name="name" Type="String" /> 
      <asp:Parameter Name="image" Type="String" /> 
     </InsertParameters> 
     <UpdateParameters> 
      <asp:Parameter Name="type" Type="String" /> 
      <asp:Parameter Name="name" Type="String" /> 
      <asp:Parameter Name="image" Type="String" /> 
      <asp:Parameter Name="id" Type="Int32" /> 
     </UpdateParameters> 
    </asp:SqlDataSource> 
    <br/> 

はaspx.csコードである:

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 > 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 

は、君たちはこの1つに私を助けることができる願っています。また、これは練習のためだけです。私はすぐに私のウェブサイトでより良いセキュリティを実装します。

を追加しましたCODE:コードは長すぎるので、私はここで

AddCodeToGuitarFileでいくつかの部分を削除したあるConnectionClassGuitarBrands.csです:

ここ
using System; 
using System.Collections; 
using System.Collections.Generic; 
using System.Configuration; 
using System.Data.SqlClient; 
using System.Linq; 
using System.Web; 

/// <summary> 
/// Summary description for ConnectionClassGuitarBrands 
/// </summary> 
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(); 
    } 

    } 



} 

があるAddCodeToGuitarFile.cs:

using System; 
using System.Collections.Generic; 
using System.IO; 
using System.Linq; 
using System.Web; 

/// <summary> 
/// Summary description for AddCodeToGuitarFile 
/// </summary> 
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<string>(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); 

} 
} 
+0

「ConnectionClassGuitarBrands」クラスと「AddCodeToGuitarFile」クラスのコードを共有することもできます。 –

+0

@MAdeelKhalid - 上記の質問を編集しました。 – BrunoEarth

+0

私は誰かが私の質問に答えることを望みます – BrunoEarth

答えて

0

私はついにこの問題を解決しました。私は最初に何かを削除すると、それがリフレッシュすることを最初に考えました。しかし、私はそれがないことを知りました。その理由は、私は2回目の何かを削除すると、グリッドビューを更新していない理由です。この問題への答えは単にResponse.Redirectです。

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 > 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); 

Response.Redirect("url"); //The answer to this question 

} 
0

page_loadイベントハンドラを以内に変更するだけで済みます。このような:

protected void Page_Load(object sender, EventArgs e) 
    { 
     if(!IsPostBack) 
     bindgridviewguitarbrands(); 
    } 

あなたが編集をクリックしたときに/ボタンを削除するので、それだけでグリッド内のグリッドデータと、すべてのイベントデータを更新し、あまりにも更新されます。したがって、グリッドイベントは再度バインドされ、編集/削除のイベントが要件ごとに発生しないのはなぜですか。

私はあなたのコードをテストしましたが、この変更だけで問題は解決します。

希望します。

+0

応答のためにありがとう、しかし私はすでにこれを試して、それはまだ動作していません。しかし、私はRemoveCodeToGuitarFile.RemoveOverviewGuitarDataASPX(名前)とRemoveCodeToGuitarFile.RemoveOverviewGuitarDataCode(名前)を消去するときに気付いた。すべて正常に動作しています。彼らは両方を削除する必要があります、私は1つを保持する場合、それは私にエラーを与える。 – BrunoEarth

関連する問題