最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

asp.net - How to reference a control in an empty data template? - Stack Overflow

programmeradmin1浏览0评论

I have in a gridview:

<EmptyDataTemplate>
    <asp:Panel ID="pnlanadir" runat="server">
        <tr>
            <td><b><asp:label ForeColor="Red" Text="*" runat="server" /> Tipo español</b> <asp:TextBox ID="txttipo_espanol" MaxLength="25" runat="server" />
                    <asp:LinkButton ID="lnkanadir" ValidationGroup="tiposobras" Text="Añadir" OnCommand="anadir" runat="server" />
                    <asp:RequiredFieldValidator ValidationGroup="tiposobras" ControlToValidate="txttipo_espanol" ErrorMessage="Tipo español obligatorio" Display="None" runat="server" />
                    <asp:RegularExpressionValidator ValidationGroup="tiposobras" ControlToValidate="txttipo_espanol" ErrorMessage="Tipo español inválido" Display="None" ValidationExpression="[^'<>]*" runat="server" />

            </td>
            <td><b><asp:label ForeColor="Red" Text="*" runat="server" /> Tipo inglés</b> <asp:TextBox ID="txttipo_ingles" MaxLength="25" runat="server" />
                    <asp:RequiredFieldValidator ValidationGroup="tiposobras" ControlToValidate="txttipo_ingles" ErrorMessage="Tipo inglés obligatorio" Display="None" runat="server" />
                    <asp:RegularExpressionValidator ValidationGroup="tiposobras" ControlToValidate="txttipo_ingles" ErrorMessage="Tipo inglés inválido" Display="None" ValidationExpression="[^'<>]*" runat="server" />
            </td>
            <td><b><asp:label ForeColor="Red" Text="*" runat="server" /> Tipo francés</b> <asp:TextBox ID="txttipo_frances" MaxLength="25" runat="server" />
                    <asp:RequiredFieldValidator ValidationGroup="tiposobras" ControlToValidate="txttipo_frances" ErrorMessage="Tipo francés obligatorio" Display="None" runat="server" />
                    <asp:RegularExpressionValidator ValidationGroup="tiposobras" ControlToValidate="txttipo_frances" ErrorMessage="Tipo francés inválido" Display="None" ValidationExpression="[^'<>]*" runat="server" />
            </td>
            <td><b><asp:label ForeColor="Red" Text="*" runat="server" /> Tipo portugués</b> <asp:TextBox ID="txttipo_portugues" MaxLength="25" runat="server" />
                    <asp:RequiredFieldValidator ValidationGroup="tiposobras" ControlToValidate="txttipo_portugues" ErrorMessage="Tipo portugués obligatorio" Display="None" runat="server" />
                    <asp:RegularExpressionValidator ValidationGroup="tiposobras" ControlToValidate="txttipo_portugues" ErrorMessage="Tipo portugués inválido" Display="None" ValidationExpression="[^'<>]*" runat="server" />
            </td>
        </tr>
        </asp:Panel>
        <asp:Panel ID="pnlnohayregistros" Visible="false" runat="server">
                <span style="color:red"> No hay registros</span>
    </asp:Panel>
</EmptyDataTemplate>

I want to reference the controls in emptydatatemplate.

I have this code in rowdatabound:

If e.Row.RowType = DataControlRowType.EmptyDataRow Then
        Dim fi As New FileInfo(Server.MapPath("../../Comun/Varios/default1.aspx"))
        strcondicion = ViewState("condicion" & strtabla)
        If strcondicion IsNot Nothing Then
            Dim inttotalregistros As Integer
            inttotalregistros = Numeromaximoregistros(strtabla, True)
            s.Caption = "0 de " & Format(inttotalregistros, "n0") & " " & IIf(inttotalregistros <> 1, "registros", "registro")
            If strtabla = "tiposobras" Then
                e.Row.Cells(0).Controls(1).FindControl("pnlnohayregistros").Visible = False
                e.Row.Cells(0).Controls(1).FindControl("pnlanadir").Visible = True
            End If
        Else
            cphcontenido.FindControl("pnlbusqueda" & strtabla).Visible = False
            s.Caption = ""
        End If
End If

But it doesn't work. It seems it doesn't reference well.

Any ideas?

