473,698 Members | 1,877 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

updating GridView cell background color

I understand how to connect a SqlDataSource to a GridView and have a nice
data-connected, paginated web page generated with virtually no coding.
Starting from that base, I would like to add an extra column to the GridView
and do two things: for each row, based on the value of another column, insert
a string in the new column cell and set the background color of the new
column cell. Suggested approaches would be appreciated.
Aug 22 '07 #1
10 7967
Hi Michael,
you can create handler for RowDataBound event of your GridView. In this
handler you will be able to access and modify cells and data of your current
row.

protected void myGridView_OnRo wDataBound(obje ct sender, GridViewRowEven tArgs
e)
{
if (e.Row.RowType = DataGridRowType .DataRow)
{
// e.Row.Cells contains collection of server side td elements, you can
fill
// text property or work with collection of controls inside this element
e.Row.Cells[INDEX_OF_YOUR_C OLUMN].Text = EvalMyField(e.R ow.DataItem );
// DataItem contains source of data for this row, it is object used by data
source to fill your row
// you can also modify css style for your elelment
e.Row.Cells[INDEX_OF_YOUR_C OLUMN].Attributes.Add ("style", ".......");
}
}

Regards,
Ladislav

"michael sorens" wrote:
I understand how to connect a SqlDataSource to a GridView and have a nice
data-connected, paginated web page generated with virtually no coding.
Starting from that base, I would like to add an extra column to the GridView
and do two things: for each row, based on the value of another column, insert
a string in the new column cell and set the background color of the new
column cell. Suggested approaches would be appreciated.
Aug 22 '07 #2
Splendid! I had to test for DataControlRowT ype.DataRow rather than
DataGridRowType .DataRow, but that essentially did most of what I needed.

Now how do I position the new column as the right-most column?
I first tried adding a new column of type Template in the visual designer.
This new column became the first column. I tried the same thing
programmaticall y by calling gridView.Column s.Add() in the PageLoad handler
and it also became the first column. I then switched to Columns.Insert( ) but
in the PageLoad handler the binding has not yet occurred, hence column count
is still 0. When the binding occurs, the columns are added to the right,
again leaving my new column as the left-most. What event handler would give
me access to the GridView after the columns have been loaded so I can then
add my new column where I want?

Aug 22 '07 #3
Hi Michael,

I'm glad that you've solved your first issue.

For the second question, have you tried to add the column in GridView's
DataBound event? In this event, the data has been bound and those columns
are generated, therefore you can add your column to the right-most.

Please let me know the result. Thanks.
Regards,
Walter Wang (wa****@online. microsoft.com, remove 'online.')
Microsoft Online Community Support

=============== =============== =============== =====
When responding to posts, please "Reply to Group" via your newsreader so
that others may learn and benefit from your issue.
=============== =============== =============== =====

This posting is provided "AS IS" with no warranties, and confers no rights.

Aug 23 '07 #4
I had tried the DataBound event because that seemed to be the right place.
But the results were the same. To see why, here is the output of a test
program that includes a GridView with 5 columns from design-time where I
attempt to add 3 more columns at run-time.

Curiousities:
(1) The column count shows 0, not 5, upon entering the DataBound event
handler.
(2) After adding the 3 new columns, the column count is then 3, not 8, at
the conclusion of the event handler.
(3) The DataBound event is triggered twice so I had to add the
gridInitialized switch to prevent adding the columns again.
(4) The column count still shows 3 on the second pass through the DataBound
event handler, yet the grid displays with all 8 columns (the 3 new ones are
left-most).
With novice-like bravado I will say that it sure looks like the event is not
firing when it is supposed to!

=============== =============== =============== ====
ENTERING GridView_DataBo und: Column count=0, gridInitialized =False,
IsPostBack=Fals e
ENTERING AddCol[1]
LEAVING AddCol
ENTERING AddCol[2]
LEAVING AddCol
ENTERING AddCol[3]
LEAVING AddCol
LEAVING GridView_DataBo und: Column count=3, gridInitialized =True,
IsPostBack=Fals e
ENTERING GridView_DataBo und: Column count=3, gridInitialized =True,
IsPostBack=Fals e
LEAVING GridView_DataBo und: Column count=3, gridInitialized =True,
IsPostBack=Fals e
=============== =============== =============== ====

Here is the sample program:
=============== =============== =============== ====
public partial class _Default : System.Web.UI.P age
{
private int numDays = 3;
private DateTime firstDisplayDat e = new DateTime(2007, 1, 3);
private List<TemplateFi eldchartCol = new List<TemplateFi eld>();
private bool gridInitialized = false;

protected void GridView1_DataB ound(object sender, EventArgs e)
{
Out("ENTERING GridView_DataBo und: Column count=" + GridView1.Colum ns.Count
+ ", gridInitialized =" + gridInitialized + ", IsPostBack="+Is PostBack);
if (!gridInitializ ed && !IsPostBack)
{
for (int i = 0; i < numDays; i++) { AddCol(); }
gridInitialized = true;
}
setDates();
Out("LEAVING GridView_DataBo und: Column count=" + GridView1.Colum ns.Count
+ ", gridInitialized =" + gridInitialized + ", IsPostBack=" + IsPostBack);
}

private void setDates()
{
DateTime d = firstDisplayDat e;
foreach (TemplateField t in chartCol)
{
t.HeaderText = d.ToString("ddd MM/dd");
d = d.AddDays(1);
}
}

private void AddCol()
{
TemplateField tField = new TemplateField() ;
chartCol.Add(tF ield);
Out("ENTERING AddCol["+chartCol.Coun t+"]");
GridView1.Colum ns.Add(tField);
Out("LEAVING AddCol");
}

private void Out(string s)
{
Response.Write( s + "<br>\n");
}

}
=============== =============== =============== ====

Aug 23 '07 #5
(1) If I set AutoGenerateCol umns = false, I presume that means I have to
manually add *all* columns? If so, do you have a code sample showing how I
would add columns bound to the original select statement (which were created
automatically before)?
(2) In your sample CreateColumns, am I correct that you are showing one
bound field and one new field? So does this also need to manually create all
columns that were bound from the select statement? Is "au_lname" one of the
items in the select list? Not really sure how this relates to the original
behavior where the framework did everything for me...
Aug 24 '07 #6
(1) If I set AutoGenerateCol umns = false, I presume that means I have to
manually add *all* columns? If so, do you have a code sample showing how I
would add columns bound to the original select statement (which were created
automatically before)?
(2) In your sample CreateColumns, am I correct that you are showing one
bound field and one new field? So does this also need to manually create all
columns that were bound from the select statement? Is "au_lname" one of the
items in the select list? Not really sure how this relates to the original
behavior where the framework did everything for me...
Aug 24 '07 #7
Hi Michael,

(1) That's right, if AutoGenerateCol umns=False, you will need to manually
add all columns. You can do it declaratively in ASPX:

<asp:GridView ID="GridView1" runat="server"
AutoGenerateCol umns="False" DataKeyNames="a u_id"
DataSourceID="S qlDataSource1" OnDataBound="Gr idView1_DataBou nd"
OnDataBinding=" GridView1_DataB inding">
<Columns>
<asp:BoundFie ld DataField="au_i d" HeaderText="au_ id"
ReadOnly="True" SortExpression= "au_id" />
<asp:BoundFie ld DataField="au_l name" HeaderText="au_ lname"
SortExpression= "au_lname" />
</Columns>
</asp:GridView>
or you can add at runtime, in either case, you need to know the DataField
name ("au_id" and "au_lname" in above example).

