【问题标题】:How to find TextBox in GridViewRow edit mode如何在 GridViewRow 编辑模式下查找 TextBox
【发布时间】:2016-02-06 22:18:15
【问题描述】:

我已经为此尝试了几个所谓的答案,但它让我迷失了方向。我只是想用今天的日期和时间默认一个TextBox 文本值,但是当我单击带有命令名称“编辑”的LinkButton 时找不到控件。

这是我的网格视图...

   <asp:GridView ID="gvSignInRegister" runat="server" AllowPaging="True" AllowSorting="True" AutoGenerateColumns="False" CellPadding="3" 
        DataSourceID="sdsSignInRegister" ForeColor="Black" BackColor="White" BorderColor="#999999" BorderStyle="Solid" BorderWidth="1px" GridLines="Vertical" OnRowCommand="gvSignInRegister_RowCommand1">
        <Columns>
            <asp:TemplateField HeaderText="Returned" SortExpression="DateTimeReturned">
                <EditItemTemplate>
                    <asp:TextBox ID="txtReturned" runat="server"></asp:TextBox>
                    <asp:ImageButton runat="Server" ID="calImg" ImageUrl="~/images/Calendar_scheduleHS.png" AlternateText="Click to show calendar" CausesValidation="False" />
                    <asp:RequiredFieldValidator ID="rfv1" runat="server" SetFocusOnError="true" ValidationGroup="vg1" ControlToValidate="txtReturned" ErrorMessage="Required"></asp:RequiredFieldValidator>
                    <ajaxToolkit:CalendarExtender ID="ce1" runat="server" PopupButtonID="calImg" Enabled="true" Format="dd/MM/yyyy" TargetControlID="txtReturned" PopupPosition="TopRight" OnClientDateSelectionChanged="AppendTime"></ajaxToolkit:CalendarExtender>
                </EditItemTemplate>
                <ItemTemplate>
                    <asp:Label ID="Label9" runat="server" Text='<%# Eval("DateTimeReturned","{0:dd/MM/yyyy HH:mm}") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField ShowHeader="False">
                <EditItemTemplate>
                    <asp:Button ID="btnCAN" runat="server" CausesValidation="false" CommandName="Cancel" Text="CANCEL" />
                    <asp:Button ID="btnUPD" runat="server" ValidationGroup="vg1" CausesValidation="true" CommandName="Update" Text="UPDATE" />
                </EditItemTemplate>
                <ItemTemplate>
                    <asp:Button ID="btnEDT" runat="server" CausesValidation="false" CommandName="Edit" CommandArgument='<%# Container.DataItemIndex %>' Text="SIGN IN" />
                </ItemTemplate>
            </asp:TemplateField>
        </Columns>
        <FooterStyle BackColor="#CCCCCC" />
        <PagerStyle BackColor="#999999" ForeColor="Black" HorizontalAlign="Center" />
        <SelectedRowStyle BackColor="#000099" Font-Bold="True" ForeColor="White" />
        <HeaderStyle BackColor="Black" Font-Bold="True" ForeColor="White" />
        <AlternatingRowStyle BackColor="#CCCCCC" />
    </asp:GridView>

LinkBut​​ton btnEDT 工作并将gridview 置于编辑模式。但是在后面的代码中我找不到“txtReturned”。

这是我迄今为止尝试过的......

protected void gvSignInRegister_RowCommand(object sender, GridViewCommandEventArgs e)
{
    if (e.CommandName == "Edit")
    {
        int rowIdx = Convert.ToInt32(e.CommandArgument);
        GridViewRow row = gvSignInRegister.Rows[rowIdx];
        if (row != null && row.RowType == DataControlRowType.DataRow)
        {
            TextBox tb = (TextBox)row.FindControl("txtReturned");
            if (tb != null) tb.Text = DateTime.Now.ToString("dd/MM/yyyy HH:mm");

            //I've tried this too but it does not work. Interestingly, it does not crash, so cells[4] must exist!
            //row.Cells[4].Text = DateTime.Now.ToString("dd/MM/yyyy HH:mm");
        }
    }
}

由于某种原因,rowIdx 始终为 0。为什么?我认为行索引为 0 表示 gridview 控件的标题。

我也尝试过使用大多数其他人在其他帖子中建议的 NamingContainer,但它返回一个空白(我怀疑是新的?)GridViewRow。

GridViewRow 行 = (GridViewRow)((GridViewRow)(e.CommandSource).NamingContainer);

更新

我找到了this,这正是我遇到的问题,但是通过 RowEditing 的解决方案仍然找不到文本框!

但是 RowDataBound() 解决了它!请阅读下面的答案。

