473,614 Members | 2,328 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Conditionally Change a DataGrid Column Value...

There are times when you will need to highlight or otherwise modify
the contents of a particular DataGrid row-column value based upon the
value in the column. In this example we will select the CompanyName,
ContactName, and ContactTitle columns from the Customers table in the
Northwind database. Whenever the value of ContactTitle equals "Owner"
we will change the font color to red.

We can do this by using an ItemTemplate where we have complete control
over the presentation of the data. We use BoundColumns for the first
two columns and an ItemTemplate for the ContactTitle column. Within
the ItemTemplate we call a function named "ChangeColo rs" and pass it
the value of the column. This is what the line <%#
ChangeColor(Con tainer.DataItem ("ContactTitle" )) %> does. We are
getting the value of ContactTitle and passing it to the ChangeColor
function which appears in our code-behind page.

<%@ Page Language="vb"
Src="/Portals/57ad7180-c5e7-49f5-b282-c6475cdb7ee7/CondDataGrid.as px.vb"
Codebehind="Con dDataGrid.aspx. vb" Inherits="CondD ataGrid"
AutoEventWireup ="false" %>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title>CondData Grid</title>
<meta content="Micros oft Visual Studio.NET 7.0" name=GENERATOR>
<meta content="Visual Basic 7.0" name=CODE_LANGU AGE>
<meta content=JavaScr ipt name=vs_default ClientScript>
<meta content=http://schemas.microso ft.com/intellisense/ie5
name=vs_targetS chema>
</head>
<body MS_POSITIONING= "GridLayout ">
<form id=Form1 method=post runat="server">
<asp:DataGrid ID="dataGrid"
AutoGenerateCol umns = "False"
Runat="server">
<Columns>
<asp:BoundColum n HeaderText="Com pany Name" DataField="Comp anyName"
/>
<asp:BoundColum n HeaderText="Con tact Name" DataField="Cont actName"
/>

<asp:TemplateCo lumn HeaderText="Con tact Title">
<ItemTemplate >
<%# ChangeColor(Con tainer.DataItem ("ContactTitle" )) %>
</ItemTemplate>
</asp:TemplateCol umn>
</Columns>
</asp:DataGrid>
</form>
</body>
</html>
Most of the code-behind file is the usual data access code to get our
resultset. At the bottom of the file, color-coded in blue, is the
ChangeColor function. As you can see, all it is doing is checking for
"Owner" in the value passed in. If the value is "Owner" then we put
font tags around the value and send it back. Otherwise, if it was not
"owner", we just send the value back to the caller to be rendered as
is.

Imports System
Imports System.Data
Imports System.Data.Sql Client
Imports System.Configur ation

Public Class CondDataGrid
Inherits System.Web.UI.P age

Protected WithEvents dataGrid As System.Web.UI.W ebControls.Data Grid

Private Sub Page_Load(ByVal sender As System.Object, ByVal e As
System.EventArg s) Handles MyBase.Load
Dim sqlConn As SqlConnection
Dim sqlCmd As SqlCommand

Try
sqlConn = New SqlConnection(C onfigurationSet tings.AppSettin gs("ConnectionS tring"))
sqlCmd = New SqlCommand("SEL ECT TOP 10 * FROM Customers",
sqlConn)
sqlConn.Open()
dataGrid.DataSo urce = sqlCmd.ExecuteR eader()
dataGrid.DataBi nd()
Catch ex As Exception
Response.Write( ex.ToString() & "<br>")
Finally
sqlConn.Close()
sqlConn.Dispose ()
End Try
End Sub

Function ChangeColor(val ue)
If value = "Owner" Then
ChangeColor="<f ont color='red'>" & value & "</font>"
Else
ChangeColor = value
End If
End Function

End Class
I hope you have seen how easy it is to modify the appearance of a
DataGrid colum based upon its value. You can, of course, base your
modifications on the value of any column you want.


AMBER [MCSD.NET MCAD.NET] http://www.dedicatedsolutions.co.uk
Nov 17 '05 #1
0 2644

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
3022
by: PeterZ | last post by:
G'day, After doing much searching and pinching bits of ideas from here there and everywhere I came up with a fairly 'clean' solution of including a comboBox into a dataGrid column. You can download a fully working C# sample with the Northwind.mdb here: www.insightgis.com.au/web/stuff/DataGridCombo.zip
0
390
by: Amber | last post by:
There are times when you will need to highlight or otherwise modify the contents of a particular DataGrid row-column value based upon the value in the column. In this example we will select the CompanyName, ContactName, and ContactTitle columns from the Customers table in the Northwind database. Whenever the value of ContactTitle equals "Owner" we will change the font color to red. We can do this by using an ItemTemplate where we have...
0
1501
by: Dan Hartshorn | last post by:
VS.NET 2003, C#, Windows Server 2003. I have a datagrid and I want the last column to be either an EditCommandColumn or a template column, depending on a value I have. The value changes for each row. So some rows will have an EditCommandColumn, others just a text message in the last column. Is this possible? I am already using the ItemDataBound method to perform some function on each row, but I can't seem to change the datagrid's column...
2
1336
by: Olav Tollefsen | last post by:
I'm creating an ASP.NET e-commerce web site and I have to conditionally (depending on site / user settings) display prices either excluding or including tax. Prices are typically read from a database (where also the tax rates are stored) various places in the code and typically (but now always) the values are returned in DataSets which are bound to controls and displayed to the user. What would be the most elegant way to implement the...
4
3346
by: Rob Kroese | last post by:
I've got a form with a datagrid that displays a list of items, along with several textboxes, comboboxes, etc., that display the details for the selected item. The columns in the datagrid and the "details" controls are both bound to fields in a dataview called dvItems. The dataview is a subset of a datatable called dtItems, which is simply a copy of all the data in a table called Items. The idea is to allow the user to edit an item in...
4
10693
by: Roger | last post by:
I have a datagrid and would like to know what even fires when a cell is changed? I want to know when the user changes a cell and moves to the next. I have some code that needs to be done to make sure entry is valid? Thanks, Rog
2
12582
by: simon | last post by:
hello, new to vb.net, have a few questions about DataGrid. I have a dataGrid that is working pulling a dataset back from a stored proc and binding to the datagrid for display the datagrid's first column is a textbox(TemplateColumn), the other 3 columns are just display(BoundColumn). (1) if the value of the textbox is 0, then i'd like to change it null, so the box is empty
2
2122
by: Billy | last post by:
Change DataGrid EditControl On Data Value Hi, I have a datagrid, and on editing, I want to change the control in the third colunm based on the value of the first column. The value in the first column can only be either "Text" or "Image", which is selcted in a dropdown list.
2
1552
by: msrahul | last post by:
HI ALL Plz Help Me. I have a datagrid with a few colums. One column is conaining 1's or 0's. Its like a flag column. It either has 0 or 1. Now what i need is that if any row has 1 in this column than another column named "Status" (of that row) should have a dropdown list conatining 4 items. This column can have values Checked,NotChecked,InProcess,Pending in the rows for which the flag column has 0's. But when the Flag value is 1 then this...
0
8142
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8591
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8294
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8444
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7115
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6093
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5549
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4058
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4138
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.