Navigation

Search

Categories

On this page

Conditional GridView Cell Formatting

Archive

Blogroll

Disclaimer
The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

RSS 2.0 | Atom 1.0 | CDF

Send mail to the author(s) E-mail

Total Posts: 112
This Year: 50
This Month: 0
This Week: 0
Comments: 0

Sign In

 Monday, July 09, 2007
Monday, July 09, 2007 8:31:48 AM (Eastern Standard Time, UTC-05:00) ( )

This code sample shows how to either show or make invisible, a checkbox in each row of the Gridview, along with making text conditional, based on certain criteria. In this case, if the Postal code starts with a non-numeric character, we change it to "Alt Text", and we set the Visible property of the checkbox in that row to "False"

<%@ Import Namespace="System.Drawing" %>
<script language="VB" Runat="server">
Sub DataCheck(ByVal sender As Object, ByVal e As GridViewRowEventArgs)
Dim chkExp as CheckBox
If e.Row.RowType = DataControlRowType.DataRow Then
Dim sCode as String=e.Row.Cells(7).text
If Not isNumeric(sCode.Substring(1,1)) Then
e.Row.Cells(7).text="<i style='color:red'>(Alt Text)</i>"
        chkExp= CType(e.row.FindControl("ck1"), Checkbox)
        chkExp.Visible="False"
End If
End If
End Sub    
</script>
<html>
<head runat="server">
    <title>Conditional GridView Cell Formatting</title>
</head>
<body>
<form id="form1" Runat="server">
<asp:GridView OnRowDataBound="DataCheck" AutoGenerateColumns="False"
    DataSourceID="SqlDataSource1" ID="GridView2" runat="Server">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="ck1" runat="server"></asp:CheckBox>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="FirstName" HeaderText="First" />
<asp:BoundField DataField="LastName" HeaderText="Last" />
<asp:BoundField DataField="Title" HeaderText="Title" />
<asp:BoundField DataField="Address" HeaderText="Address" />
<asp:BoundField DataField="City" HeaderText="City" />
<asp:BoundField DataField="Region" HeaderText="Region" />
<asp:BoundField DataField="PostalCode" HeaderText="PostalCode" />
<asp:BoundField DataField="country" HeaderText="country" />
</Columns>
<HeaderStyle BackColor="Blue" Font-Bold="True" ForeColor="White" />
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>"
SelectCommand="Select FirstName, LastName, Title, Address, City, Region, PostalCode, country from Employees">
</asp:SqlDataSource>
        </form>
    </body>
</html>