【问题标题】:Button onClick does not fire in GridView inside of TemplateField按钮 onClick 不会在 TemplateField 内的 GridView 中触发
【发布时间】:2014-04-21 06:17:34
【问题描述】:

我正在尝试编写一个只更新数据记录的代码。

我不需要能够更新行中的每个字段,只需要更新一个特定字段。

我有一个定义 GridView 的页面,如下所示:

<asp:Content runat="server" ID="BodyContent" ContentPlaceHolderID="MainContent">
<UpdatePanel> 
    <ContentTemplate>   
 <fieldset style="width: 1%">
        <legend>Search Customer</legend>
        <table>
            <tr>
                <td>
                <asp:DropDownList id="ddlSearchOption"
                    AutoPostBack="True"
                    OnSelectedIndexChanged="ddlSearchOption_SelectedIndexChanged"
                    runat="server">
                    <asp:ListItem Selected="True" Value="SearchBy"> Search By </asp:ListItem>
                    <asp:ListItem Value="CustID"> Customer ID </asp:ListItem>
                    <asp:ListItem Value="CustFirst"> First Name </asp:ListItem>
                    <asp:ListItem Value="CustLast"> Last Name </asp:ListItem>
                    <asp:ListItem Value="CustCity"> City </asp:ListItem>
                </asp:DropDownList>
                </td>
      <asp:Panel id="pnlCustSearch" runat="server" >
                    <td>
             <asp:Label id="lblEntry" runat="server" Text="" width="120px"></asp:Label>
                    </td>
                    <td>
                        <asp:TextBox id="txtSearchOptions" runat="server" width="50px">Hello</asp:TextBox>
                    </td>
                    <td>
                        <asp:Button id="btnFind" Text="Search" runat="server" onClick="btnFind_Click"></asp:Button>
                    </td>
    </asp:Panel>
            </tr>
        </table>
    </fieldset>
    <div id ="msg">
    <asp:Label id="lblMsg" runat="server" Text=""></asp:Label>
    </div>
    <div id="gridShow">

  <asp:GridView ID="GridView1" runat="server" GridLines="None" AutoGenerateColumns="false"
  AlternatingRowStyle-BackColor="#EEEEEE" EditRowStyle-BorderColor="Red">           
  <Columns>           
     <asp:TemplateField Visible="true" HeaderText="Customer ID">
        <ItemTemplate>
          <asp:Label runat="server" ID="lblCustID" Text='<%#Eval("CustID")%>' />
        </ItemTemplate>
     </asp:TemplateField>

     <asp:TemplateField HeaderText="First Name">

        <ItemTemplate>
         <asp:Label runat="server" ID="lblFirstName" Text='<%#Eval("CustFirstName") %>' />
        </ItemTemplate>
     </asp:TemplateField>
     <asp:TemplateField HeaderText="Last Name">
        <ItemTemplate>
          <asp:Label runat="server" ID="lblLastName" Text='<%#Eval("CustLastName") %>' />
        </ItemTemplate>
     </asp:TemplateField>

     <asp:TemplateField HeaderText="City">
       <ItemTemplate>
         <asp:Label runat="server" ID="lblCity" Text='<%#Eval("CustCity") %>' />
       </ItemTemplate>
     </asp:TemplateField>
     <asp:TemplateField HeaderText="Email">  
      <ItemTemplate>
         <asp:TextBox runat="server" ID="txtEmail" Text='<%#Eval("CustEmail") %>' />
          <asp:Button runat="server" ID="btnUpdate" Text="Update" onClick="GridView1_btnUpdate_Click"/>
  <asp:RequiredFieldValidator runat="server" ID="rfdCountry" ControlToValidate="txtEmail" 
             ValidationGroup="var1" ErrorMessage="*" />
       </ItemTemplate>
     </asp:TemplateField>

 </Columns>
 </asp:GridView>

</div>
</ContentTemplate>
</UpdatePanel> 

 </asp:Content>

然后在代码隐藏中我写以下内容:

    protected void GridView1_btnUpdate_Click(Object sender, EventArgs e)
    {
       //Code goes here
    }

单击按钮更新电子邮件时,没有任何反应。

我做错了什么?

我在这里尝试使用其中一个建议:

        if (!IsPostBack)
        {
            GridView1.DataSource = App_Data.DataHandler.GetData("fname", "de");
            GridView1.DataBind();
            GridView1.Visible = true;
        }

数据显示了,但是点击事件无论如何都不起作用

我在 GridView 定义中添加了以下内容:

onrowcommand="GridView1_RowCommand"

并添加了建议的代码:

             <asp:Button runat="server" ID="btnUpdate" Text="Update" CommandName="UpdateEmail" 
             CommandArgument="<%# ((GridViewRow) Container).RowIndex %>"/>

