对Gridview的绑定字段运行回调

本文关键字:运行 回调 字段 绑定 Gridview | 更新日期: 2023-09-27 18:20:53

我想处理从Gridview的数据库中检索的字段,以检查其中的信息是否是超链接。如果是,我想从中生成一个链接,否则就把它作为原始文本。目前,Gridview中的字段看起来像:

    <asp:TemplateField HeaderText="Reference">
        <EditItemTemplate>
            <asp:TextBox ID="txtReference" runat="server" Text='<%# Bind("Reference") %>'></asp:TextBox>
        </EditItemTemplate>
        <ItemTemplate>
            <asp:Label ID="Label3" runat="server" Text='<%# Bind("Reference") %>'></asp:Label>
        </ItemTemplate>
    </asp:TemplateField>

我尝试修改ItemTemplate的"Text"属性中的内容,但无论我输入了什么,我都会在页面加载时出错。如何根据此字段中绑定的特定信息动态修改发送到浏览器的内容?

非常感谢!

对Gridview的绑定字段运行回调

如果绑定的文本符合正确的URL,则可以在TemplateField中同时使用LabelHyperLink,并显示HyperLink(并隐藏Label)。您可以使用codeehind函数来完成此操作,该函数向Visible属性返回bool,类似于以下内容:

ASP.NET

<asp:TemplateField HeaderText="Reference"> 
    <ItemTemplate> 
        <asp:Label ID="lbl" runat="server" Visible='<%# IsTextHyperlink(Eval("Reference")) %>' Text='<%# Bind("Reference") %>'/>
        <asp:HyperLink ID="hl" runat="server" Visible='<%# !IsTextHyperlink(Eval("Reference")) %>' NavigateUrl='<%# Bind("Reference") %>'/>
    </ItemTemplate> 
</asp:TemplateField> 

C#

protected bool IsTextHyperlink(object text)
{
    bool IsHyperLink = false;
    ...
    // check if text qualifies as hyperlink
    ...
    return IsHyperLink ; 
}

请注意,使用类型object作为IsHyperLink函数参数,因为Eval()返回一个对象,只需将其强制转换为String即可。

您还需要将HyperLinkText属性格式化为有意义的内容。

您可以使用类似的GridView.OnRowDataBound方法

protected virtual void yourGV_OnRowDataBound(object sender, gridViewRowEventArgs e)
{
   GridViewRow row = e.Row 
}

在其中,您可以使用FindControl访问行中的控件。

我通过在TemplateField中同时使用LabelHyperLink解决了这个问题,如果绑定的文本符合正确的URL,则显示HyperLink(并隐藏Label)。

以下ASP.NET设置了要输出的潜在HTML:

ASP.NET

<asp:TemplateField HeaderText="Reference"> 
    <ItemTemplate>
                <asp:Label ID="lblReference" runat="server" Visible='<%# !isTextHyperlink(Eval("Reference")) %>' Text='<%# Bind("Reference") %>'/>
                <asp:HyperLink ID="hlReference" runat="server" Visible='<%# isTextHyperlink(Eval("Reference")) %>' Text='<%# Bind("Reference") %>' NavigateUrl='<%# Bind("Reference") %>'/>
    </ItemTemplate> 
</asp:TemplateField> 

我在页面"codebehind"中添加了一个函数,如下所示:

C#

protected bool isTextHyperlink(object refobj)
{
    string refstring = refobj.ToString();
    try
    {
        Uri uri = new Uri(refstring);
        return Uri.CheckSchemeName(uri.Scheme);
    }
    catch
    {
        // not a valid uri (that Uri can construct with)
        return false;
    }
}

非常感谢Brisles的建议。