Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. Web Development
  3. ASP.NET
  4. IF...THEN in asp.net datagrid code

IF...THEN in asp.net datagrid code

Scheduled Pinned Locked Moved ASP.NET
csharphtmlasp-nettutorial
10 Posts 4 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • J Offline
    J Offline
    j45mw
    wrote on last edited by
    #1

    Does anyone know how to create an IF...THEN statement in the ASP.NET datagrid HTML code. Within the code that creates the datagrid I need to display data in a cell IF a certain condition is met. And that is where the IF THEN comes in to play. I realize I could do this in Code Behind but I need to do it within the HTML code in order to allow an HTML designer to work with it also.

    M M 2 Replies Last reply
    0
    • J j45mw

      Does anyone know how to create an IF...THEN statement in the ASP.NET datagrid HTML code. Within the code that creates the datagrid I need to display data in a cell IF a certain condition is met. And that is where the IF THEN comes in to play. I realize I could do this in Code Behind but I need to do it within the HTML code in order to allow an HTML designer to work with it also.

      M Offline
      M Offline
      Mircea Grelus
      wrote on last edited by
      #2

      Well, ASP.Net is serverside code which means code behind, so no, you cannot add ASP.NET in the html code. What I think you can do is bind all the data to the datagrid and on the client side execute a Javascript function that will hide or display the rows of the datagrid using style="display: none" to hide or style="display:''" to show. regards, Mircea Many people spend their life going to sleep when they’re not sleepy and waking up while they still are.

      1 Reply Last reply
      0
      • J j45mw

        Does anyone know how to create an IF...THEN statement in the ASP.NET datagrid HTML code. Within the code that creates the datagrid I need to display data in a cell IF a certain condition is met. And that is where the IF THEN comes in to play. I realize I could do this in Code Behind but I need to do it within the HTML code in order to allow an HTML designer to work with it also.

        M Offline
        M Offline
        Mike Ellison
        wrote on last edited by
        #3

        Just to offer another suggestion - you could use the C# ternary operator (condition ? valueIfTrue : valueIfFalse) within a databinding expression in a TemplateColumn to mimick an IF/THEN/ELSE evaluation. Here's an example; look at how the asp:TemplateColumn is defined to see what I mean.

        <%@ Page Language="C#" %>
        <%@ Import Namespace="System.Data" %>

        <script runat="server">

        // upon page load, initialize the grid
        void Page\_Load(object o, EventArgs e)
        {
            if (!IsPostBack)
            {
                myGrid.DataSource = CreateDataSource();
                myGrid.DataBind();            
            }
        }
        
        // Create the sample datasource for this exercise
        private DataTable CreateDataSource()
        {
            DataTable t = new DataTable();
            
            // create the table structure
            DataColumn c = new DataColumn();
            c.DataType = System.Type.GetType("System.Int32");
            c.ColumnName = "ID";
            c.Unique = true;
            t.Columns.Add(c);
            
            c = new DataColumn();
            c.DataType = System.Type.GetType("System.String");
            c.ColumnName = "Name";
            t.Columns.Add(c);        
            
            c = new DataColumn();
            c.DataType = System.Type.GetType("System.String");
            c.ColumnName = "City";
            t.Columns.Add(c);    
            
            // establish ID as the primary key
            DataColumn\[\] primaryKey = new DataColumn\[1\];
            primaryKey\[0\] = t.Columns\["ID"\];
            t.PrimaryKey = primaryKey;
        
            // populate the table with some sample rows of data
            DataRow r = t.NewRow();
            r\["id"\] = 1001;
            r\["Name"\] = "Jack Bauer";
            r\["City"\] = "Los Angeles";
            t.Rows.Add(r);
            
            r = t.NewRow();
            r\["id"\] = 1002;
            r\["Name"\] = "David Palmer";
            r\["City"\] = "Washington D.C.";
            t.Rows.Add(r);
            
            r = t.NewRow();
            r\["id"\] = 1003;
            r\["Name"\] = "Nina Meyers";
            r\["City"\] = "Los Angeles";
            t.Rows.Add(r);
        
            r = t.NewRow();
            r\["id"\] = 1004;
            r\["Name"\] = "Bill Buchanan";
            r\["City"\] = "Los Angeles";
            t.Rows.Add(r);
            
            return t;
        }
        

        </script>

        <html>
        <head>
        <title>Conditional Output in a DataGrid</title>
        <style> body {font-family: 'Tahoma'; font-size: 10pt;}</style>
        </head>

        <bo

        M 1 Reply Last reply
        0
        • M Mike Ellison

          Just to offer another suggestion - you could use the C# ternary operator (condition ? valueIfTrue : valueIfFalse) within a databinding expression in a TemplateColumn to mimick an IF/THEN/ELSE evaluation. Here's an example; look at how the asp:TemplateColumn is defined to see what I mean.

          <%@ Page Language="C#" %>
          <%@ Import Namespace="System.Data" %>

          <script runat="server">

          // upon page load, initialize the grid
          void Page\_Load(object o, EventArgs e)
          {
              if (!IsPostBack)
              {
                  myGrid.DataSource = CreateDataSource();
                  myGrid.DataBind();            
              }
          }
          
          // Create the sample datasource for this exercise
          private DataTable CreateDataSource()
          {
              DataTable t = new DataTable();
              
              // create the table structure
              DataColumn c = new DataColumn();
              c.DataType = System.Type.GetType("System.Int32");
              c.ColumnName = "ID";
              c.Unique = true;
              t.Columns.Add(c);
              
              c = new DataColumn();
              c.DataType = System.Type.GetType("System.String");
              c.ColumnName = "Name";
              t.Columns.Add(c);        
              
              c = new DataColumn();
              c.DataType = System.Type.GetType("System.String");
              c.ColumnName = "City";
              t.Columns.Add(c);    
              
              // establish ID as the primary key
              DataColumn\[\] primaryKey = new DataColumn\[1\];
              primaryKey\[0\] = t.Columns\["ID"\];
              t.PrimaryKey = primaryKey;
          
              // populate the table with some sample rows of data
              DataRow r = t.NewRow();
              r\["id"\] = 1001;
              r\["Name"\] = "Jack Bauer";
              r\["City"\] = "Los Angeles";
              t.Rows.Add(r);
              
              r = t.NewRow();
              r\["id"\] = 1002;
              r\["Name"\] = "David Palmer";
              r\["City"\] = "Washington D.C.";
              t.Rows.Add(r);
              
              r = t.NewRow();
              r\["id"\] = 1003;
              r\["Name"\] = "Nina Meyers";
              r\["City"\] = "Los Angeles";
              t.Rows.Add(r);
          
              r = t.NewRow();
              r\["id"\] = 1004;
              r\["Name"\] = "Bill Buchanan";
              r\["City"\] = "Los Angeles";
              t.Rows.Add(r);
              
              return t;
          }
          

          </script>

          <html>
          <head>
          <title>Conditional Output in a DataGrid</title>
          <style> body {font-family: 'Tahoma'; font-size: 10pt;}</style>
          </head>

          <bo

          M Offline
          M Offline
          munklefish
          wrote on last edited by
          #4

          Mike, Could you explain what exactrly is going on here please, as this is something i think this code would be useful to a lot of people including myself.

          Mike Ellison wrote:

          <%# (DataBinder.Eval(Container.DataItem, "City") != "Washington D.C." ? "" : "Washington D.C." ) %>

          Thanks!

          M 1 Reply Last reply
          0
          • M munklefish

            Mike, Could you explain what exactrly is going on here please, as this is something i think this code would be useful to a lot of people including myself.

            Mike Ellison wrote:

            <%# (DataBinder.Eval(Container.DataItem, "City") != "Washington D.C." ? "" : "Washington D.C." ) %>

            Thanks!

            M Offline
            M Offline
            Mike Ellison
            wrote on last edited by
            #5

            Okay - first, the C# ternary operator follows this syntax: _condition_ ? _valueIfTrue_ : _valueIfFalse_ It allows for assignment expressions like the following example:

            string sMessage = (sName == null ? "Name doesn't exist" : sName);

            The above will test if sName is null; if it is, the variable sMessage is assigned the value "Name doesn't exist". If sName is not null, then sMessage is assigned the value sName. Now, the ternary operator may be applied within the context of a databinding expression, as in this excerpt from the example I posted earlier:

            <%# (DataBinder.Eval(Container.DataItem, "City") != "Washington D.C." ? "" : "Washington D.C." ) %>

            The condition in this example is DataBinder.Eval(Container.DataItem, "City") != "Washington D.C.". This uses the reflective DataBinder.Eval statement to evaluate the "City" field for a particular data row during binding. (Note: in ASP.NET 2.0, the shorthand Eval("City") could be used instead.) So the condition being evaluated in this example is whether or not the "City" field contains the value "Washington D.C.". If it contains something other than "Washington D.C." (the condition is using the not equals != operator), then the valueIfTrue element from the ternary operator is returned - in this case, a blank string "". If the condition is false (i.e. if the value is "Washington D.C.") then the valueIfFalse element from the ternary operator is returned - in this case, the literal text "Washington D.C.". My example would have been a bit cleaner if I had used an equality condition == rather than a not-equals condition != - sorry about that. Hopefully you understand what I'm getting at though.

            M 1 Reply Last reply
            0
            • M Mike Ellison

              Okay - first, the C# ternary operator follows this syntax: _condition_ ? _valueIfTrue_ : _valueIfFalse_ It allows for assignment expressions like the following example:

              string sMessage = (sName == null ? "Name doesn't exist" : sName);

              The above will test if sName is null; if it is, the variable sMessage is assigned the value "Name doesn't exist". If sName is not null, then sMessage is assigned the value sName. Now, the ternary operator may be applied within the context of a databinding expression, as in this excerpt from the example I posted earlier:

              <%# (DataBinder.Eval(Container.DataItem, "City") != "Washington D.C." ? "" : "Washington D.C." ) %>

              The condition in this example is DataBinder.Eval(Container.DataItem, "City") != "Washington D.C.". This uses the reflective DataBinder.Eval statement to evaluate the "City" field for a particular data row during binding. (Note: in ASP.NET 2.0, the shorthand Eval("City") could be used instead.) So the condition being evaluated in this example is whether or not the "City" field contains the value "Washington D.C.". If it contains something other than "Washington D.C." (the condition is using the not equals != operator), then the valueIfTrue element from the ternary operator is returned - in this case, a blank string "". If the condition is false (i.e. if the value is "Washington D.C.") then the valueIfFalse element from the ternary operator is returned - in this case, the literal text "Washington D.C.". My example would have been a bit cleaner if I had used an equality condition == rather than a not-equals condition != - sorry about that. Hopefully you understand what I'm getting at though.

              M Offline
              M Offline
              munklefish
              wrote on last edited by
              #6

              Mike, I understood the != part, it was more a case of what the subsequent bits were referring to and doing. However the explanation was excellent and cleared things up. Quick question for you thought. Is it possible to return the actual field value, rather than a specific string. Say for example you do the == to check for a given value. If this given value is not met then you just display the contents of the field, rather than having to actually tell it what string to display?

              M 1 Reply Last reply
              0
              • M munklefish

                Mike, I understood the != part, it was more a case of what the subsequent bits were referring to and doing. However the explanation was excellent and cleared things up. Quick question for you thought. Is it possible to return the actual field value, rather than a specific string. Say for example you do the == to check for a given value. If this given value is not met then you just display the contents of the field, rather than having to actually tell it what string to display?

                M Offline
                M Offline
                Mike Ellison
                wrote on last edited by
                #7

                Sure - it's all in the context of one databinding expression, so anything that can be parsed/interpreted in that context is fair game. Here's an example - I'll use the ASP.NET 2.0 syntax, but you can expand it to the full DataBinder.Eval syntax if you want to:

                <%# Eval("Discount") == 0 ? "No Discount" : Eval("Discount") %>

                M 2 Replies Last reply
                0
                • M Mike Ellison

                  Sure - it's all in the context of one databinding expression, so anything that can be parsed/interpreted in that context is fair game. Here's an example - I'll use the ASP.NET 2.0 syntax, but you can expand it to the full DataBinder.Eval syntax if you want to:

                  <%# Eval("Discount") == 0 ? "No Discount" : Eval("Discount") %>

                  M Offline
                  M Offline
                  munklefish
                  wrote on last edited by
                  #8

                  Your Great! :-O:-O:-O:-O

                  1 Reply Last reply
                  0
                  • M Mike Ellison

                    Sure - it's all in the context of one databinding expression, so anything that can be parsed/interpreted in that context is fair game. Here's an example - I'll use the ASP.NET 2.0 syntax, but you can expand it to the full DataBinder.Eval syntax if you want to:

                    <%# Eval("Discount") == 0 ? "No Discount" : Eval("Discount") %>

                    M Offline
                    M Offline
                    munklefish
                    wrote on last edited by
                    #9

                    Mike, I tried the code as suggested, using the following in a DataList: <%# DataBinder.Eval("menuVegetarian") == 1 ? "wibble" : "poop" %> But i get the following error: CS1501: No overload for method 'Eval' takes '1' arguments So i added the Container part that ive used for all my other data displayed in the dataList. <%# DataBinder.Eval(Container, "menuVegetarian") == 1 ? "wibble" : "poop" %> But i get this error: CS0019: Operator '==' cannot be applied to operands of type 'object' and 'int' The value i'm comparing is stored as a Yes/No in Access 2003. So i tried doing it this way: <%# Convert.ToInt16(DataBinder.Eval(Container, "menuVegetarian")) == 1 ? "wibble" : "poop" %> Which gives the following error: DataBinder.Eval: 'System.Web.UI.WebControls.DataListItem' does not contain a property with the name menuVegetarian. Any ideas mate? Thanks Its not my fault im stoopid! :confused: -- modified at 7:22 Saturday 25th February, 2006 Got It: <%# Convert.ToInt16(DataBinder.Eval(Container, "DataItem.menuVegetarian")) == 1 ? "wibble" : "poop" %>

                    M 1 Reply Last reply
                    0
                    • M munklefish

                      Mike, I tried the code as suggested, using the following in a DataList: <%# DataBinder.Eval("menuVegetarian") == 1 ? "wibble" : "poop" %> But i get the following error: CS1501: No overload for method 'Eval' takes '1' arguments So i added the Container part that ive used for all my other data displayed in the dataList. <%# DataBinder.Eval(Container, "menuVegetarian") == 1 ? "wibble" : "poop" %> But i get this error: CS0019: Operator '==' cannot be applied to operands of type 'object' and 'int' The value i'm comparing is stored as a Yes/No in Access 2003. So i tried doing it this way: <%# Convert.ToInt16(DataBinder.Eval(Container, "menuVegetarian")) == 1 ? "wibble" : "poop" %> Which gives the following error: DataBinder.Eval: 'System.Web.UI.WebControls.DataListItem' does not contain a property with the name menuVegetarian. Any ideas mate? Thanks Its not my fault im stoopid! :confused: -- modified at 7:22 Saturday 25th February, 2006 Got It: <%# Convert.ToInt16(DataBinder.Eval(Container, "DataItem.menuVegetarian")) == 1 ? "wibble" : "poop" %>

                      M Offline
                      M Offline
                      Mike Ellison
                      wrote on last edited by
                      #10

                      munklefish wrote:

                      Got It: <%# Convert.ToInt16(DataBinder.Eval(Container, "DataItem.menuVegetarian")) == 1 ? "wibble" : "poop" %>

                      Yup. DataBinder.Eval is looking at the object that is passed in the first argument, to evaluate its property (identified through the second string argument). You could also have done something like this I think:

                      <%# DataBinder.Eval(Container.DataItem, "menuVegetarian") == 1 ? "wibble" : "poop" %>

                      You might have had to use the Convert.ToInt16 code or not, it just depends on the field type itself.

                      1 Reply Last reply
                      0
                      Reply
                      • Reply as topic
                      Log in to reply
                      • Oldest to Newest
                      • Newest to Oldest
                      • Most Votes


                      • Login

                      • Don't have an account? Register

                      • Login or register to search.
                      • First post
                        Last post
                      0
                      • Categories
                      • Recent
                      • Tags
                      • Popular
                      • World
                      • Users
                      • Groups