【问题讨论】:

    标签: c# textbox gridviewrow


    【解决方案1】:

    答案是进入 GridView 本身的编辑模式版本,然后找到控件!

    根据this post...

    <asp:GridView ID="gvSignInRegister" runat="server" AllowPaging="True" AllowSorting="True" AutoGenerateColumns="False" CellPadding="3" 
                DataSourceID="sdsSignInRegister" ForeColor="Black" BackColor="White" BorderColor="#999999" BorderStyle="Solid" BorderWidth="1px" GridLines="Vertical" OnRowDataBound="gvSignInRegister_RowDataBound">
                <Columns> ...etc...
    
    
    protected void gvSignInRegister_RowDataBound(object sender, GridViewRowEventArgs e)
                    {
                        if (e.Row.RowType == DataControlRowType.DataRow)
                        {
                            if ((e.Row.RowState & DataControlRowState.Edit) > 0)
                            {
                                TextBox tb = (TextBox)e.Row.FindControl("txtReturned");
                                if (tb != null) tb.Text = DateTime.Now.ToString("dd/MM/yyyy HH:mm");
                            }
                        }
                    }
    

    【讨论】:

      【解决方案2】:

      使用 Container.DisplayIndex 代替 Container.DataItemIndex

      但我不认为如果你将它放在 EditItemTemplate 中你会得到 textBox 控件

      如果您的期望是编辑操作,请使用以下代码

      HTML

      <asp:GridView ID="gvSignInRegister" runat="server" AllowPaging="True" AllowSorting="True" AutoGenerateColumns="False" CellPadding="3"           ForeColor="Black" BackColor="White" BorderColor="#999999" BorderStyle="Solid" BorderWidth="1px" OnRowEditing="gvSignInRegister_RowEditing" OnRowCancelingEdit="gvSignInRegister_RowCancelingEdit"  OnRowUpdating ="gvSignInRegister_RowUpdating" GridLines="Vertical">
                  <Columns>
                      <asp:TemplateField HeaderText="Returned" SortExpression="DateTimeReturned">
                          <EditItemTemplate>
                              <asp:TextBox ID="txtReturned" Text='<%#Bind("DateTimeReturned", "{0:dd/MM/yyyy HH:mm}")%>'  runat="server"></asp:TextBox>
                              <asp:ImageButton runat="Server" ID="calImg" ImageUrl="~/images/Calendar_scheduleHS.png" AlternateText="Click to show calendar" CausesValidation="False" />
                          </EditItemTemplate>
                          <ItemTemplate>
                              <asp:Label ID="Label9" runat="server" Text='<%# Eval( "DateTimeReturned","{0:dd/MM/yyyy HH:mm}") %>'></asp:Label>
                          </ItemTemplate>
                      </asp:TemplateField>
                      <asp:CommandField ShowEditButton="true" />
                  </Columns>
                  <FooterStyle BackColor="#CCCCCC" />
                  <PagerStyle BackColor="#999999" ForeColor="Black" HorizontalAlign="Center" />
                  <SelectedRowStyle BackColor="#000099" Font-Bold="True" ForeColor="White" />
                  <HeaderStyle BackColor="Black" Font-Bold="True" ForeColor="White" />
                  <AlternatingRowStyle BackColor="#CCCCCC" />
      
              </asp:GridView>
      

      代码隐藏:

          protected void gvSignInRegister_RowEditing(object sender, GridViewEditEventArgs e)
          {
              gvSignInRegister.EditIndex = e.NewEditIndex;
              List<QuotationDetail> itemList = (List<QuotationDetail>)ViewState["ItemList"];
              gvSignInRegister.DataSource = itemList;
              gvSignInRegister.DataBind();
          }
      
          protected void gvSignInRegister_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
          {
      
          }
      
          protected void gvSignInRegister_RowUpdating(object sender, GridViewUpdateEventArgs e)
          {
              var txtQty = (TextBox)gvSignInRegister.Rows[e.RowIndex].FindControl("txtQuantity");
              decimal qty = 0;
              decimal.TryParse(txtQty.Text, out qty);
      
              if (qty < 0)
              {
                  lblErrorSummary.InnerText = "Please provide valid Quantity";
                  lblErrorSummary.Visible = true;
                  return;
              }
              itemList[e.RowIndex].Quantity = qty
              ViewState["ItemList"] = itemList;
              gvSignInRegister.EditIndex = -1;
              gvSignInRegister.DataSource = itemList;
              gvSignInRegister.DataBind();
          }
      

      【讨论】:

      • 谢谢,但在用户提供有效的日期/时间之前我不会启动 GV 更新,并且我希望它在点击提交触发 RowUpdating 之前默认为今天的日期和时间。我刚刚尝试使用 RowEditing,因为它处于编辑模式,是的,你是对的。我仍然找不到文本框。这是为什么?在gridview的编辑模式下找不到控件吗?
      • 是的,EditItemTemplate 中的控件只有在编辑模式激活后才可用。所以你不能在行编辑事件中得到它。这就是我对文本框控件进行绑定的原因。这将为您提供一个占位符,以在加载网格本身时取消当前日期。您可以在 rowUpdating 事件中进行验证,如果验证失败则返回 false。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-12-06
      • 2018-02-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-08
      相关资源
      最近更新 更多