datagrid

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
LVL 1
alain123Asked:
Who is Participating?
 
TheAvengerConnect With a Mentor Commented:
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
 
alain123Author Commented:
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
 
TheAvengerCommented:
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
Cloud Class® Course: CompTIA Cloud+

The CompTIA Cloud+ Basic training course will teach you about cloud concepts and models, data storage, networking, and network infrastructure.

 
alain123Author Commented:
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
 
alain123Author Commented:
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
 
TheAvengerCommented:
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
 
alain123Author Commented:
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
 
TheAvengerCommented:
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
 
alain123Author Commented:
uh? how do you do that?
0
 
TheAvengerCommented:
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
 
alain123Author Commented:
     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
 
TheAvengerCommented:
OK, can you review the properties of ((DataGrid)e.Item.Parent).Columns[0] and paste them here as you did before?
0
 
alain123Author Commented:
     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
 
alain123Author Commented:
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
 
TheAvengerCommented:
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
 
alain123Author Commented:
ok Avenger, you're the man..  it works.. thanks a lot!


alain
0
 
alain123Author Commented:
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
 
TheAvengerCommented:
If you know the type of the columns, you can use it directly. What I showed you was some kind of "general" handling
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.