在TemplateField的GridView中,buttonclick不会触发

本文关键字:buttonclick TemplateField GridView | 更新日期: 2023-09-27 17:50:30

我想写一个代码,只更新一个记录的数据。

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

我有一个定义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";
    }
}

在TemplateField的GridView中,buttonclick不会触发

当您尝试从GridView处理事件时,您需要使用CommandNameCommandArgument,然后从GridView处理RowCommand事件。

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

ASP。网页应该看起来像:

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

我终于明白了。我必须把<asp:Button/>改成

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

并将其从ItemTemplate中删除。

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

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

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

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

Thank you