gridview中的条件超链接字段? ASP.net

时间:2009-11-13 11:59:20

标签: asp.net gridview

我将一个超链接域放入gridview,但我发现有时候我希望它可以点击,有时候不是,这取决于数据。

如果项目是A或B,我想要一个bibble.aspx?id = 123的超链接,否则我只想要纯文本。

最好的方法是什么?我应该使用其他类型的字段吗?

3 个答案:

答案 0 :(得分:3)

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" 
     onrowdatabound="GridView1_RowDataBound">
    <Columns>
        <asp:TemplateField HeaderText="Column to check">
            <ItemTemplate>
                <asp:Label runat="server" ID="lblCrtl" Text='<%# Eval("Name") %>' />
            </ItemTemplate>
        </asp:TemplateField>

        <asp:TemplateField HeaderText="Column Name">

        </asp:TemplateField>
    </Columns>
</asp:GridView>



protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        // you may need to do this if you didnt use templatefield;
        // string val = e.Row.Cells[<column index>].Text;
        // if its templatefield do following;
        Label lbl = e.Row.FindControl("lblCrtl") as Label; 

        Button btn = null;

        if (lbl.Text == "Car") // put your own value to check, my case it was Car
        {
            btn = new Button();
            btn.Text = "Test";
            e.Row.Cells[1].Controls.Add(btn); // cells<column index that control will be added>
        }
    }
}

答案 1 :(得分:1)

使用模板字段和超链接控件可能会更好,NavigateUrl由三元运算符确定。

答案 2 :(得分:0)

您需要处理GridView的RowDataBound事件。

这个link演示了如何使用RowDataBound事件在GridView控件中显示之前修改数据源中字段的值。