Thanks in advance.

I have in a gridview:

<EmptyDataTemplate>
    <asp:Panel ID="pnlanadir" runat="server">
        <tr>
            <td><b><asp:label ForeColor="Red" Text="*" runat="server" /> Tipo español</b> <asp:TextBox ID="txttipo_espanol" MaxLength="25" runat="server" />
                    <asp:LinkButton ID="lnkanadir" ValidationGroup="tiposobras" Text="Añadir" OnCommand="anadir" runat="server" />
                    <asp:RequiredFieldValidator ValidationGroup="tiposobras" ControlToValidate="txttipo_espanol" ErrorMessage="Tipo español obligatorio" Display="None" runat="server" />
                    <asp:RegularExpressionValidator ValidationGroup="tiposobras" ControlToValidate="txttipo_espanol" ErrorMessage="Tipo español inválido" Display="None" ValidationExpression="[^'<>]*" runat="server" />

            </td>
            <td><b><asp:label ForeColor="Red" Text="*" runat="server" /> Tipo inglés</b> <asp:TextBox ID="txttipo_ingles" MaxLength="25" runat="server" />
                    <asp:RequiredFieldValidator ValidationGroup="tiposobras" ControlToValidate="txttipo_ingles" ErrorMessage="Tipo inglés obligatorio" Display="None" runat="server" />
                    <asp:RegularExpressionValidator ValidationGroup="tiposobras" ControlToValidate="txttipo_ingles" ErrorMessage="Tipo inglés inválido" Display="None" ValidationExpression="[^'<>]*" runat="server" />
            </td>
            <td><b><asp:label ForeColor="Red" Text="*" runat="server" /> Tipo francés</b> <asp:TextBox ID="txttipo_frances" MaxLength="25" runat="server" />
                    <asp:RequiredFieldValidator ValidationGroup="tiposobras" ControlToValidate="txttipo_frances" ErrorMessage="Tipo francés obligatorio" Display="None" runat="server" />
                    <asp:RegularExpressionValidator ValidationGroup="tiposobras" ControlToValidate="txttipo_frances" ErrorMessage="Tipo francés inválido" Display="None" ValidationExpression="[^'<>]*" runat="server" />
            </td>
            <td><b><asp:label ForeColor="Red" Text="*" runat="server" /> Tipo portugués</b> <asp:TextBox ID="txttipo_portugues" MaxLength="25" runat="server" />
                    <asp:RequiredFieldValidator ValidationGroup="tiposobras" ControlToValidate="txttipo_portugues" ErrorMessage="Tipo portugués obligatorio" Display="None" runat="server" />
                    <asp:RegularExpressionValidator ValidationGroup="tiposobras" ControlToValidate="txttipo_portugues" ErrorMessage="Tipo portugués inválido" Display="None" ValidationExpression="[^'<>]*" runat="server" />
            </td>
        </tr>
        </asp:Panel>
        <asp:Panel ID="pnlnohayregistros" Visible="false" runat="server">
                <span style="color:red"> No hay registros</span>
    </asp:Panel>
</EmptyDataTemplate>

I want to reference the controls in emptydatatemplate.

I have this code in rowdatabound:

If e.Row.RowType = DataControlRowType.EmptyDataRow Then
        Dim fi As New FileInfo(Server.MapPath("../../Comun/Varios/default1.aspx"))
        strcondicion = ViewState("condicion" & strtabla)
        If strcondicion IsNot Nothing Then
            Dim inttotalregistros As Integer
            inttotalregistros = Numeromaximoregistros(strtabla, True)
            s.Caption = "0 de " & Format(inttotalregistros, "n0") & " " & IIf(inttotalregistros <> 1, "registros", "registro")
            If strtabla = "tiposobras" Then
                e.Row.Cells(0).Controls(1).FindControl("pnlnohayregistros").Visible = False
                e.Row.Cells(0).Controls(1).FindControl("pnlanadir").Visible = True
            End If
        Else
            cphcontenido.FindControl("pnlbusqueda" & strtabla).Visible = False
            s.Caption = ""
        End If
End If

But it doesn't work. It seems it doesn't reference well.

Any ideas?

Thanks in advance.

