?
Solved

datagrid

Posted on 2004-04-15
18
Medium Priority
?
1,703 Views
Last Modified: 2007-12-19
i have a dynamic datagrid, created based on an xml spec. I create columns on the fly based on the xml,

eg.


                                                            case "Text":  --> attribute from xml
                                                                  // Default Column
                                                                  BoundColumn datagridcol = new BoundColumn();
                                                                  datagridcol.HeaderText = HeaderText.Trim() + "<span id=" + DataField + "></span>";
                                                                  datagridcol.DataField = DataField;
                                                                  datagridcol.SortExpression = "";


etc ..


then i do a databind()

and then i loop trough every cell on my datagrid to verify for negatives values and change the color of the displayed value as Red.


the question is, how would you be able to access the values on every cell and modify it based on an attribute of the xml spec?

problems:
before the databind, you cannot check the values of a particular cell
after the databind, you can check the values, but you don't what is that particular column name?

thanks
0
Comment
Question by:alain123
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 10
  • 8
18 Comments
 
LVL 1

Author Comment

by:alain123
ID: 10837413
actually is there ny way to get the column name inside this loop?

thanks.

alain


Grid.DataSource = ds;
                                          Grid.DataBind();
                                          
                                          //======Mark negatives red==============
                                          int iColumns = Grid.Columns.Count;   //total columns
                                          int iCount = Grid.Items.Count;            //current items shown
                                          int iRows =  ds.Tables[0].Rows.Count;            //total rows count

                                          for(int x = 0; x < iColumns; x++)
                                          {
                                                for(int y = 0; y < iCount ; y ++)
                                                {
                                                      
                                                      string CellValue = Grid.Items[y].Cells[x].Text;
                                                      
                                                      //CellValue = "";
//                                                      if(CellValue == "")
//                                                      {
//
//                                                            Grid.Items[y].Cells[x].Text = "-";
//
//                                                      }

                                                      bool bIsNumber = IsNumber(CellValue);
                                                
                                                      if(bIsNumber)
                                                      {
                                                            double cv = Convert.ToDouble(CellValue);
                                                                  
                                                            if (cv < 0 )
                                                            {
                                                                  Grid.Items[y].Cells[x].ForeColor =  System.Drawing.Color.FromName("#DD0000");
                                                            }
                                                      }
                                                      
                                                      if(Grid.Items[y].ItemType == ListItemType.Footer)
                                                      {
                                                                  //string test1 = "";
                                                      }
                                                }      
                                          }
0
 
LVL 20

Expert Comment

by:TheAvenger
ID: 10839951
I think you can use the ItemDataBound event to change the properties of the cell:

The ItemDataBound event is raised after an item is data bound to the DataGrid control. This event provides you with the last opportunity to access the data item before it is displayed on the client. After this event is raised, the data item is nulled out and no longer available.

More info under: http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfsystemwebuiwebcontrolsdatagridclassitemdataboundtopic.asp
0
 
LVL 1

Author Comment

by:alain123
ID: 10842324
Thank you Avenger, I'm actually using the ItemDataBound  event to do some other stuff. my problem is how do i get the name of the column?

after databind() i have this info from the immwindow

OMSmartGrid.Columns[1]
{System.Web.UI.WebControls.BoundColumn}
    System.Web.UI.WebControls.DataGridColumn: {System.Web.UI.WebControls.BoundColumn}
    boundField: "ProductName"  
    boundFieldDesc: {System.Data.DataColumnPropertyDescriptor}
    boundFieldDescValid: true
    DataField: "ProductName"   --> if i could access this would be great -
    DataFormatString: ""
    formatting: ""
    ReadOnly: false
    thisExpr: "!"


the on itemdatabound i have only access to find out if it is a header of item or footer

if(e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)  etc .. not the column name...

thank you.
alain
0
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 1

Author Comment

by:alain123
ID: 10842426
Avenger, really what i'm trying to do is to change/format every value on every cell of the datagrid depending on what it is..
0
 
LVL 20

Expert Comment

by:TheAvenger
ID: 10842431
I think you should use the e.Item.Cells property. You can take a specific cell by:

e.Item.Cells[1]

However I don't know how you can get the Column from the cell :-(( You can try what the Parent property will give you...

Start the solution in debug mode and put a breakpoint somewhere in the ItemDataBound event. Then review the e.Item.Cell[0] object, maybe you will find a reference to help you
0
 
LVL 1

Author Comment

by:alain123
ID: 10842688
looking to the properties of the cell, nothing...  the parent also when i look at the object data/properties does not have anything like that..
=(

e.Item.Cells[0].Parent
{System.Web.UI.WebControls.DataGridItem}
    [System.Web.UI.WebControls.DataGridItem]: {System.Web.UI.WebControls.DataGridItem}
    System.Object: {System.Web.UI.WebControls.DataGridItem}
    _cachedUniqueID: null
    _controls: {System.Web.UI.WebControls.TableRow.CellControlCollection}
    _controlState: Loaded
    _controlsViewState: <undefined value>
    _dataBindings: <undefined value>
    _events: <undefined value>
    _id: "_ctl3"
    _namedControls: <undefined value>
    _namedControlsID: 1
    _namingContainer: {System.Web.UI.WebControls.DataGrid}
    _page: {ASP.Reports_aspx}
    _parent: {System.Web.UI.WebControls.DataGridTable}
    _renderMethod: <undefined value>
    _site: <undefined value>
    _viewState: <undefined value>
    automaticIDCount: 128
    automaticIDPrefix: "_ctl"
    automaticIDs: {Length=128}
    BindingContainer: {System.Web.UI.WebControls.DataGrid}
    ChildControlsCreated: false
    ClientID: "DataGrid1__ctl3"
    Context: {System.Web.HttpContext}
    Controls: {System.Web.UI.WebControls.TableRow.CellControlCollection}
    controlsCreated: 8
    ControlState: Loaded
    creatingControls: 256
    disableViewState: 4
    EnableViewState: true
    EventDataBinding: {System.Object}
    EventDisposed: {System.Object}
    EventInit: {System.Object}
    EventLoad: {System.Object}
    EventPreRender: {System.Object}
    Events: {System.ComponentModel.EventHandlerList}
    EventUnload: {System.Object}
    flags: {System.Web.Util.SimpleBitVector32}
    HasChildViewState: false
    ID: null
    ID_RENDER_SEPARATOR: 95 '_'
    ID_SEPARATOR: 58 ':'
    idNotCalculated: 1
    idNotRequired: 64
    invisible: 16
    isNamingContainer: 128
    IsTrackingViewState: true
    marked: 2
    NamingContainer: {System.Web.UI.WebControls.DataGrid}
    nonBindingContainer: 512
    Page: {ASP.Reports_aspx}
    Parent: {System.Web.UI.WebControls.DataGridTable}
    Site: <undefined value>
    TemplateSourceDirectory: "/NET/Sitescape"
    UniqueID: "DataGrid1:_ctl3"
    UniqueIDWithDollars: "DataGrid1$_ctl3"
    ViewState: {System.Web.UI.StateBag}
    ViewStateIgnoresCase: false
    Visible: true
    visibleDirty: 32
0
 
LVL 20

Expert Comment

by:TheAvenger
ID: 10842710
Parent: {System.Web.UI.WebControls.DataGridTable}

Thus you can take the table, from the table you can take the column, from the column you can take the name
0
 
LVL 1

Author Comment

by:alain123
ID: 10842804
uh? how do you do that?
0
 
LVL 20

Expert Comment

by:TheAvenger
ID: 10842846
ok, try this:
((DataGrid)e.Item.Parent).Columns[0].DataField


if it does not work, please tell me what is the result of this (you can evaluate it in the watch window):

typeof(e.Item.Parent).ToString()

0
 
LVL 1

Author Comment

by:alain123
ID: 10843154
     if(e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
                  {
                        string test =  typeof(e.Item.Parent).ToString();   -->"Type or namespace e could not be found"  -- cannot find a reference to e  .. does not make sense to me ....



((DataGrid)e.Item.Parent).Columns[0].DataField --> did not work ... datafield is not part of columns properties...
0
 
LVL 20

Expert Comment

by:TheAvenger
ID: 10843196
OK, can you review the properties of ((DataGrid)e.Item.Parent).Columns[0] and paste them here as you did before?
0
 
LVL 1

Author Comment

by:alain123
ID: 10843359
     private void GridItemDataBound(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)
            {

                  DataGrid dg = (DataGrid)sender;      

if(e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
                  {
                        //string test =  typeof(e.Item.Parent).ToString();
                        
                        if(e.Item.ItemType == ListItemType.Item)
                        {
                              e.Item.Attributes.Add("onmouseover", "this.style.backgroundColor='#FFF5A4'");
                              e.Item.Attributes.Add("onmouseout", "this.style.backgroundColor='#FEFFDF'");
                        }


dg.Columns[0]
{System.Web.UI.WebControls.HyperLinkColumn}
    System.Web.UI.WebControls.DataGridColumn: {System.Web.UI.WebControls.HyperLinkColumn}
    DataNavigateUrlField: "Orders"
    DataNavigateUrlFormatString: "test.aspx?x={0}"
    DataTextField: "ItemCode"
    DataTextFormatString: ""
    NavigateUrl: ""
    Target: ""
    Text: ""
    textFieldDesc: <undefined value>
    urlFieldDesc: <undefined value>
0
 
LVL 20

Accepted Solution

by:
TheAvenger earned 2000 total points
ID: 10843420
I see. OK, then you need to check the type of column and take its properties. Something like:

string s = null;
swtich (typeof (dg.Columns[0]).ToString()) {
      case "System.Web.UI.WebControls.HyperLinkColumn":
            s = ((System.Web.UI.WebControls.HyperLinkColumn)dg.Columns[0]).DataTextField;
            break;
      case "System.Web.UI.WebControls.BoundColumn":
            s = ((System.Web.UI.WebControls.BoundColumn)dg.Columns[0]).DataField;
            break;
      case "System.Web.UI.WebControls.ButtonColumn":
...
      case "System.Web.UI.WebControls.EditCommandColumn":
...
      case "System.Web.UI.WebControls.TemplateColumn":
...
}
0
 
LVL 1

Author Comment

by:alain123
ID: 10843587
typeof(dg.Columns[0]).ToString()
error: identifier 'typeof' out of scope
typeof(dg.Columns[0])
error: identifier 'typeof' out of scope

also, i'm trying to access the "ColumnName" of the column, not the type.... =)
0
 
LVL 20

Expert Comment

by:TheAvenger
ID: 10843623
My mistake in the code: use dg.Columns[0].GetType() instead of typeof (dg.Columns[0])

The typeof operator gives you the type of the column in means of C# type. Then based on the type you select different data, because all column types provide you with different options.

In the example I showed how you can get the two properties you pointed to in the previous posts.
0
 
LVL 1

Author Comment

by:alain123
ID: 10843740
ok Avenger, you're the man..  it works.. thanks a lot!


alain
0
 
LVL 1

Author Comment

by:alain123
ID: 10843790
Avenger,

why do i need to cast it instead of accessing it directly?

      s = ((System.Web.UI.WebControls.HyperLinkColumn)OMSmartGrid.Columns[0]).DataTextField;
                                                                                                s = (OMSmartGrid.Columns[0]).DataTextField;  ..?
0
 
LVL 20

Expert Comment

by:TheAvenger
ID: 10845631
If you know the type of the columns, you can use it directly. What I showed you was some kind of "general" handling
0

Featured Post

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Extention Methods in C# 3.0 by Ivo Stoykov C# 3.0 offers extension methods. They allow extending existing classes without changing the class's source code or relying on inheritance. These are static methods invoked as instance method. This…
Article by: Najam
Having new technologies does not mean they will completely replace old components.  Recently I had to create WCF that will be called by VB6 component.  Here I will describe what steps one should follow while doing so, please feel free to post any qu…
Have you created a query with information for a calendar? ... and then, abra-cadabra, the calendar is done?! I am going to show you how to make that happen. Visualize your data!  ... really see it To use the code to create a calendar from a q…
How to fix incompatible JVM issue while installing Eclipse While installing Eclipse in windows, got one error like above and unable to proceed with the installation. This video describes how to successfully install Eclipse. How to solve incompa…
Suggested Courses
Course of the Month14 days, 5 hours left to enroll

800 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question