Gridview按钮在TemplateField只触发第二次点击

本文关键字:第二次 按钮 TemplateField Gridview | 更新日期: 2023-09-27 18:02:10

我在提问之前做了一些搜索,虽然这篇文章很接近,但它不适合我的场景。

我发现,在我的模板字段中的"删除"按钮似乎触发,但点击事件没有触发。然而,当你第二次点击按钮时,它会像预期的那样工作。

因此,将代码分解,我使用' SqlDataSource将我的数据绑定到GridView

我的页面加载事件开始如下:

if (!Page.IsPostBack)  
{  
    externalUserDataSource.ConnectionString = "some connection string";  
}

我的数据来源如下:

<asp:SqlDataSource ID="externalUserDataSource" runat="server" 
    ConflictDetection="CompareAllValues" SelectCommand="uspGetExternalUsersByTeam"
SelectCommandType="StoredProcedure" ProviderName="System.Data.SqlClient">
<SelectParameters>
    <asp:SessionParameter Name="TeamID" SessionField="TeamID" Type="Int32" />
</SelectParameters>
</asp:SqlDataSource>

这是我的GridView标记:

<asp:GridView ID="gridView" runat="server" AutoGenerateColumns="False" 
    BackColor="White" BorderColor="#3366CC" BorderStyle="None" BorderWidth="1px" 
    CellPadding="4" DataKeyNames="LoginID" DataSourceID="externalUserDataSource" 
    EnableModelValidation="True" OnRowDataBound="GridViewRowDataBound" TabIndex="3">
        <HeaderStyle BackColor="#003399" Font-Bold="True" ForeColor="White" />
        <FooterStyle BackColor="#99CCCC" ForeColor="#003399" />
        <PagerStyle BackColor="#99CCCC" ForeColor="#003399" HorizontalAlign="Left" />
        <RowStyle BackColor="LightGoldenrodYellow" />
        <SelectedRowStyle BackColor="#009999" Font-Bold="True" ForeColor="#CCFF99" />
        <Columns>
            <asp:BoundField DataField="RowID" HeaderText="Row ID" ReadOnly="True" 
                SortExpression="RowID" Visible="False" />
            <asp:BoundField DataField="LoginID" HeaderText="Login ID" ReadOnly="True" 
                SortExpression="LoginID" Visible="False" />
            <asp:BoundField DataField="EmailAddress" HeaderText="Email Address" 
                ItemStyle-VerticalAlign="Bottom" ReadOnly="True" SortExpression="AssociateName"/>
            <asp:BoundField DataField="TeamID" HeaderText="Team ID" ReadOnly="True" 
                SortExpression="TeamID" Visible="False" />
            <asp:CheckBoxField DataField="HasFIAccess" 
                 HeaderText="Has Access to&lt;br /&gt;Funding&lt;br/&gt;Illustrator" 
                 ItemStyle-HorizontalAlign="Center" ItemStyle-VerticalAlign="Bottom" 
                 ReadOnly="True"/>
            <asp:CheckBoxField DataField="HasALTAccess" 
                 HeaderText="Has Access to&lt;br /&gt;Asset Liability&lt;br/&gt;Tracker" 
                 ItemStyle-HorizontalAlign="Center" ItemStyle-VerticalAlign="Bottom"
                 ReadOnly="True"/>
            <asp:CheckBoxField DataField="HasFIAAccess" 
                 HeaderText="Has Access to&lt;br /&gt;Funding&lt;br/&gt;Illustrator App" 
                 ItemStyle-HorizontalAlign="Center" ItemStyle-VerticalAlign="Bottom"
                 ReadOnly="True"/>                    
            <asp:TemplateField>
            <ItemTemplate>
                <asp:Button runat="server" CssClass="additionsRow" ID="btnDeleteExternalUser" OnClick="DeleteExtUserButtonClick" 
                    CausesValidation="False" Text="Delete" 
                    CommandArgument='<%#Eval("TeamID") + "," + Eval("LoginID") + "," + Eval("EmailAddress") + "," + Eval("HasALTAccess")%>'/>                            
            </ItemTemplate>
            </asp:TemplateField>
        </Columns>
    </asp:GridView>

所以,你可以看到我在事件中使用的按钮中传递了一些信息,以确保正确的数据被删除(这就是为什么我不能使用ButtonField,如上面的链接所建议的)。

最后一部分是GridView的绑定事件:

        protected void GridViewRowDataBound(object sender, 
                                        GridViewRowEventArgs e)
    {
        // if rowtype is not data row...
        if (e.Row.RowType != DataControlRowType.DataRow)
        {
            // exit with no further processing...
            return;
        }
        // get the ID for the selected record...
        var selectedId = DataBinder.Eval(e.Row.DataItem, "RowID").ToString();
        // create unique row ID...
        e.Row.ID = string.Format("ExtUserRow{0}", selectedId);
        // find the button delete for the selected row...
        var deleteButton = (Button)e.Row.FindControl("btnDeleteExtUser");
        // get the email address for the selected record...
        var selectedUser = DataBinder.Eval(e.Row.DataItem, "EmailAddress").ToString();
        // define the message text...
        var messageText = string.Format("OK to delete {0}?",
                                        selectedUser.Replace("'", "'''")); 
        // add attribute to row delete action...
        this.AddConfirmMessage(deleteButton, messageText);
    }  

其中AddConfirmMessage只是为控件分配一个onclick属性,以确保用户必须确认删除。

现在,在每种情况下都会弹出消息'OK to delete abc@xyz.com?',但如前所述,分配给"delete"按钮的事件直到第二次单击按钮才触发。

奇怪的是,我从另一个页面上取了这段代码并进行了相应的修改,尽管那里没有这个问题:

        protected void DeleteExtUserButtonClick(object sender, 
                                            EventArgs e)
    {
        // get the buton which was clicked...
        var button = (Button)sender;
        // break the delimited array up...
        string[] argumentArray = button.CommandArgument.Split(',');
        // store the items from the array...
        string teamId = argumentArray[0];
        string loginId = argumentArray[1];
        string emailAddress = argumentArray[2];
        string hasAltAccess = argumentArray[3];
        using (var conn = new SqlConnection(Utils.GetConnectionString()))
        {
            // create database command...
            using (var cmd = new SqlCommand())
            {
                // set the command type...
                cmd.CommandType = CommandType.StoredProcedure;
                // set the name of the stored procedure to call...
                cmd.CommandText = "uspDeleteExternalUser";
                // create and add parameter to the collection...
                cmd.Parameters.Add(new SqlParameter("@TeamId", SqlDbType.Int));
                // assign the search value to the parameter...
                cmd.Parameters["@TeamId"].Value = teamId;
                // create and add parameter to the collection...
                cmd.Parameters.Add(new SqlParameter("@LoginId", SqlDbType.VarChar, 50));
                // assign the search value to the parameter...
                cmd.Parameters["@LoginId"].Value = loginId;
                // set the command connection...
                cmd.Connection = conn;
                // open the connection...
                conn.Open();
                // perform deletion of user...
                cmd.ExecuteNonQuery();
            }
        }
        // bind control to refresh content...
        ExtUsersGrid.DataBind();
    }

我错过了什么明显的东西吗?如果有更好的方法,我很乐意修改。

编辑1:根据下面的讨论,我修改了以下内容:

  • 删除ButtonItemOnclick事件属性;
  • 按如下建议设置CommandNameCommandArgument,并将DataKeyNames更新为使用RowID,这是来自数据的唯一ID;
  • GridView分配RowCommand事件;
  • RowCommand事件分配删除码。

在这些更改之后,它仍然在第二次单击时触发行事件代码。

编辑2:供参考-我现在已经删除了SqlDataSource和相关的代码/引用,并创建了一个过程来填充数据集,这是在Page_Load上调用的(在!Page.IsPostBack括号内)。我开始做下面的改变,使用RowCommand事件,但他们仍然引起了同样的问题(即按钮只会在第二次点击时触发)。由于使用RowCommand意味着将BoundField s转换为ItemTemplate s,我回到按钮单击事件,因为它似乎毫无意义地进行所有这些更改。如果有人能帮助我理解为什么它只在第二次点击时触发,将非常感谢您的输入。

Gridview按钮在TemplateField只触发第二次点击

好吧,令人沮丧的是,这是由于一些代码由于未知的原因,在其他地方工作。
在DataBound事件中,有两行代码:

        // get the associate name for the selected record...
        var selectedId = DataBinder.Eval(e.Row.DataItem, "RowID").ToString();
        // create unique row ID...
        e.Row.ID = string.Format("ExtUserRow{0}", selectedId);  

以编程方式向行应用ID的过程似乎破坏了数据和事件之间的连接。
通过删除这两行代码,它可以按预期工作。

你可以这样做。

像这样添加一个CommandName属性到你的GridView。还要注意CommandArgument属性中的变化:

<asp:TemplateField>
    <ItemTemplate>
        <asp:Button runat="server" CssClass="additionsRow" ID="btnDeleteExtUser"  
                    CausesValidation="False" Text="Delete" 
                    CommandName="OnDelete"  
                    CommandArgument='<%# Container.DisplayIndex %>" '                              
</ItemTemplate>
</asp:TemplateField>

后面的代码看起来像这样。注意,我使用的是GridviewRowCommand事件。

protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
    if(e.CommandName == "OnDelete")
    {
        int rowIndex = Convert.ToInt32(e.CommandArgument);
        // now you got the rowindex, write your deleting logic here.
        int ID = Convert.ToInt32(myGrid.DataKeys[rowIndex]["ID"].Value);
        // id will return you the id of the row you want to delete 
        TextBox tb = (TextBox)GridView1.Rows[rowIndex].FindControl("textboxid");
        string text = tb.Text;
        // This way you can find and fetch the properties of controls inside a `GridView`. Just that it should be within `ItemTemplate`.
    }
} 

注意:在你的GridView里面提到DataKeyNames="ID"。"ID"是表的主键列。

你绑定GridView页面加载吗?如果是,那么将其移动到!IsPostBack块,如下所示:

protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
    {
        GridView1.DataSource = yourDataSource;
        GridView1.DataBind();           
    } 
}