?
Solved

Format rows in GridView on ASPX page

Posted on 2011-04-19
3
Medium Priority
?
500 Views
Last Modified: 2013-11-26
Hello Experts,

I have an issues here, that sounds very complicated for a novice user like me :-(.

I am developing a website for my company to automate Windows Server Administration. Using this web based tool one can query windows server details like Hardware/Software/Ping Status/Network Configuration etc. To get these details I have an ASPX page with a GridView control placed on it. There are few text boxes for getting input from the user and few buttons to perform actions.

Coming to the issue:
The GridView control placed on the aspx page is used as common way to display output from any of the several buttons on the page. I am collecting the couput details in a DataTable during the code execution and finally binding the DataTable to the GridView to display the results.
There are different functions attached with each button click event. Every function is using different structure of columns to display output based on the purpose. For example: function to display ping status will use columns - ServerName, IPAddress, FQDN, PingStatus; whereas the function to display OS details will have columns such as - ServerName, OperatingSystem, ServicePack, SerialNumber, LastBootUp. Thus the same GridView will have different columns at different times.

Based on the value criterias defined in different functions I need to highlight the rows in GridView in different color (yellow background). For example: In the function to display windows Service details I need to highlight rows where Service status is Stopped. Whereas in the function to display Disk Usage I need to highlight the rows where disk free space percentage column is having values below 10%.

I have searched the web and found below (event handler) function to highlight the rows based on the cell value but it is depending on the RowDataBound Event.
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)  
    {  
        if (e.Row.RowType == DataControlRowType.DataRow)  
        {  
            if (e.Row.Cells[4].Text=="1")  
                e.Row.BackColor = Color.Green;  
            else  
                e.Row.BackColor = Color.Red;  
        }  
    }

Open in new window


There are two issues with the above approach:
(1)  Since we are adding data to GridView by setting DataSource = DataTable and then binding the datatable, I am not sure if that will trigger the above RowDataBound event.
(2) And, since the column structure is not fixed due to different functions using same GridView with different column structure each time, in order to get the Column reference we need to first get reference of the function which is creating the GridView.

Hope this is clear. If not, please feel free to ask for more explaination or any other input from my side.
0
Comment
Question by:SavindraSingh
  • 2
3 Comments
 
LVL 14

Expert Comment

by:robasta
ID: 35422980
1. RowDataBound will be triggered when because you will make a call to GridView1.DataBind()

2. since the columns will be dynamic, You need to setup the colors before hand. You need to add the logic to determine the columns that will be colored.
 as an example, you can create two arrays = type{"ping","os"} column{"3","5"} color{"blue","red"}
in the example above, the Column 3, for the ping table will be colored Blue. whilst the 5th column of the 'os' table will be Red. (you will determine the values using the index.










0
 
LVL 5

Accepted Solution

by:
SavindraSingh earned 0 total points
ID: 35423762
Thanks for your response robasta,

Fortunately, I have got a better workaround for this :-)

What I have done is. I have created an ENUM like:
    public enum FunctionName
    {
        PingStatus, ServiceDetails, NICDetails, ServerConfig, OSDetails, MemoryUtil, RDPStatus, DriveSpaceInfo, PortStatus
    }

Open in new window

Then declared a public variable of this type:
FunctionName CurrentFunction;

Open in new window


