【问题标题】:How to create custom delete and edit button in gridview using asp.net pt.2?如何使用 asp.net pt.2 在 gridview 中创建自定义删除和编辑按钮?
【发布时间】:2017-03-14 17:46:24
【问题描述】:

最后我能够为我的 gridview 创建一个自定义的删除和编辑按钮。但是我注意到我的gridview中有两个问题。假设我有一个如下所示的网格视图:

问题 1: 当我第一次单击删除按钮时,它只是刷新页面并且什么都不做。但是当我第二次单击它时,它会完美执行。为什么第一次点击时删除按钮不起作用,只是刷新页面,然后第二次起作用?
问题2: 当我第一次单击编辑按钮时,它工作正常。然后,我可以更新/更改数据库。假设我想将 ID“7”下的名称“Dean”更改为“Jackson”。所以我只是简单地在文本框中更改它并单击更新按钮。但是网站再次刷新,名称“Dean”仍在文本框中(顺便说一句,这仍然处于更新/取消模式)。所以我需要在文本框中再次输入“Jackson”,然后第二次点击更新按钮。这次它起作用了,它确实更新了我的gridview。与问题1类似,为什么第一次点击更新按钮不起作用,只是刷新页面,第二次点击可以?

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

希望你们能帮助我解决这个问题。另外,这只是为了练习。我将很快在我的网站中实施更好的安全性。

添加的代码:代码太长,所以我删除了 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);

}
 }

【问题讨论】:

  • 分享你的ConnectionClassGuitarBrandsAddCodeToGuitarFile类的代码。
  • @MAdeelKhalid - 我已经编辑了上面的问题。
  • 我希望有人能回答我的问题
  • 我希望有人能回答我的问题

标签: c# asp.net gridview


【解决方案1】:

您只需要像这样修改aspx.cs 中的page_load 事件处理程序:

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

因为每当您单击编辑/删除按钮时,它只会刷新网格数据,并且网格内的所有事件数据也会刷新。因此,网格事件再次绑定,这就是为什么那些编辑/删除事件没有按要求触发的原因。

我已经测试了您的代码,只是这个更改将解决您的问题。

希望对你有帮助。

【讨论】:

  • 感谢您的回复,但我已经尝试过了,但仍然无法正常工作。但我注意到,当我删除 RemoveCodeToGuitarFile.RemoveOverviewGuitarDataASPX(name) 和 RemoveCodeToGuitarFile.RemoveOverviewGuitarDataCode(name) 时。一切正常。它们都需要删除,如果我保留一个,它会给我一个错误。
【解决方案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

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-01-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多