I have a gridview in my visual studio 2015 master page web project. I am populating the gridview in codebehind via Datatable. And Datatable have 4 columns and one column is Status (displaying colours RED, ORANGE and GREEN) depending on data for that field.
I have set timer every 30 seconds to refresh the gridview (code behind - Data load function). I want the column to be sorted by colour on status = RED ASC (Red at the top).
I am trying to figure out way to achieve the idea
My aspx page code is below
<asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server">
<div> </div>
<asp:Timer ID="ctlTimer" runat="server" Interval="30000" OnTick="OnTimerIntervalElapse">
</asp:Timer>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:Label ID="lblTimer" runat="server"></asp:Label>
</ContentTemplate>
</asp:UpdatePanel>
<asp:UpdatePanel runat="server" ID="pnlUpdate" EnableViewState="False">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="ctlTimer" EventName="Tick" />
</Triggers>
<ContentTemplate>
<asp:GridView ID="GridView1" runat="server" OnRowDataBound="GridView1_RowDataBound" Width="100%" AllowSorting="True"></asp:GridView>
</ContentTemplate>
</asp:UpdatePanel>
</asp:Content>
My code-Behind code.
// create data table
DataTable dt = new DataTable();
protected void Page_Load(object sender, EventArgs e)
{
// create columns
dt.Columns.Add(new DataColumn("col1", typeof(string)));
dt.Columns.Add(new DataColumn("Status", typeof(string)));
dt.Columns.Add(new DataColumn("col3", typeof(string)));
dt.Columns.Add(new DataColumn("col4", typeof(string)));
// get list of items to display
getListofSystems(1);
// clear datatable
dt.Clear();
}
protected void GridView1_RowDataBound(object sender, System.Web.UI.WebControls.GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
var statusValue = Convert.ToString(DataBinder.Eval(e.Row.DataItem, "Status"));
if (statusValue == "Red")
{
e.Row.Cells[1].BackColor = Color.FromName("Red");
}
if (statusValue == "Orange")
{
e.Row.Cells[1].BackColor = Color.FromName("Orange");
}
if (statusValue == "Green")
{
e.Row.Cells[1].BackColor = Color.FromName("Green");
}
}
}
protected void OnTimerIntervalElapse(object sender, EventArgs e)
{
getListofSystems(1);
}
Load data as a code/logic below.
DataRow dr = dt.NewRow();
// display system name
dr["col1"] = ID;
// Get status from database
switch (status)
{
case "red":
dr["Status"] = "Red";
break;
case "orange":
dr["Status"] = "Orange";
break;
case "green":
dr["Status"] = "Green";
break;
}
dr["col3"] = Datetime.Now;
dr["col4"] = contact;
// add row to datatable
dt.Rows.Add(dr);
// bind data to gridview
GridView1.Visible = true;
GridView1.DataSource = dt;
GridView1.DataBind();
This is pretty much all the code. I have removed un-necessary code to populate the data rows from above.