?
Solved

GridView Control with TemplateField

Posted on 2012-09-21
14
Medium Priority
?
607 Views
Last Modified: 2012-09-22
Hello Experts,

I would like to display an image with a green check if a value for a field is equl to 1 and a red x image if that same value for a field is equal to 0. I have all the code getting performed on Page_Load but not sure how to add the image to the GridView control as a TemplateField.

The code attached is what i'm using to check agains the fields in the DB. I just need to know how I can place an image within the GridView and how to call that image from the GridView into the code attached.

protected void CompletedSections()
    {
        SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["WellnessTracker"].ConnectionString);

        SqlCommand cmd = new SqlCommand();
        cmd.CommandText = "RetrieveCompletedSections";
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Connection = conn;

        DataTable dtCompletedSections = new DataTable();

        SqlDataAdapter adp = new SqlDataAdapter();

        try
        {
            conn.Open();

            adp.SelectCommand = cmd;
            adp.Fill(dtCompletedSections);

            DataRow data = dtCompletedSections.Rows[0];

            string GreenCheck = "../../img/GreenCheckOnly.png";
            string RedX = "../../img/RedXOnly.png";

            if (data["ap_section_complete"].ToString() == "1")
            {
                // Place Green Check
            }
            else
            {
                // Place Red X
            }
            if (data["ghpone_section_complete"].ToString() == "1")
            {
                // Place Green Check
            }
            else
            {
                // Place Red X
            }
            if (data["ghpthree_section_complete"].ToString() == "1")
            {
                // Place Green Check
            }
            else
            {
                // Place Red X
            }
            if (data["ghptwo_section_complete"].ToString() == "1")
            {
                // Place Green Check
            }
            else
            {
                // Place Red X
            }
            if (data["wp_section_complete"].ToString() == "1")
            {
                // Place Green Check
            }
            else
            {
                // Place Red X
            }
            if (data["phs_section_complete"].ToString() == "1")
            {
                // Place Green Check
            }
            else
            {
                // Place Red X
            }
            if (data["sha_section_complete"].ToString() == "1")
            {
                // Place Green Check
            }
            else
            {
                // Place Red X
            }
            if (data["phy_section_complete"].ToString() == "1")
            {
                // Place Green Check
            }
            else
            {
                // Place Red X
            }

            gv_CompletedSections.DataSource = dtCompletedSections;
            gv_CompletedSections.DataBind();
        }

        catch (Exception ex)
        {
            ex.Message.ToString();
        }

        finally
        {
            conn.Close();
        }
    }

Open in new window

0
Comment
Question by:asp_net2
  • 8
  • 6
14 Comments
 
LVL 96

Expert Comment

by:Bob Learned
ID: 38422156
My usual approach there was to apply a different CSS style in the GridView_RowDataBound, after checking the value of a cell...
0
 
LVL 4

Author Comment

by:asp_net2
ID: 38422182
Ok, that would work for me instead of using an image. Can you tell me how I would do that in my GridView and what I would need to put into my code behind? I think the codebehind would need something like System.Drawing.Color.Red; but not sure.
0
 
LVL 96

Expert Comment

by:Bob Learned
ID: 38422367
If you want to go with code-behind, and System.Drawing.Color, here is one approach:

protected void GridView1_RowDataBound(Object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
            if (e.Row.Cells[0].Text == "Administrator")
                e.Row.Cells[0].BackColor = Color.Red;

            if (e.Row.Cells[0].Text == "Power User")
                e.Row.Cells[0].BackColor = Color.Green;
    }
}

Open in new window

0
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 
LVL 4

Author Comment

by:asp_net2
ID: 38422386
Ok, just so I understand. If I use the RowDataBound then how do I add the color for the specific value in my CodeBehind below? Basically, I will have at least 7 of these with a value of either 1 or NULL. I need to display green if value is 1 and red if value is NULL or 0.

if (data["ap_section_complete"].ToString() == "1")
            {
                // Place Green Check
            }
            else
            {
                // Place Red X
            }
0
 
LVL 96

Expert Comment

by:Bob Learned
ID: 38422433
If you need to get a value from the row, in the RowDataBound event handler, then you can do something like this:

GridViewRow.DataItem Property
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridviewrow.dataitem.aspx

 if(e.Row.RowState == DataControlRowState.Edit)
    {
      // Preselect the DropDownList control with the state value
      // for the current row.

      // Retrieve the underlying data item. In this example
      // the underlying data item is a DataRowView object. 
      DataRowView rowView = (DataRowView)e.Row.DataItem;

      // Retrieve the state value for the current row. 
      String state = rowView["state"].ToString();

      // Retrieve the DropDownList control from the current row. 
      DropDownList list = (DropDownList)e.Row.FindControl("StatesList");

      // Find the ListItem object in the DropDownList control with the 
      // state value and select the item.
      ListItem item = list.Items.FindByText(state);
      list.SelectedIndex = list.Items.IndexOf(item);

Open in new window

0
 
LVL 4

Author Comment

by:asp_net2
ID: 38422444
That makes no sense to what I need though. How does that relate to how I need to display those fields based on value returned.
0
 
LVL 96

Accepted Solution

by:
Bob Learned earned 2000 total points
ID: 38422620
If I understand your requirement, it would be a combination of checking the value of data item, and then changing the cell color based on that value.

protected void GridView1_RowDataBound(Object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
            DataRowView rowView = (DataRowView)e.Row.DataItem;

            string userType = rowView["UserType"].ToString();

            if (userType == "Administrator")
                e.Row.Cells[0].BackColor = Color.Red;
            else if (userType == "Power User")
                e.Row.Cells[0].BackColor = Color.Green;
    }
}

Open in new window

0
 
LVL 4

Author Comment

by:asp_net2
ID: 38422687
Requirements below:

 - Display all employees and display the color green if a value has 1 and red if the value is either null or 0. There will be 7 fields that I have to check this for. If you look at my original post above you will see the names of those 7 fields in the CompletedSections() method.

  - Page_Load - calls the method named CompletedSections(). This is how I anticipated displaying the cells in the GridView based on the values returned to this method. I did not think I needed to use the RowDataBound. But if I do then how do I perform that task, will I need the CompletedSections() if I use the RowDataBound method.
0
 
LVL 96

Expert Comment

by:Bob Learned
ID: 38422702
You won't have access to any cells in the Page_Load, that is what the RowDataBound event handler is useful for.  It is called after RowCreated, and after the grid is bound to the data, so that you can check values for the DataItem, and adjust any cell or control styling.

I believe that you should be able to take the examples that I have given you, and modify the RowDataBound event handler to fit your needs.
0
 
LVL 4

Author Comment

by:asp_net2
ID: 38422728
Ok, but do I need the CompletedSections() method still? Or do I just need to retrieve the data to the GridView and then use the RowDataBound method to format the cell's BG Color? Also, your example shows the use of TExt and i'm using integer values such as 1, 0, or NULL.
0
 
LVL 4

Author Comment

by:asp_net2
ID: 38422827
TheLearnedOne,

Ok, I was able to get your code to work as I needed. I understand what you were saying now. Just one more little problem. How do I format that if I need to apply a BackColor and BorderColor instead of just a BackColor?
0
 
LVL 4

Author Closing Comment

by:asp_net2
ID: 38423223
Thank you!
0
 
LVL 96

Expert Comment

by:Bob Learned
ID: 38424798
I am guessing that you figured it out for yourself...
0
 
LVL 4

Author Comment

by:asp_net2
ID: 38424823
Yes, thank you so much for getting me started :)
0

Featured Post

Technology Partners: 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!

Question has a verified solution.

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

Wouldn’t it be nice if you could test whether an element is contained in an array by using a Contains method just like the one available on List objects? Wouldn’t it be good if you could write code like this? (CODE) In .NET 3.5, this is possible…
In real business world data are crucial and sometimes data are shared among different information systems. Hence, an agreeable file transfer protocol need to be established.
Whether it be Exchange Server Crash Issues, Dirty Shutdown Errors or Failed to mount error, Stellar Phoenix Mailbox Exchange Recovery has always got your back. With the help of its easy to understand user interface and 3 simple steps recovery proced…
Kernel Data Recovery is a renowned Data Recovery solution provider which offers wide range of softwares for both enterprise and home users with its cost-effective solutions. Let's have a quick overview of the journey and data recovery tools range he…
Suggested Courses

571 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