Share Improve this question edited Jan 18 at 21:16 marc_s 756k184 gold badges1.4k silver badges1.5k bronze badges asked Jan 18 at 13:06 volar.2016volar.2016 133 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 0

In a standard GridView, then "auto generated" columns, or bound field columns use the .cells() collection.

However, for any templated columns (in any of the templates such as header template, or footer template), then you have to use .FindControl method of that given row.

Also, keep in mind that the EmptyDataRow does NOT render nor show if there is data in the GridView.

So, take this example where we have a search button to fill out the GridView. If the user enters a search that returns no rows, then the empty row template will render but we also want to show in that empty template the search used (that presumably failed). As noted, the empty template does not render unless you feed the GridView a data source that returns no rows.

And VERY important, in the RowDataBound event, there will NEVER be a EmptyDataRow, nor will such code run unless the data source used returns no rows to the GridView.

Markup:

    <div style="float:left">
        <h4>Search for City</h4>
        <asp:TextBox ID="txtSearch" runat="server"></asp:TextBox>
    </div>
    <div style="float:left;margin-left:25px;margin-top:18px">
        <asp:Button ID="cmdSearch" runat="server" 
            Text="Search"
            CssClass="btn myshadow"
            OnClick="cmdSearch_Click"
            />
    </div>

    <%-- start a new line in markup with some height to 
        push down the GV a few lines (20px)--%>

    <div style="clear:both;height:20px">
    </div>

    <asp:GridView ID="GVHotels" runat="server" AutoGenerateColumns="False"
        DataKeyNames="ID" CssClass="table table-hover"
        ShowHeaderWhenEmpty="true"
        Width="50%"
        OnRowDataBound="GVHotels_RowDataBound"
        >
        <Columns>
            <asp:BoundField DataField="FirstName" HeaderText="FirstName" />
            <asp:BoundField DataField="LastName" HeaderText="LastName" />
            <asp:BoundField DataField="City" HeaderText="City" />
            <asp:BoundField DataField="HotelName" HeaderText="Hotel" />
            <asp:BoundField DataField="Description" HeaderText="Description" />
        </Columns>

        <EmptyDataTemplate>
            <h4>No data found</h4>
            <asp:Label ID="lblFilter" runat="server" 
                Text=""></asp:Label>
        </EmptyDataTemplate>
    </asp:GridView>

And code behind:

Protected Sub GVHotels_RowDataBound(sender As Object, e As GridViewRowEventArgs)

    If e.Row.RowType = DataControlRowType.DataRow Then

    End If

    If e.Row.RowType = DataControlRowType.EmptyDataRow Then
        Debug.Print("code for empty row")
        ' get/grab label in emptry row
        Dim lblFilter As Label = e.Row.FindControl("lblFilter")
        lblFilter.Text = $"Filter for City was {txtSearch.Text}"
    End If

End Sub

Protected Sub cmdSearch_Click(sender As Object, e As EventArgs)

    Dim strSQL As String =
        "SELECT * FROM tblHotels
        WHERE City = @City
        AND Description is not null
        ORDER BY HotelName"

    Dim cmdSQL As New SqlCommand(strSQL)

    If txtSearch.Text <> "" Then
        cmdSQL.Parameters.Add("@City", SqlDbType.NVarChar).Value = txtSearch.Text
    Else
        cmdSQL.CommandText =
            "SELECT * FROM tblHotels
            WHERE Description is not null
            ORDER BY HotelName"
    End If

    GVHotels.DataSource = MyRstP(cmdSQL)
    GVHotels.DataBind()

End Sub

The result for a search is thus this:

However, to trigger the empty template (and the code in the row data bound) we enter an invalid search, and the result is now this:

So, keep in mind that for any of the template rows, the cell's collection is only for data bound columns. For standard controls, you have to use .FindControl. And you do not need/want to use .FindControl inside of a cell() reference, as it is not required. .FindControl will pick up any control inside of the empty template row, just like you would do the same for the DataRow template.

And keep in mind that the empty template is ONLY rendered if the data source returns no rows. If data exists, then the empty row template will not render, and thus code inside of the rowDataBound event will not see the empty row template. As a result, no need exists to try and set such controls as "visible", since the template will ONLY render if the GridView is sent a data source with no rows.

发布评论

评论列表(0)

  1. 暂无评论