您可以使用 itemDataBound 事件进行所有条件格式设置(颜色、隐藏等)。但是,您的示例标记似乎没有控件 - 您希望对该信息进行控件。并且该控件应该具有某种可以在代码中引用的“id”或名称。
但是,由于您没有提供太多标记?然后,我为单元格集合和您可能拥有的控件提供了一个示例。
所以,假设我们有这个简单的网格视图。注意最后两个字段都是城市,一个是绑定字段(通常很常见),另一个是标签(但可以是文本框或几乎任何 asp.net 控件)。
<asp:GridView ID="GridView1" runat="server" CssClass="table-hover" AutoGenerateColumns="False" DataKeyNames="ID">
<Columns>
<asp:BoundField DataField="ID" HeaderText="ID" InsertVisible="False" ReadOnly="True" SortExpression="ID" />
<asp:BoundField DataField="FirstName" HeaderText="FirstName" SortExpression="FirstName" />
<asp:BoundField DataField="LastName" HeaderText="LastName" SortExpression="LastName" />
<asp:BoundField DataField="HotelName" HeaderText="HotelName" SortExpression="HotelName" />
<asp:BoundField DataField="City" HeaderText="City" SortExpression="City" />
<asp:TemplateField HeaderText ="City2">
<ItemTemplate>
<asp:Label ID="lblCity" runat="server" Text = '<%# Eval("City") %>' >'<"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
好的,在页面加载时,我们使用以下代码加载上面的网格:
protected void Page_Load(object sender, System.EventArgs e)
{
if (IsPostBack == false)
LoadGrid();
}
public void LoadGrid()
{
using (SqlCommand cmdSQL = new SqlCommand("SELECT ID, FirstName, LastName, HotelName, City from tblHotels", new SqlConnection(My.Settings.TEST3)))
{
cmdSQL.Connection.Open();
GridView1.DataSource = cmdSQL.ExecuteReader;
GridView1.DataBind();
}
}
好的,我们得到这个输出:
现在,让我们根据城市来隐藏一列。我们说 City = "Edmonton",我们隐藏了控件。
所以,你使用 itemData 绑定事件。
我在这个示例中既有绑定字段(单元格)集合隐藏示例,也有关于如何使用模板控件(查找控件)执行此操作的示例。
所以,代码是这样的:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
GridViewRow gvRow = e.Row;
// hide a Bound field
TableCell f = gvRow.Cells(4);
if (f.Text == "Edmonton")
f.Style("Display") = "none";
// hide a templated control
Label lbl = gvRow.FindControl("lblCity");
if (lbl.Text == "Edmonton")
lbl.Style("Display") = "none";
}
}
现在输出是这样的: