Solved

datagrid

Posted on 2004-04-15
18
1,689 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
  • 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
 
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
Better Security Awareness With Threat Intelligence

See how one of the leading financial services organizations uses Recorded Future as part of a holistic threat intelligence program to promote security awareness and proactively and efficiently identify threats.

 
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 500 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

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

Suggested Solutions

Bit flags and bit flag manipulation is perhaps one of the most underrated strategies in programming, likely because most programmers developing in high-level languages rely too much on the high-level features, and forget about the low-level ones. Th…
Summary: Persistence is the capability of an application to store the state of objects and recover it when necessary. This article compares the two common types of serialization in aspects of data access, readability, and runtime cost. A ready-to…
In this seventh video of the Xpdf series, we discuss and demonstrate the PDFfonts utility, which lists all the fonts used in a PDF file. It does this via a command line interface, making it suitable for use in programs, scripts, batch files — any pl…
This video gives you a great overview about bandwidth monitoring with SNMP and WMI with our network monitoring solution PRTG Network Monitor (https://www.paessler.com/prtg). If you're looking for how to monitor bandwidth using netflow or packet s…

757 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

Need Help in Real-Time?

Connect with top rated Experts

21 Experts available now in Live!

Get 1:1 Help Now