在我的.cs 文件中,我添加了以下内容:

        protected void GridView1_RowCommand(Object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "UpdateEmail")
        {
            //Get the index from the argument
            int index = Convert.ToInt32(e.CommandArgument);
            //Get the row
            GridViewRow row = GridView1.Rows[index];

            //Do whatever you need with your row here!
        }
    }

不过,点击事件不会触发。

好的,这是我在.cs文件后面的代码:

public partial class index : System.Web.UI.Page
{
    protected override object LoadPageStateFromPersistenceMedium()
    {
        return Session["__VIEWSTATE"];
    }
    protected override void SavePageStateToPersistenceMedium(object viewState)
    {
        Session["VIEWSTATE"] = viewState;
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
            Reset();
        else
            lblMsg.Text = "";

    }

    protected void Reset()
    {
        pnlCustSearch.Visible = false;
        GridView1.Visible = false;
        lblMsg.Text = "";
    }

    protected void ddlSearchOption_SelectedIndexChanged(object sender, EventArgs e)
    {

            Reset();
            String ddlSelected = ddlSearchOption.SelectedValue;
            if (ddlSelected != "")
            {
                ViewState["ddlSelected"] = ddlSelected;
                pnlCustSearch.Visible = true;
                SelectLabel(ddlSelected);
            }
    }

    protected void SelectLabel(String choice)
    {
        switch (choice)
        {
            case "CustID":
                lblEntry.Text = "Enter Customer ID";
                break;
            case "CustFirst":
                lblEntry.Text = "Enter First Name";
                break;
            case "CustLast":
                lblEntry.Text = "Enter Last Name";
                break;
            case "CustCity":
                lblEntry.Text = "Enter City";
                break;
            default: 
                lblEntry.Text = "Enter Customer ID";
                break;
        }
    }

    protected void btnFind_Click(object sender, EventArgs e)
    {
        GridView1.Visible = true;
        String option = (String)ViewState["ddlSelected"];
        String input = txtSearchOptions.Text.Trim();

        GridView1.DataSource = DataHandler.GetData(option,input);
        GridView1.DataBind();
        GridView1.Visible = true;

    }

    protected void GridView1_RowCommand(Object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "UpdateEmail")
        {
            //Get the index from the argument
            int index = Convert.ToInt32(e.CommandArgument);
            //Get the row
            GridViewRow row = GridView1.Rows[index];

            //Do whatever you need with your row here!
        }
    }

    protected void btnUpdate_Click(Object sender, EventArgs e)
    {
        String txt = null;
        txt = "here";
    }
}

【问题讨论】:

    标签: c# asp.net gridview templatefield


    【解决方案1】:

    当您尝试处理来自GridView 的事件时,您需要使用CommandName 和CommandArgument 然后处理来自GridView 的RowCommand 事件。

    参考http://msdn.microsoft.com/...。

    ASP.Net 页面应如下所示:

    <asp:ButtonField runat="server" ID="btnUpdate" Text="Update" 
         CommandName="UpdateEmail" 
         CommandArgument="<%# CType(Container,GridViewRow).RowIndex %>" />
    

    在RowCommand 事件中:

    if (e.CommandName == "UpdateEmail")
    {
        //Get the index from the argument
        int index = Convert.ToInt32(e.CommandArgument);
        //Get the row
        GridViewRow row = GridView1.Rows[index];
    
        //Do whatever you need with your row here!
    }
    

    【讨论】:

    • 我对这些东西比较陌生。所以不要介意我问。它只适用于单列吗?我不需要更新整行,只需要更新一个特定字段,在我的情况下是电子邮件。谢谢
    • 刚刚尝试了您的建议。不工作。不知何故,事件根本没有触发
    • 你处理 GridView RowCommand 吗?
    • 我还注意到每次单击更新按钮时,它都会以某种方式触发 SelectedIndexChanged 事件?
    • 是的,我处理 'OnRowCommand="GridView1_RowCommand' 我正在使用 VS 2012。这可能是个问题吗?
    【解决方案2】:

    我终于明白了。我不得不将 &lt;asp:Button/&gt; 更改为

        `<asp:ButtonField Text="Update Email" CommandName="UpdateEmail"`
    

    并将其从 ItemTemplate 中删除。

    但是为什么这是一个问题。我想做的只是用按钮在同一个itemtemplate中显示文本字段?

    【讨论】:

      【解决方案3】:

      实际上,答案比我最初想的要容易得多。我只是使用不同的值来设置会话:__VIEWSTATE 和 VIEWSTATE

          protected override object LoadPageStateFromPersistenceMedium()
          {
              return Session["__VIEWSTATE"];
          }
          protected override void SavePageStateToPersistenceMedium(object viewState)
          {
          Session["VIEWSTATE"] = viewState;
          }
      

      只要我更改它,按钮就能够触发事件。

      谢谢

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-07-12
        相关资源
        最近更新 更多