How to enable the sorting for dynamically setting the lbl field text in a GridView. Below is the code for the GridView and .cs code where i am setting the value for the dynamic label field. The question is, I am not able to apply the sorting expression for this particular asp:template similar to other templates.
<asp:GridView ID="gvAlertsStatus" runat="server" AllowSorting="true"
OnSorting="gvAlertsStatus_Sorting" AutoGenerateColumns="false"
OnRowDataBound="gvAlertsStatus_RowDataBound">
<Columns>
<asp:TemplateField HeaderText="Owner" SortExpression="UsrName"
ItemStyle-Width="120px">
<ItemTemplate><%#Eval("UsrName") %></ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Last Result" SortExpression="lblLastResult"
ItemStyle-Width="40px" ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:Label runat="server" ID="lblLastResult" Font-Bold="true">
</asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Active" SortExpression="Active"
ItemStyle-Width="60px" >
<ItemTemplate>
<asp:Label runat="server" ID="lblActive"
Text='<%#Eval("Active") %>' >
</asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
.aspx.cs code
public void gvAlertsStatus_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowIndex >= 0)
{
Label lblLastResult = (Label)e.Row.FindControl("lblLastResult");
// Get the dates
DateTime dtSuccess = (eScan.Lib.Shared.Utils.IsDate(lblSuccess.Text)) ?
DateTime.Parse(lblSuccess.Text) : DateTime.MinValue;
DateTime dtFailure = (eScan.Lib.Shared.Utils.IsDate(lblFailure.Text)) ?
DateTime.Parse(lblFailure.Text) : DateTime.MinValue;
DateTime dtDelay = (eScan.Lib.Shared.Utils.IsDate(lblDelay.Text)) ?
DateTime.Parse(lblDelay.Text) : DateTime.MinValue;
DateTime dtLastRun = (dtSuccess > dtFailure) ? dtSuccess : dtFailure;
// Set up the Last Result label
lblLastResult.Text = (dtSuccess > dtFailure) ? "Success" : "Fail";
}
}
protected void gvAlertsStatus_Sorting(object sender, GridViewSortEventArgs e)
{
// Set up the sort direction
SortDirection sd = SortDirection.Ascending;
// If the same column is clicked, then alternate sort direction
if (e.SortExpression.Equals(ViewState["SortExp"]))
{
sd = ((SortDirection)ViewState["SortDir"] == SortDirection.Descending) ?
SortDirection.Ascending : SortDirection.Descending;
}
// Save the states
ViewState["SortExp"] = e.SortExpression;
ViewState["SortDir"] = sd;
// Sort the view and rebind that
DataView dv = (DataView)gvAlertsStatus.DataSource;
dv.Sort = e.SortExpression + " " +
((sd == SortDirection.Descending) ? "DESC" : "ASC");
gvAlertsStatus.DataSource = dv;
gvAlertsStatus.DataBind();
}
Try this code.........
protected void RadgvData_SortCommand(object sender, GridSortCommandEventArgs e)
{
GridTableView tableView = e.Item.OwnerTableView;
e.Canceled = true;
GridSortExpression expression = new GridSortExpression();
expression.FieldName = e.SortExpression;
if (tableView.SortExpressions.Count == 0 || tableView.SortExpressions[0].FieldName != e.SortExpression)
{
expression.SortOrder = GridSortOrder.Descending;
}
else if (tableView.SortExpressions[0].SortOrder == GridSortOrder.Descending)
{
expression.SortOrder = GridSortOrder.Ascending;
}
else if (tableView.SortExpressions[0].SortOrder == GridSortOrder.Ascending)
{
expression.SortOrder = GridSortOrder.Descending;
}
tableView.SortExpressions.AddSortExpression(expression);
RadgvData.Rebind();
}
Related
I have tried a number of solutions to get this working, but I could not find one that it working for me. I am a beginner at programming in C# with ASP.net, and I would appreciate any help that I can get.
Currently, my gridview allows me to sort, if I click on the column header, and this sorts it by ascending to descending order. However, when I click a link button i.e. one of the buttons in the 'flags' column of my programme, it does highlight that option (it is supposed to do it), but it doesn't keep the sort - I want it to keep the sort after this has been clicked. Would someone be able to help with this please?
Here is my aspx code (this is in asp:GridView):
<%--Flags column--%>
<asp:TemplateField HeaderText ="Flags" ItemStyle-Width="34px" SortExpression="sortFlag">
<ItemTemplate>
<div style="width:34px">
<asp:HiddenField ID="HidSortFlag" Value='<%#Eval("sortFlag") %>' runat="server" />
<asp:HiddenField ID="hidAmended" Value='<%#Eval("Amended") %>' runat="server" />
<asp:HiddenField ID="hidPayAnyway" Value='<%#Eval("PaymentOverrideFlag") %>' runat="server" />
<asp:HiddenField ID="hidQueries" Value='<%#Eval("QueryCount") %>' runat="server" />
<asp:HiddenField ID="hidSupplierRefCount" Value='<%#Eval("SupplierRefCount") %>' runat="server" />
<asp:HiddenField ID="hdnElementRef" Value='<%# Eval("SuggestedMatches") %>' runat="server" />
<asp:LinkButton ID="flagQueries" runat="server" Text="<span class='glyphicon glyphicon-comment' data-toggle='tooltip' data-placement='top' title='Comments and Queries'></span>" OnClick="flagQueries_Click" CommandArgument='<%# Eval("StatementLineId") +";"+Eval("SupplierRef") +";" + Eval("SuggestedMatches")%>' > </asp:LinkButton><br />
<asp:LinkButton ID="flagAmends" runat="server" Text="<span class='glyphicon glyphicon-flag' data-toggle='tooltip' data-placement='top' title='Related Booking Has Been Amended' ></span>" OnClick="flagAmends_Click" CommandArgument='<%# Eval("StatementLineId") %>'></asp:LinkButton><br />
<asp:LinkButton id="flagPayments" runat="server" Text="<span class='glyphicon glyphicon-ok' data-toggle='tooltip' data-placement='top' title='Pay Anyway'></span>" OnClick="flagPayments_Click" CommandArgument='<%# Eval("StatementLineId") + ";" +Eval("SuggestedMatches")%>'></asp:LinkButton> <br />
</div>
</ItemTemplate>
</asp:TemplateField>
Here is the code behind which does the sort:
protected void gridSummary_Sorting(object sender, GridViewSortEventArgs e)
{
//Check if the sort field is being used or a new sort
if (ViewState["summarySortField"] == null)
{
ViewState["summarySortField"] = e.SortExpression;
}
else if (ViewState["summarySortField"].ToString() != e.SortExpression)
{
ViewState["summaryDirectionState"] = null;
ViewState["summarySortField"] = e.SortExpression;
}
summaryDirection = summaryDirection == SortDirection.Ascending ? SortDirection.Descending : SortDirection.Ascending;
string sortingDirection = summaryDirection == SortDirection.Ascending ? "Desc" : "Asc";
DataView summaryView = LoadStatement();
summaryView.Sort = string.Format("{0} {1}", e.SortExpression, sortingDirection);
//Session["SortedView"] = summaryView;
gridSummary.DataSource = summaryView;
gridSummary.DataBind();
//ColourFlags();
}
public SortDirection summaryDirection
{
get
{
if (ViewState["summaryDirectionState"] == null)
{
ViewState["summaryDirectionState"] = SortDirection.Ascending;
}
return (SortDirection)ViewState["summaryDirectionState"];
}
set
{
ViewState["summaryDirectionState"] = value;
}
}
protected void gridDetail_Sorting(object sender, GridViewSortEventArgs e)
{
//Check if the sort field is being used or a new sort
if (ViewState["detailSortField"] == null)
{
ViewState["detailSortField"] = e.SortExpression;
}
else if (ViewState["detailSortField"].ToString() != e.SortExpression)
{
ViewState["detailDirectionState"] = null;
ViewState["detailSortField"] = e.SortExpression;
}
detailDirection = detailDirection == SortDirection.Ascending ? SortDirection.Descending : SortDirection.Ascending;
string sortingDirection = detailDirection == SortDirection.Ascending ? "Desc" : "Asc";
//string gets toggle error field in order to add the colour red to certain columns
DataView detailView = LoadDetails(Session["arg"].ToString());
string[] args = Session["arg"].ToString().Split(';');
string status = args[0];
detailView.Sort = string.Format("{0} {1}", e.SortExpression, sortingDirection);
//Session["SortedView"] = summaryView;
gridDetail.DataSource = detailView;
gridDetail.DataBind();
ColourFlags();
ToggleErrorFields(string.IsNullOrEmpty(status));
}
public SortDirection detailDirection
{
get
{
if (ViewState["detailDirectionState"] == null)
{
ViewState["detailDirectionState"] = SortDirection.Ascending;
}
return (SortDirection)ViewState["detailDirectionState"];
}
set
{
ViewState["detailDirectionState"] = value;
}
}
Here is the click event for one of the flags:
protected void flagAmends_Click(object sender, EventArgs e)
{
LinkButton faBtn = sender as LinkButton;
int lineId = int.Parse(faBtn.CommandArgument);
using (SpamEntities spam = new SpamEntities())
{
SPM_Statement_Lines line = spam.SPM_Statement_Lines.Where(x => x.StatementLineID == lineId).FirstOrDefault();
line.Amended = !line.Amended;
spam.SaveChanges();
}
//reloads gridview
LoadDetails(hidStatus.Value + ";" + hidCategory.Value + ";" + lineId);
}
After the button clicks the button changes colour, and performs the necessary action, however it does not keep its sort - I have been trying to fix this but I have not been successful. I would appreciate any clear step by step solutions.
I am trying to change the color of gridview rows based on label value in a gridview. I have End Date value in the gridview, so i want to change background color if the End Date < Today's date.
<asp:GridView ID="gv_profile" runat="server" AutoGenerateColumns="false" Width="300px" OnRowDataBound="OnRowDataBound" DataKeyNames="ID" >
<Columns>
<asp:TemplateField ItemStyle-Width="10px" HeaderText="ID" >
<ItemTemplate>
<asp:Label ID="LblID" runat="server" Text='<%# Eval("ID")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField ItemStyle-Width="50px" HeaderText="End Date">
<ItemTemplate>
<asp:Label ID="lblEndDate" runat="server" Text='<%# Eval("End_Date", "{0: yyyy-MM-dd}") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
code behind
protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
}
}
that should fit your needs
protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow && !((e.Row.RowState == (DataControlRowState.Edit | DataControlRowState.Alternate)) || (e.Row.RowState == DataControlRowState.Edit)))
{
Label lblEndDate = (Label)e.Row.FindControl("lblEndDate");
DateTime EndDate = DateTime.Parse(lblEndDate.Text);
if (EndDate<DateTime.Today)
{
e.Row.BackColor = System.Drawing.Color.MistyRose;
}
}
}
protected void grdView_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Cells[0].Attributes.Add("onmouseover", "MouseEvents(this, event)");
e.Row.Cells[0].Attributes.Add("onmouseout", "MouseEvents(this, event)");
if ((lblhidisinsert.Value == "1") )
{
e.Row.BackColor = System.Drawing.ColorTranslator.FromHtml("#ecf8ec");
}
}
}
if (e.Row.RowType == DataControlRowType.DataRow)
{
int id = Convert.ToInt32(e.Row.Cells[1].Text);
if (id > 0)
{
e.Row.Cells[1].ForeColor = System.Drawing.Color.Red;
}
else
{
e.Row.Cells[1].Text = Math.Abs(id).ToString();
e.Row.Cells[1].ForeColor = System.Drawing.Color.Red;
}
}
Hello Friends my Pagination works fine, but when sort any column, it gets sorted on first page but on next pages sorting gets lost.
Please any one can help me to figure this out.
My Markup Code for .aspx
<asp:TemplateField HeaderText="Actions" ItemStyle-Width="20%">
<ItemTemplate>
<span class="glyphicon glyphicon-eye-open"></span>View
</span>Edit
</span>Delete
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Substance_ID" HeaderText="Substance ID" SortExpression="Substance_ID" />
<asp:TemplateField HeaderText="CAS Number" ItemStyle-Width="10%" SortExpression="CAS_Number">
<ItemTemplate>
<%# Eval("CAS_Number").ToString().Trim()%>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="EC Number" ItemStyle-Width="10%" SortExpression="EC_Number">
<ItemTemplate>
<%# Eval("EC_Number").ToString().Trim()%>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Substance Name" SortExpression="Substance_Name">
<ItemTemplate>
<%#Eval("Substance_Name").ToString().Trim()%>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Primary SG ID" ItemStyle-Width="10%" SortExpression="Primary_SG_ID">
<ItemTemplate>
<%#Eval("Primary_SG_ID")%>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Status" ItemStyle-Width="5%" SortExpression="Status">
<ItemTemplate>
<%#Eval("Status")%>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<PagerStyle CssClass="my_pagination" />
<PagerSettings Mode="NumericFirstLast" FirstPageText="First" LastPageText="Last" PageButtonCount="10" />
<EmptyDataTemplate>No Data</EmptyDataTemplate>
</asp:GridView>
<asp:Label runat="server" ID="lblCount"></asp:Label>
And My Code Behind:
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
BindGridViewData();
}
}
private void BindGridViewData()
{
List<Substance_Display> Substance_List = new List<Substance_Display>();
Substance_List = Substance_MasterAccessLayer.GetAllSubstances("Substance_ID");
Substance_Master.DataSource = Substance_List;
Substance_Master.DataBind();
lblCount.Text = "Total " + Substance_List.Count().ToString() + " Records found.";
}
protected void Substance_Master_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
Substance_Master.PageIndex = e.NewPageIndex;
Substance_Master.DataBind();
}
private void SortGridView(GridView Substance_Master, GridViewSortEventArgs e, out SortDirection sortDirection, out string sortField)
{
sortField = e.SortExpression;
sortDirection = e.SortDirection;
if (Substance_Master.Attributes["CurrentSortField"] != null & Substance_Master.Attributes["CurrentSortDirection"] != null)
{
if (sortField == Substance_Master.Attributes["CurrentSortField"])
{
if (Substance_Master.Attributes["CurrentSortDirection"] == "ASC")
{
sortDirection = SortDirection.Descending;
}
else
{
sortDirection = SortDirection.Ascending;
}
}
Substance_Master.Attributes["CurrentSortField"] = sortField;
Substance_Master.Attributes["CurrentSortDirection"] = (sortDirection == SortDirection.Ascending ? "ASC" : "DESC");
}
}
protected void Substance_Master_Sorting(object sender, GridViewSortEventArgs e)
{
SortDirection sortDirection = SortDirection.Ascending;
string sortField = string.Empty;
SortGridView(Substance_Master, e, out sortDirection, out sortField);
string strSortDirection = sortDirection == SortDirection.Ascending ? "ASC" : "DESC";
Substance_Master.DataSource = Substance_MasterAccessLayer.GetAllSubstances(e.SortExpression + " " + strSortDirection);
Substance_Master.DataBind();
}
EDIT: I would suggest the following to fix the issue:
Change your Page_Load method to this:
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
Substance_Master.Attributes["CurrentSortField"] = "Substance_ID";
Substance_Master.Attributes["CurrentSortDirection"] = "ASC";
BindGridViewData();
}
}
And change the Substance_Master_PageIndexChanging method to this:
protected void Substance_Master_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
Substance_Master.PageIndex = e.NewPageIndex;
var sortField = Substance_Master.Attributes["CurrentSortField"];
var sortDirection = Substance_Master.Attributes["CurrentSortDirection"];
if (sortField != null && sortDirection != null)
{
Substance_Master.DataSource = Substance_MasterAccessLayer.GetAllSubstances(sortField + "" + sortDirection);
}
Substance_Master.DataBind();
}
Explanation: You need to set the datasource of GridView before databind in PageIndexChanging event method. And you may need to sort the datasource depending on the current sort conditions.
<asp:TemplateField HeaderText="Status" ItemStyle-Width="15%">
<ItemTemplate>
<asp:Image ID="Status" runat="server" />
</ItemTemplate>
</asp:TemplateField>
I have this Column in my grid view and there is no column as status in my table, I do rowdatabound to display a image based on the values in other columns,
protected void MyGrid_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
Image img = (Image)e.Row.FindControl("Status");
DateTime received;
DateTime read;
DateTime.TryParse(Convert.ToString(DataBinder.Eval(e.Row.DataItem, "TimeReceived")), out received);
DateTime.TryParse(Convert.ToString(DataBinder.Eval(e.Row.DataItem, "TimeRead")), out read);
if (received == DateTime.MinValue)
{
img.ImageUrl = "Styles/Images/red.png";
img.ToolTip = "Message Not Received";
}
else (read == DateTime.MinValue)
{
img.ImageUrl = "Styles/Images/amber.png";
img.ToolTip = "Message Received";
}
img.Visible = true;
}
}
How do I sort the status column, Other column I have sort expression as column name and I am sorting it. But for this column with image how can I do the sort.
I normally already have a property on my object from the backend set that would hold the "Status", then you could sort on it and still apply your UI logic.
<asp:TemplateField HeaderText="Status" SortExpression="MessageStatus">
<ItemTemplate>
<asp:Image ID="Status" runat="server" />
</ItemTemplate>
</asp:TemplateField>
public YourObject
{
public string MessageStatus {get; set;}
..........
}
Put logic in the business layer when calling the query:
//call db
//fill object
//while filling object
DateTime received = this.TimeReceived
DateTime read = this.TimeRead
if (received == DateTime.MinValue)
{
MessageStatus = "Message Not Received";
}
else (read == DateTime.MinValue)
{
MessageStatus = "Message Received";
}
RowDataBound:
protected void MyGrid_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
Image img = (Image)e.Row.FindControl("Status");
string messsageStatus = DataBinder.Eval(e.Row.DataItem, "MessageStatus") as string;
if (messsageStatus == "Message Not Received")
{
img.ImageUrl = "Styles/Images/red.png";
img.ToolTip = messsageStatus ;
}
else if (messsageStatus == "Message Received")
{
img.ImageUrl = "Styles/Images/amber.png";
img.ToolTip = messsageStatus ;
}
img.Visible = true;
}
}
Add a SortExpression to your template that names another field that you can sort on.
<asp:TemplateField HeaderText="Status" SortExpression="SomeOtherColumn">
<ItemTemplate>
<asp:Image ID="Status" runat="server" />
</ItemTemplate>
</asp:TemplateField>
How to apply basic sorting in the gridview? Below is the gridview code.
<asp:TemplateField SortExpression="Sample1">
<HeaderTemplate SortExpression="Sample1">
<asp:Literal ID="litSample1" runat="server" Text="<%$ Resources:Resource, gvColSample1 %>"></asp:Literal>
<asp:DropDownList ID="ddlSample1" runat="server" OnSelectedIndexChanged="SelectionChanged" AutoPostBack="true" CssClass="dropdownS" AppendDataBoundItems="true">
<asp:ListItem Text=" " Value="-1"></asp:ListItem>
<asp:ListItem Text="ALL" Value="ALL"></asp:ListItem>
</asp:DropDownList>
</HeaderTemplate>
<ItemTemplate>
<%# Eval("RowSample1") %>
</ItemTemplate>
</asp:TemplateField>
As you can see the header template contains a literal. So how to apply sorting? will the addition of literal make a difference in applying sorting?
Use sort expression with template field and use the following code for sorting. ITs working perfectly fine for me.
protected void gvTool_Sorting(object sender, GridViewSortEventArgs e)
{
if (ViewState["sortMode"] == null)
{
ViewState["sortMode"] = SORT_DESC;
}
if (ViewState["sortMode"] != null)
{
if (Convert.ToString(ViewState["sortMode"]).Trim().Equals(SORT_ASC))
{
ViewState["sortMode"] = SORT_DESC;
}
else
{
ViewState["sortMode"] = SORT_ASC;
}
}
string sortexpr = e.SortExpression;
ViewState["sortexpr"] = e.SortExpression;
sort();
}
protected void sort()
{
if (ViewState["sortexpr"] != null)
{
DataView dvTool = default(DataView);
DataTable dtTool = new DataTable();
dtTool = (DataTable)ViewState["dtTool"];
if ((dtTool != null))
{
if (dtTool.Rows.Count > 0)
{
dvTool = dtTool.DefaultView;
dvTool.Sort = ViewState["sortexpr"].ToString().Trim() + " " + ViewState["sortMode"];
gvTool.DataSource = dvTool;
gvTool.DataBind();
}
}
}
}