Now before Binding the data to the GridView (in this case dgOutput) I am calling an event handler which is working perfectly (example):

    protected void btnPingStatus_Click(object sender, EventArgs e)          // Button => Get Ping Status 
    {
        CurrentFunction = FunctionName.PingStatus;
        if (PageMaster.CheckErrors())
        {
            dgOutput.DataSource = null;
            dgOutput.DataBind();

            string[] ServerList;
            string ServerName;
            string IsAlive = "";
            Out_Table.Columns.Add(new DataColumn("Server Name", typeof(string)));
            Out_Table.Columns.Add(new DataColumn("IP Address", typeof(string)));
            Out_Table.Columns.Add(new DataColumn("FQDN", typeof(string)));
            Out_Table.Columns.Add(new DataColumn("Ping Status", typeof(string)));

            if (string.IsNullOrWhiteSpace(txtServerList.Text.Trim()))
            {
                lblError.Text = "Error: No Servers listed!";
                lblError.Visible = true;
                return;
            }
            lblError.Text = "";
            lblError.Visible = false;
            ServerList = txtServerList.Text.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);

            foreach (string Server in ServerList)
            {
                ServerName = Server.Trim();
                if (string.IsNullOrWhiteSpace(ServerName))
                    continue;
                IsAlive = GetPingStatus(ServerName);
                DataRow Out_Row = Out_Table.NewRow();
                if (IsAlive != "Failed")
                {
                    Out_Row["Server Name"] = ServerHostName;
                    Out_Row["IP Address"] = IP_Addr;
                    Out_Row["FQDN"] = FQDN;
                    Out_Row["Ping Status"] = IsAlive;
                    Out_Table.Rows.Add(Out_Row);
                }
                else
                {
                    Out_Row["Server Name"] = ServerName;
                    Out_Row["IP Address"] = "NA";
                    Out_Row["FQDN"] = FQDN;
                    Out_Row["Ping Status"] = IsAlive;
                    Out_Table.Rows.Add(Out_Row);
                }
                Out_Row = null;
            }
            dgOutput.RowDataBound += new GridViewRowEventHandler(dgOutput_RowDataBound);
            dgOutput.DataSource = Out_Table;
            dgOutput.DataBind();
            Out_Table = null;
        }
    }

    void dgOutput_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        switch (CurrentFunction)
        {
            case FunctionName.PingStatus:
                if (e.Row.RowType == DataControlRowType.DataRow)
                {
                    try
                    {
                        if (e.Row.Cells[3].Text == "Failed")
                        {
                            e.Row.BackColor = Color.Orange;
                        }
                    }
                    catch { }
                }
                break;
            case FunctionName.ServiceDetails:
                if (e.Row.RowType == DataControlRowType.DataRow)
                {
                    try
                    {
                        if (e.Row.Cells[4].Text == "Stopped")
                        {
                            e.Row.BackColor = Color.Orange;
                        }
                    }
                    catch { }
                }
                break;
            case FunctionName.NICDetails:
                break;
            case FunctionName.ServerConfig:
                break;
            case FunctionName.OSDetails:
                break;
            case FunctionName.MemoryUtil:
                break;
            case FunctionName.RDPStatus:
                if (e.Row.RowType == DataControlRowType.DataRow)
                {
                    try
                    {
                        if (e.Row.Cells[1].Text == "Not Available")
                        {
                            e.Row.BackColor = Color.Orange;
                        }
                    }
                    catch { }
                }
                break;
            case FunctionName.DriveSpaceInfo:
                if (e.Row.RowType == DataControlRowType.DataRow)
                {
                    try
                    {
                        double PFree;
                        bool CanConvert = double.TryParse(e.Row.Cells[4].Text, out PFree);
                        if (CanConvert)
                        {
                            if (PFree < 10)
                                e.Row.BackColor = Color.Orange;
                        }
                    }
                    catch { }
                }
                break;
            case FunctionName.PortStatus:
                if (e.Row.RowType == DataControlRowType.DataRow)
                {
                    try
                    {
                        if (e.Row.Cells[2].Text == "Close")
                        {
                            e.Row.BackColor = Color.Orange;
                        }
                    }
                    catch { }
                }
                break;
            default:
                break;
        }
    }

    public string GetPingStatus(string hostName)                            // Function Get Ping Status 
    {
        try
        {
            Ping pingSender = new Ping();
            PingReply reply;
            PingOptions options = new PingOptions();
            options.Ttl = 110;
            int timeout = 330;
            byte[] buffer = new byte[]{1};
            
            reply = pingSender.Send(hostName.Trim(), timeout, buffer, options);

            if (reply.Status == IPStatus.Success)
            {
                IP_Addr = reply.Address.ToString();
                FQDN = Dns.Resolve(IP_Addr).HostName.ToString();
                string[] Temp_FQDN;
                Temp_FQDN = FQDN.Split(new string[]{"."}, StringSplitOptions.RemoveEmptyEntries);
                ServerHostName = Temp_FQDN[0].ToUpper();
                return reply.Status.ToString();
            }
            else
            {
                IP_Addr = reply.Address.ToString();
                FQDN = Dns.Resolve(IP_Addr).HostName.ToString();
                string[] Temp_FQDN;
                Temp_FQDN = FQDN.Split(new string[]{"."}, StringSplitOptions.RemoveEmptyEntries);
                ServerHostName = Temp_FQDN[0].ToUpper();
                return reply.Status.ToString();
            }
        }
        catch (Exception)
        {
            FQDN = "Unable to connect";
            return "Failed";
        }
    }

Open in new window


Thus I can just keep adding the code to the SWITCH CASE in the event handler part.

Though, thanks again for your input.
0
 
LVL 5

Author Closing Comment

by:SavindraSingh
ID: 35455451
I got some workaround that worked for me.
0

Featured Post

[Webinar On Demand] Database Backup and Recovery

Does your company store data on premises, off site, in the cloud, or a combination of these? If you answered “yes”, you need a data backup recovery plan that fits each and every platform. Watch now as as Percona teaches us how to build agile data backup recovery plan.

Question has a verified solution.

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

More often than not, we developers are confronted with a need: a need to make some kind of magic happen via code. Whether it is for a client, for the boss, or for our own personal projects, the need must be satisfied. Most of the time, the Framework…
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.
THe viewer will learn how to use NetBeans IDE 8.0 for Windows to perform CRUD operations on a MySql database.
The viewer will learn how to use and create new code templates in NetBeans IDE 8.0 for Windows.
Suggested Courses
Course of the Month9 days, 16 hours left to enroll

569 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