根据转发器中隐藏字段的值显示/隐藏文件上传控件

时间:2013-08-08 07:04:52

标签: asp.net file-upload repeater hidden-field

我在ASP.Net页面上有一个转发器控件。它有一个复选框,标签,文件上传控件和3个隐藏字段。我想隐藏/显示基于其中一个隐藏字段的值的文件上传控件。

以下是转发器的ItemDataBound事件的代码段。

protected void rptChecks_ItemDataBound (object sender, RepeaterItemEventArgs e)
{ 
    HiddenField hdID = (HiddenField)e.Item.FindControl("hdnCheckID");
    HiddenField hdDocOpt = (HiddenField)e.Item.FindControl("hdnDocOption");
    FileUpload fileCheck = (FileUpload)e.Item.FindControl("fileDocument");

    if ( Convert.ToInt32(hdDocOpt.Value) == 0 || Convert.ToInt32(hdDocOpt.Value) == 1)
            fileCheck.Visible = true;
        else
            fileCheck.Visible = false;
}

这是标记代码

<asp:Repeater ID="rptChecks" runat="server" 
                onitemdatabound="rptChecks_ItemDataBound">
                <HeaderTemplate>
                    <table>
                        <tr>
                            <th>
                                &nbsp;
                            </th>
                            <th>
                                &nbsp;
                            </th>
                            <th>
                                &nbsp;
                            </th>
                        </tr>
                </HeaderTemplate>
                <ItemTemplate>
                    <tr>
                        <td>
                            <asp:CheckBox ID="chk" runat="server" />
                        </td>
                        <td style="padding-left: 10px">
                            <asp:Label ID="lblCheck" runat="server" Text="<%#Bind('Name') %>"></asp:Label>
                        </td>
                        <td style="padding-left: 10px">
                            <asp:HiddenField ID="hdnDocOption" runat="server" Value="<%#Bind('DocumentOption') %>" />
                            <asp:HiddenField ID="hdnCheckID" runat="server" Value="<%#Bind('ID') %>" />
                            <asp:FileUpload ID="fileDocument" runat="server" />
                        </td>
                    </tr>
                </ItemTemplate>
                <FooterTemplate>
                    </table>
                </FooterTemplate>
            </asp:Repeater>

我该怎么做?

错误:错误发生,因为对象引用未设置为if条件的对象实例。

1 个答案:

答案 0 :(得分:0)

错误是当您尝试在HeaderTemplate中查找控件并使用该值时,在这种情况下,值始终为null。我们应该在ItemTemplate中找到如下控件:

protected void rptChecks_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
    if (e.Item.ItemType == ListItemType.AlternatingItem || e.Item.ItemType == ListItemType.Item)
    {
        HiddenField hdID = (HiddenField)e.Item.FindControl("hdnCheckID");

        HiddenField hdDocOpt = (HiddenField)e.Item.FindControl("hdnDocOption");

        FileUpload fileCheck = (FileUpload)e.Item.FindControl("fileDocument");

        if (Convert.ToInt32(hdDocOpt.Value) == 0 || Convert.ToInt32(hdDocOpt.Value) == 1)
            fileCheck.Visible = true;
        else
            fileCheck.Visible = false;
    }
}