It's possible to duplicate the functionality of how GridView's
AutoGenerateCol umns does, however, it's much complicated and I don't think
it's worth the effort doing this: the GridView needs to support various
data source such as DataSource controls (ObjectDataSour ce, SqlDataSource,
etc.) and IEnumerable data, you can take a look at GridView's code using
Reflector (http://www.aisto.com/roeder/dotnet/) if you're interested.

(2) Yes one field is a data bound field, just like above declarative
example shows.

As I explained above, I think if you need to set the
AutoGenerateCol umns=True, then I suggest you create a customized GridView
to add your custom columns; if you set AutoGenrateColu mns=False, then you
need to manually setup those columns in ASPX or code, but you need to know
the data field names.
Hope this helps.
Regards,
Walter Wang (wa****@online. microsoft.com, remove 'online.')
Microsoft Online Community Support

=============== =============== =============== =====
When responding to posts, please "Reply to Group" via your newsreader so
that others may learn and benefit from your issue.
=============== =============== =============== =====

This posting is provided "AS IS" with no warranties, and confers no rights.

Aug 27 '07 #8
This all seems rather more convoluted that it should need to be. After all,
the GridView.Column s collection has both an Add and an Insert method. I am
rather skeptical that you are, in essence, saying that either or both of
those and the DataBound event do not work as advertised.
Aug 27 '07 #9
Hi Michael,

I fully understand your concerns here. Please let me try to explain more
about the limitation here.

First, I apologize if my initial reply indicated that this could be done in
the DataBound event, which I later found out is not correct.

You are right that the columns has Insert and Add method, however, it's all
about the correct timing to call these methods if you need to position your
manually added column with the auto generated columns. Currently GridView
doesn't expose an appropriate event that could let you do this after the
columns are auto-generated, in other words, from the WebForm that hosts the
GridView, we don't have a correct event or time to call
GridView.Column s.Add or Insert.

On the other hand, the GridView internally does calls a virtual method
named 'CreateColumns' which can be overriden to append new columns after
the auto-generated columns.

I agree that this is a limitation of the GridView. I will make sure this
feature request is correctly forwarded to product team for future version's
improvement. In the meanwhile, you're also welcome to submit your feedback
at http://connect.microsoft.com/Main/co...ContentID=2220
which is monitored by product team directly and other community members can
also vote on the reqeust.

Thanks again for your great feedback!
Regards,
Walter Wang (wa****@online. microsoft.com, remove 'online.')
Microsoft Online Community Support

=============== =============== =============== =====
When responding to posts, please "Reply to Group" via your newsreader so
that others may learn and benefit from your issue.
=============== =============== =============== =====

This posting is provided "AS IS" with no warranties, and confers no rights.

Aug 28 '07 #10

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

Similar topics

1
3771
by: Michael | last post by:
How can I use onclick to change a table cell background color. I know I can use this.className=? to change the classname. But then I would have to put the code into every single table cell. I read once about using a collection method. Lets say a table has 100 TD Cells with a white background. I want to click on just 1 and then have it change to a Yellow background. Then when I click on a different Cell have the old one change back to...
3
5523
by: Vam | last post by:
Hi, My program makes an HTML report which needs to be easily printable. On this report is a table, and one of the columns in the table needs to express a color. I've done this by setting the background of the cells in that column to their colors (which differ from row to row), but those background colors don't print unless a certain option is set in IE, which is apparently off by default. The way we've figured around this is to add a...
0
1279
by: Bruce W.1 | last post by:
I'm trying to put together a horizontal tab nav in a User Control, and I want to have some mouseOver behavior. This could easily be done with just CSS, however hyperlinking this way (client-side) would lose session state, right? So I can't do this. I was thinking that a mouseOver on the link text would just make it bold, or change color. I'd like each tab to be prettier than just a different table cell background color, more like a...
1
1933
by: G. Whiz | last post by:
How would I do that? Thanks
11
109596
by: dgk | last post by:
Is there a way to change the foreground or background color of a single cell in an unbound datagridview?
0
2508
by: Thanu | last post by:
Hi, I want to import the background color of cells from excelsheet to Mshflexgrid in Vb6. I already have the code to import the contents from excel to mshflexgrid but i want to import the color also. And the text in some of the cells of mshflexgrid are not Fully visible.only half of the word is visible.How do i format the cells so that i get the entire text in that cell to be seen by stretching the cell size. please let me know as soon...
1
4642
by: dowlingpc | last post by:
Has anyone discovered a way to control the background color of individual "cells" based on the cells content? When the cell has a negative value or is without content I'd like to change its background color. I'm using XP Pro with all updates and MS-Access 2003 with SP1. Thanks for whatever help you can give - Pat
0
3588
by: Chanman | last post by:
I've posted this on the python-excel group, but perhaps people here know what to do. How does one change the cell background color using the xlwt module? I've looked at several tutorials but none show how to change the background color. I've tried the following: badBG = xlwt.Pattern() badBG.SOLID_PATTERN = 0x34 badBG.NO_PATTERN = 0x34
2
9715
by: patrick.waldo | last post by:
Hi all, I am trying to figure out a way to read colors with xlrd, but I did not understand the formatting.py module. Basically, I want to sort rows that are red or green. My initial attempt discovered that text:u'test1.txt' (XF:22) text:u'test2.txt' (XF:15) text:u'test3.txt' (XF:15) text:u'test4.txt' (XF:15) text:u'test5.txt' (XF:23)
0
8672
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8600
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
8858
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
7711
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
6517
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
4614
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3038
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2322
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
1997
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.