【发布时间】:2009-11-13 11:59:20
【问题描述】:
我将一个超链接字段放入一个网格视图中,但我意识到有时我希望它可以点击,有时却不能,具体取决于数据。
如果项目是 A 或 B,我想要一个指向 bibble.aspx?id=123 的超链接,否则我只想要纯文本。
最好的方法是什么?我应该为此使用其他类型的字段吗?
【问题讨论】:
我将一个超链接字段放入一个网格视图中,但我意识到有时我希望它可以点击,有时却不能,具体取决于数据。
如果项目是 A 或 B,我想要一个指向 bibble.aspx?id=123 的超链接,否则我只想要纯文本。
最好的方法是什么?我应该为此使用其他类型的字段吗?
【问题讨论】:
<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>
}
}
}
【讨论】:
使用模板字段和超链接控件可能会更好,NavigateUrl 由三元运算符确定。
【讨论】:
您需要处理 GridView 的 RowDataBound 事件。
此link 演示了如何使用 RowDataBound 事件在数据源中的字段值显示在 GridView 控件中之前对其进行修改。
【讨论】: