Solved

datagrid

Posted on 2004-04-15
18
1,697 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
Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

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

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

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…
This article introduced a TextBox that supports transparent background.   Introduction TextBox is the most widely used control component in GUI design. Most GUI controls do not support transparent background and more or less do not have the…
Microsoft Active Directory, the widely used IT infrastructure, is known for its high risk of credential theft. The best way to test your Active Directory’s vulnerabilities to pass-the-ticket, pass-the-hash, privilege escalation, and malware attacks …
Although Jacob Bernoulli (1654-1705) has been credited as the creator of "Binomial Distribution Table", Gottfried Leibniz (1646-1716) did his dissertation on the subject in 1666; Leibniz you may recall is the co-inventor of "Calculus" and beat Isaac…

792 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