【问题标题】:ASP.NET DataGrid Select ItemTemplate By ConditionASP.NET DataGrid 按条件选择 ItemTemplate
【发布时间】:2014-02-25 01:53:58
【问题描述】:

这是我的数据网格:

 <asp:DataGrid ID="dgAll" runat="server"  AutoGenerateColumns="false">
            <Columns>
                <asp:TemplateColumn>
                    <ItemTemplate>
                        <asp:TextBox ID="txtB" runat="server" Text='<%#Eval("Value")%>' ></asp:TextBox>
                    </ItemTemplate>
                    <ItemTemplate>
                        <asp:DropDownList ID="drdL" runat="server" DataSource='<%#GetComboData(Eval("Value"))%>'></asp:DropDownList>
                    </ItemTemplate>
                </asp:TemplateColumn>
            </Columns>
        </asp:DataGrid>

如您所见,我有一个 TextBox 和一个 DropDownList,但我在每一行中只需要其中一个,所以问题是如何按条件选择 ItemTemplate,假设 Eval("Type") == "TextBox") 我需要 TextBox,如果 Eval("Type") == "DropDown")我需要在那一行中的下拉菜单。有人对此有任何想法吗?

【问题讨论】:

  • 您可以使用单个模板字段并根据条件隐藏显示控件。

标签: asp.net datagrid .net-4.0


【解决方案1】:

您可以在同一个模板字段中使用这两个控件并使用如下代码

<asp:DataGrid ID="dgAll" runat="server"  AutoGenerateColumns="false">
    <Columns>
        <asp:TemplateColumn>
            <ItemTemplate>
                 <asp:TextBox ID="txtB" runat="server" Text='<%#Eval("Value")%>'
                      Visible ='<%# Eval("Type").ToString()=="TextBox"%'>
                 </asp:TextBox>
                 <asp:DropDownList ID="drdL" runat="server" 
                      DataSource='<%#GetComboData(Eval("Value"))%>'
                      Visible ='<%# Eval("Type").ToString()!="TextBox"%'>
                 </asp:DropDownList>
            </ItemTemplate>
        </asp:TemplateColumn>
    </Columns>
</asp:DataGrid>

【讨论】:

  • 谢谢,只是一个更新:我认为 Visible 而不是 Visibility。
  • @SaeidAlizade 谢谢,是的,我正在更新我的答案。
【解决方案2】:

你为什么要用一对asp:TemplateColumn,你也可以这样用,

<asp:TemplateColumn>
    <ItemTemplate>
     <asp:TextBox ID="txtB" runat="server" Text='<%#Eval("Value")%>' Visible="false" ></asp:TextBox>
     <asp:DropDownList ID="drdL" runat="server" Visible="false"></asp:DropDownList>
    </ItemTemplate>
 </asp:TemplateColumn>

在 Grid 的 ItemDataBound 事件中

protected void dgAll_ItemDataBound(object sender, DataGridItemEventArgs e)
        {
            if (e.Item.ItemIndex == -1) return;

            if (e.Item.ItemIndex % 2 == 0)
                e.Item.FindControl("drdL").Visible = true;
            else
                e.Item.FindControl("txtB").Visible = true;
        }

【讨论】:

    猜你喜欢
    • 2011-01-20
    • 1970-01-01
    • 1970-01-01
    • 2011-12-22
    • 2023-03-13
    • 1970-01-01
    • 1970-01-01
    • 2013-03-12
    • 1970-01-01
    相关资源
    最近更新 更多