last image repeating in gridview - asp.net

I want to display an image in grid view cell on specific condition andthe condition fails image not to be display.
<asp:GridView ID="gvWrkLogVW" runat="server" AutoGenerateColumns="False"
onrowdatabound="gvWrkLogVW_RowDataBound"
>
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Image ID="Image1" runat="server" Width="20px" Height="20px" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
On row data bound
if (e.Row.RowType == DataControlRowType.DataRow)
{
Image img = (Image)e.Row.FindControl("Image1");
for (int i = 0; i < dtWorkLogDeatils.Rows.Count; i++)
{
if (dtWorkLogDeatils.Rows[i]["email"].ToString() == "True")
{
img.ImageUrl = "/images/mail_send.png";
}
else
{
img.ImageUrl = "";
}
}
}
the last binding image is repeating all the columns.How to assign the image to particular cell

Related

Nested gridview not showing data inside updatepanel , its shows undefined

Data not showing in nested gridview.I have tried and googled but not
getting solution. Nested gridview is placed inside the updatepanel,
collapsible works fine but data not showing in the gvCandidate grid.
It showing undefined.
<asp:UpdatePanel ID="MainUpdatePanel" runat="server">
> <ContentTemplate>
> <asp:GridView ID="gvdlgEditTestScores" runat="server" CssClass="gvdlgEditTestScores"
>
> ShowFooter="false" ShowHeader="true" EnableViewState="True" GridLines="None"
> EmptyDataText="No records found" AutoGenerateColumns="false" CaptionAlign="Left" CellPadding="0"
> CellSpacing="0" ShowHeaderWhenEmpty="True"
> OnRowDataBound="gvdlgEditTestScores_RowDataBound"> <Columns>
> <asp:TemplateField ItemStyle-CssClass="" HeaderStyle-CssClass="" HeaderText="TestScore">
> <ItemTemplate>
> <asp:TextBox ID="gvdlgEditTestScores_Vocab" runat="server" Text='<%# Eval("Vocab") %>' ReadOnly="true"></asp:TextBox>
> </ItemTemplate>
> </asp:TemplateField>
> <asp:Panel ID="pnlCandidate" runat="server" Style="display: none;">
> <asp:GridView ID="gvCandidate" runat="server" EnableViewState="True" GridLines="None"
> EmptyDataText="No records found" AutoGenerateColumns="false" CaptionAlign="Left"
> CssClass="gvCandidateAssignedHistory">
> <Columns>
> <asp:BoundField ItemStyle-Width="100px" DataField="OrderId" HeaderText="Order Id" />
> <asp:BoundField ItemStyle-Width="100px" DataField="OrderAmount" HeaderText="Amount" />
> </Columns>
> </asp:GridView>
> </asp:
Data not showing in nested gridview.I have tried and googled but not getting solution.
Nested gridview is placed inside the updatepanel, collapsible works fine but data not showing in the gvCandidate grid. It showing undefined.
>
<asp:UpdatePanel ID="MainUpdatePanel" runat="server">
> <ContentTemplate>
> <asp:GridView ID="gvdlgEditTestScores" runat="server" CssClass="gvdlgEditTestScores"
>
> ShowFooter="false" ShowHeader="true" EnableViewState="True" GridLines="None"
> EmptyDataText="No records found" AutoGenerateColumns="false" CaptionAlign="Left" CellPadding="0"
> CellSpacing="0" ShowHeaderWhenEmpty="True"
> OnRowDataBound="gvdlgEditTestScores_RowDataBound"> <Columns>
> <asp:TemplateField ItemStyle-CssClass="" HeaderStyle-CssClass="" HeaderText="TestScore">
> <ItemTemplate>
> <asp:TextBox ID="gvdlgEditTestScores_Vocab" runat="server" Text='<%# Eval("Vocab") %>' ReadOnly="true"></asp:TextBox>
> </ItemTemplate>
> </asp:TemplateField>
> <asp:Panel ID="pnlCandidate" runat="server" Style="display: none;">
> <asp:GridView ID="gvCandidate" runat="server" EnableViewState="True" GridLines="None"
> EmptyDataText="No records found" AutoGenerateColumns="false" CaptionAlign="Left"
> CssClass="gvCandidateAssignedHistory">
> <Columns>
> <asp:BoundField ItemStyle-Width="100px" DataField="OrderId" HeaderText="Order Id" />
> <asp:BoundField ItemStyle-Width="100px" DataField="OrderAmount" HeaderText="Amount" />
> </Columns>
> </asp:GridView>
> </asp:Panel> </Columns>
> </ContentTemplate>
> </asp:UpdatePanel>
<script type="text/javascript">
> function pageLoad(sender, args) {
> $(document).ready(function () {
> //NESTED GRID EXPAND
> $("[src*=plus]").one("click", plus);
> });
> }
> function plus() {
> $(this).closest("tr").after("<tr><td></td><td></td><td colspan='50' style='padding-left:2%;'>" + $(this).next().html() +
> "</td></tr>");
> $(this).attr("src", "images/main/minus.png");
> $(this).one("click", minus);
> }
> function minus() {
> $(this).attr("src", "images/main/plus.png");
> $(this).closest("tr").next().remove();
> $(this).one("click", plus);
> } </script>
>
> protected void gvDashboardTestScores_RowDataBound(object sender, GridViewRowEventArgs e)
> {
> DataTable dttable = new DataTable();
>
> dttable.Columns.Add(new DataColumn("OrderId", typeof(string)));
> dttable.Columns.Add(new DataColumn("OrderAmount", typeof(string)));
>
> DataRow dtrow = dttable.NewRow();
> dtrow[0]="100";
> dtrow[1]="150";
>
> dttable.Rows.Add(dtrow);
>
> GridView gvCandidateAssignedHistory = (GridView)e.Row.FindControl("gvCandidateAssignedHistory");
> gvCandidateAssignedHistory.DataSource = dttable;
> gvCandidateAssignedHistory.DataBind();
>
> }
Panel>
> </Columns>
> </ContentTemplate>
> </asp:UpdatePanel>
<script type="text/javascript">
> function pageLoad(sender, args) {
> $(document).ready(function () {
> //NESTED GRID EXPAND
> $("[src*=plus]").one("click", plus);
> });
> }
> function plus() {
> $(this).closest("tr").after("<tr><td></td><td></td><td colspan='50' style='padding-left:2%;'>" + $(this).next().html() +
> "</td></tr>");
> $(this).attr("src", "images/main/minus.png");
> $(this).one("click", minus);
> }
> function minus() {
> $(this).attr("src", "images/main/plus.png");
> $(this).closest("tr").next().remove();
> $(this).one("click", plus);
> } </script>
>
> protected void gvDashboardTestScores_RowDataBound(object sender, GridViewRowEventArgs e)
> {
> DataTable dttable = new DataTable();
>
> dttable.Columns.Add(new DataColumn("OrderId", typeof(string)));
> dttable.Columns.Add(new DataColumn("OrderAmount", typeof(string)));
>
> DataRow dtrow = dttable.NewRow();
> dtrow[0]="100";
> dtrow[1]="150";
>
> dttable.Rows.Add(dtrow);
>
> GridView gvCandidateAssignedHistory = (GridView)e.Row.FindControl("gvCandidateAssignedHistory");
> gvCandidateAssignedHistory.DataSource = dttable;
> gvCandidateAssignedHistory.DataBind();
>
> }
Data not showing in nested gridview.I have tried and googled but not
getting solution. Nested gridview is placed inside the updatepanel,
collapsible works fine but data not showing in the gvCandidate grid.
It showing undefined.
see this Gridview image

how to apply pagging to data list control

i just want to make data list with pagging. here is my code :
public partial class Template_Management : System.Web.UI.Page
{
PagedDataSource adsource = null;
int pos;
protected void Page_Init(object sender, EventArgs e)
{
if (!IsPostBack)
{
adsource = new PagedDataSource();
}
}
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
.....
Session["StartAlpha"] = "All";
Session["GroupByCategory"] = -1;
Session["ColumnName"] = null;
Session["SearchText"] = null;
this.FillGrid((String)Session["StartAlpha"] ?? null, (int)Session["GroupByCategory"], (String)Session["ColumnName"] ?? null, (String)Session["SearchText"] ?? null);
this.ViewState["vs"] = 0;
}
pos = (int)this.ViewState["vs"];
}
}
public void FillGrid(string StartAlpha, int GroupByCategory, string ColumnName, string SearchText)
{
if (myDataSet.Tables[0].Rows.Count > 0)
{
adsource.DataSource = myDataSet.Tables[0].DefaultView;
adsource.AllowPaging = true;
adsource.PageSize = 20;
DL_ViewTemplate.DataSource = adsource;
}
if (DL_ViewTemplate.Items.Count != 0)
{
SetPageNumbers();
}
UpdatePanel8.Update();
DL_ViewTemplate.DataBind();
}
private void SetPageNumbers()
{
foreach (DataListItem item in DL_ViewTemplate.Items)
{
if (item.ItemType == ListItemType.Footer)
{
if (pos == 0)
{
ImageButton img = (ImageButton)item.FindControl("ImageButton1");
img.Enabled = false;
}
if (pos == adsource.PageCount - 1)
{
ImageButton img = (ImageButton)item.FindControl("ImageButton4");
img.Enabled = false;
}
}
}
}
protected void DL_ViewTemplate_ItemCommand(object source, DataListCommandEventArgs e)
{
int intCurIndex = adsource.CurrentPageIndex;
switch (e.CommandArgument.ToString())
{
case "first":
adsource.CurrentPageIndex = 0;
break;
case "prev":
CurrentPage -= 1;
break;
case "next":
CurrentPage += 1;
break;
case "last":
adsource.CurrentPageIndex = adsource.PageCount;
break;
}
this.FillGrid((String)Session["StartAlpha"] ?? null, (int)Session["GroupByCategory"], (String)Session["ColumnName"] ?? null, (String)Session["SearchText"] ?? null);
}
protected void DL_ViewTemplate_ItemDataBound(object sender, DataListItemEventArgs e)
{
foreach (DataListItem item in DL_ViewTemplate.Items)
{
if (item.ItemType == ListItemType.Footer && item.ItemType == ListItemType.Item)
{
// get your controls from the gridview
DropDownList ddlPages = (DropDownList)item.FindControl("ddlPages");
Label lblPageCount = (Label)item.FindControl("lblPageCount");
if (ddlPages != null)
{
// populate pager
for (int i = 0; i < adsource.PageCount; i++)
{
int intPageNumber = i + 1;
ListItem lstItem = new ListItem(intPageNumber.ToString());
if (i == adsource.CurrentPageIndex)
lstItem.Selected = true;
ddlPages.Items.Add(lstItem);
}
}
// populate page count
if (lblPageCount != null)
lblPageCount.Text = adsource.PageCount.ToString();
}
}
}
protected void ddlPages_SelectedIndexChanged(object sender, EventArgs e)
{
foreach (DataListItem item in DL_ViewTemplate.Items)
{
if (item.ItemType == ListItemType.Footer)
{
DropDownList ddlPages = (DropDownList)item.FindControl("ddlPages");
adsource.CurrentPageIndex = ddlPages.SelectedIndex;
//a method to populate your grid
this.FillGrid((String)Session["StartAlpha"] ?? null, (int)Session["GroupByCategory"], (String)Session["ColumnName"] ?? null, (String)Session["SearchText"] ?? null);
}
}
}
}
how ever footer control with ddl doesn't filled.
for more info i place html markup :
<asp:DataList ID="DL_ViewTemplate" runat="server" RepeatColumns="6"
ShowFooter="True" HorizontalAlign="Left" RepeatDirection="Horizontal"
DataKeyField="Id" onitemcommand="DL_ViewTemplate_ItemCommand"
ShowHeader="False" onitemcreated="DL_ViewTemplate_ItemCreated"
onitemdatabound="DL_ViewTemplate_ItemDataBound" CellPadding="1"
CellSpacing="3">
<ItemStyle HorizontalAlign="Left" Wrap="True" Width="40%" />
<ItemTemplate>
<div class="thumb" align="center" style="height:150px;width:130px">
<table width="40%" align="center">
<tr>
<td>
<asp:Literal ID="Literal4" runat="server"></asp:Literal><!-- Text=<'#Eval("TemplateBody")%>'-->
<ajaxToolkit:HoverMenuExtender ID="hme1" runat="Server"
TargetControlID="Literal4"
PopupControlID="Panel2"
DynamicContextKey='<%# Eval("Id") %>'
DynamicControlID="Panel2"
DynamicServiceMethod="GetDynamicContent"
PopupPosition="Right"
OffsetX="-25"
OffsetY="15"/>
</td>
</tr>
</table>
</div>
<table width="145px" align="left" style="border-color:Black;border-style:solid;border-width:1px;height:50px">
<tr>
<td align="center">
<table>
<tr>
<td><asp:CheckBox ID="ChkSelect" runat="server" onclick = "Check_Click(this)"/></td>
<td> </td>
<td><asp:LinkButton ID="LinkButton2" runat="server" CssClass="quicklink"
Text='<%# Eval("TemplateName").ToString().Length > 12 ? Eval("TemplateName").ToString().Substring(0,12)+"..." :Eval("TemplateName") %>' CommandName="ViewTemplate"
ToolTip ='<%# Eval("TemplateName")%>' CommandArgument='<%# Eval("Id") %>'></asp:LinkButton>
<br/>
<asp:Label ID="Label2" runat="server" CssClass="normaltext"
Text='<%# DataBinder.Eval(Container.DataItem, "CreatedDate", "{0:dd/MM/yyyy}") %>'
ToolTip='<%# Bind("CreatedDate","{0:F}") %>'></asp:Label></td>
</tr>
</table>
</td>
</tr>
</table>
</ItemTemplate>
<SeparatorTemplate> </SeparatorTemplate>
<FooterTemplate>
<table>
<tr>
<td>
<asp:ImageButton ID="ImageButton1" runat="server"
AlternateText="Go to First Page" CommandArgument="First" CommandName="Page"
ImageUrl="images/1330128819_resultset_first.png" />
</td>
<td>
<asp:ImageButton ID="ImageButton2" runat="server" AlternateText="Previous Page"
CommandArgument="Prev" CommandName="Page"
ImageUrl="images/1330128981_resultset_previous.png" />
</td>
<td>
Page <asp:DropDownList ID="ddlPages" runat="server" AutoPostBack="True"
onselectedindexchanged="ddlPages_SelectedIndexChanged" Width="50px">
</asp:DropDownList>
of
<asp:Label ID="lblPageCount" runat="server"></asp:Label>
</td>
<td>
<asp:ImageButton ID="ImageButton3" runat="server" AlternateText="Next Page"
CommandArgument="Next" CommandName="Page"
ImageUrl="images/Farm-Fresh_resultset_next.png" />
</td>
<td>
<asp:ImageButton ID="ImageButton4" runat="server"
AlternateText="Go to Last Page" CommandArgument="Last" CommandName="Page"
ImageUrl="images/1330128876_resultset_last.png" />
</td>
</tr>
</table>
</FooterTemplate>
<FooterStyle CssClass="pager" VerticalAlign="Bottom"
HorizontalAlign="Center" />
</asp:DataList>
here i set adsource which was paged data source declared first and assigned in Page_Init() is it valid ?? because when ever other event want to access adsource then Object reference not found error thrown.
what am i going wrong please help me....
you can refer these links for more information on paging on datalist control in ASP.net
http://www.c-sharpcorner.com/UploadFile/718fc8/paging-in-datalist-control/
http://www.codeproject.com/Articles/14080/Implementing-Efficient-Data-Paging-with-the-Datali

When using radio button,I'm tring to hide div, the checkbox list[control itself] is not displayed

script:
$(document).ready(function () {
$('#Custom').hide('fast');
$('#rbtnEntire').click(function () {
$('#Custom').hide('fast');
$('#Entire').show('fast');
});
$('#rbtnCustom').click(function () {
$('#Entire').hide('fast');
$('#Custom').show('fast');
});
});
function showdiv() {
document.getElementById("divChkList").style.display = "block";
}
aspx file:
<div style="height:700; width:500;">
<div id="select scan type">
<asp:RadioButton ID="rbtnEntire" runat="server" Text="Entire"
GroupName="s1"/>
<asp:RadioButton ID="rbtnCustom" runat="server" Text="Custom"
GroupName="s1"/>
</div>
<div id="Entire" style="float:left; height:1000; width:1000; border: solid 1px; margin-left:5px;">
Entire<br />
<asp:TreeView ID="TreeView1" runat="server" ShowCheckBoxes="All" ShowLines="True" ExpandDepth="2">
<Nodes>
<asp:TreeNode Text="Entire">
<asp:TreeNode Text="VM">
<asp:TreeNode Text="MBS1">
</asp:TreeNode>
<asp:TreeNode Text="PF1"></asp:TreeNode>
</asp:TreeNode>
<asp:TreeNode Text="VM1">
<asp:TreeNode Text="MBS2"></asp:TreeNode>
<asp:TreeNode Text="PF2"></asp:TreeNode>
</asp:TreeNode>
</asp:TreeNode>
</Nodes>
</asp:TreeView>
<p>
<asp:Button ID="btnCreateXML" runat="server" onclick="btnCreateXML_Click"
Text="Create XML" />
<asp:Label ID="lblResult" runat="server" Text="Label"></asp:Label>
</p></div>
<div id="Custom" style="float:left; height:1000; width:2000; border: solid 1px; margin-left:10px;">
Custom <br />
<div id="Manual" style="border:solid 1px; float:left;">
Manual Scan Controls
</div>
<div id="Multiple" style="border:solid 1px; float:left;">
Multiple Scan Controls
<table>
<tr>
<td valign="top" style="width: 165px">
<asp:PlaceHolder ID="phDDLCHK" runat="server"></asp:PlaceHolder>
</td>
<td valign="top">
<asp:Button ID="btn" runat="server" Text="Get Checked" OnClick="btn_Click" />
</td>
<td valign="top">
<asp:Label ID="lblSelectedItem" runat="server"></asp:Label>
</td>
</tr>
</table>
</div>
<asp:HiddenField ID="hidList" runat="server" />
</div>
<br />
</div>
code behind:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
initialiseCheckBoxList();
rbtnEntire.Checked = true;
try
{
TreeView1.Attributes.Add("onclick", "javascript: OnTreeClick();");
}
catch(Exception)
{
Response.Write("Error Occured While onTreeClick");
}
}
}
public void initialiseCheckBoxList()
{
CheckBoxList chkBxLst = new CheckBoxList();
chkBxLst.ID = "chkLstItem";
chkBxLst.Attributes.Add("onmouseover", "showdiv()");
DataTable dtListItem = GetListItem();
int rowNo = dtListItem.Rows.Count;
string lstValue = string.Empty;
string lstID = string.Empty;
for (int i = 0; i < rowNo - 1; i++)
{
lstValue = dtListItem.Rows[i]["Value"].ToString();
lstID = dtListItem.Rows[i]["ID"].ToString();
chkBxLst.Items.Add(lstValue);
}
System.Web.UI.HtmlControls.HtmlGenericControl div = new System.Web.UI.HtmlControls.HtmlGenericControl("div");
div.ID = "divChkList";
div.Controls.Add(chkBxLst);
div.Style.Add("border", "black 1px solid");
div.Style.Add("width", "160px");
div.Style.Add("height", "130px");
div.Style.Add("overflow", "AUTO");
div.Style.Add("display", "block");
}//end of initialiseCheckBoxList()
protected void btn_Click(object sender, EventArgs e)
{
string x=string.Empty;
string strSelectedItem = "Selected Items ";
CheckBoxList chk = (CheckBoxList)phDDLCHK.FindControl("chkLstItem"); // phDDLCHK is placeholder's ID
for (int i = 0; i < chk.Items.Count; i++)
{
if (chk.Items[i].Selected)
{
if (strSelectedItem.Length == 0)
{
strSelectedItem = strSelectedItem + ":" + chk.Items[i].Text;
}
else
{
strSelectedItem = strSelectedItem + ":" + chk.Items[i].Text;
}
}
}
lblSelectedItem.Text =strSelectedItem;
}
public DataTable GetListItem()
{
DataTable table = new DataTable();
table.Columns.Add("ID", typeof(int));
table.Columns.Add("Value", typeof(string));
for (int icnt = 0; icnt < 10; icnt++)
{
table.Rows.Add(icnt, "ListItem"+":"+icnt);
}
return table;
}
Problem: When i Select radio button rbtnCustom, It should display div Custom along with the CheckboxList control,which is not happening. When I do not hide div,it is displayed. What can be done to display checkboxList control?
Here is my code, Can any one let me know where I went wrong?
Any help would be appriciated! Thanks!
The reason some of your Javascript isn't working is because you are using the server ID in the client side (Javascript) code.
<asp:RadioButton ID="rbtnCustom" runat="server" Text="Custom"
GroupName="s1"/>
Since the above control is set to runat="server" the ID attribute is setting a sever side control ID, the client ID will be generated. If you don't need access to this control on the server, it might be easier to simply use a 'input' element instead of an asp.net control. The other option would be to set the ClientIDMode="Static" so the client ID is the same as the server ID.
<asp:RadioButton ID="rbtnCustom" runat="server" Text="Custom" ClientIDMode="Static"
GroupName="s1"/>
Use this for any control if you are not setting the ID in the code behind and if you are using the ID in client side Javascript.
EDIT: You are also missing phDDLCHK.Controls.Add(div); at the end of your initialiseCheckBoxList method.
You are also not providing what javascript "OnTreeClick();" is. It is referenced in the code behind. From what I can tell you are only populating the contents of the custom checkboxlist once on the initialiseCheckBoxList.
How to use asp checkbox control as RadioButton
First we create a script like this:
<script type="text/javascript">
function check(sender) {
var chkBox;
var i;
var j;
for (i = 1; i < 6; i++) {
for (j = 1; j < 6; j++) {
if (i != j) {
if (sender.id == "ck" + i) {
chkBox = document.getElementById("ck" + j);
}
else {
chkBox = document.getElementById("ck" + i);
}
if (sender.checked) {
if (chkBox.checked) {
chkBox.checked = false;
}
}
}
}
}
}
</script>
Now we use following code for our ASP CheckBox controls
<div>
<asp:CheckBox ID="ck1" runat="server" Text="P1" onclick="check(this)"/>
<asp:CheckBox ID="ck2" runat="server" Text="P2" onclick="check(this)"/>
<asp:CheckBox ID="ck3" runat="server" Text="P3" onclick="check(this)"/>
<asp:CheckBox ID="ck4" runat="server" Text="P4" onclick="check(this)"/>
<asp:CheckBox ID="ck5" runat="server" Text="P5" onclick="check(this)"/>
</div>
Thank you...

Draw border between rows and cols of table

How to draw a border between rows and cols of the asp.net(C#) table?
I have following:
<asp:Table ID="Table1" runat="server" BackColor="White" BorderColor="Black"
BorderWidth="1px" ForeColor="Black">
</asp:Table>
in the codebehind file I add rows:
for (int i = 0; i < games.Count(); i++)
{
TableRow tr = new TableRow();
for (int j = 0; j < 9; j++)
{
TableCell tc = new TableCell();
tc.Text = games[i].getData(j);
tr.Cells.Add(tc);
}
tr.BorderWidth = 1;
tr.BorderColor = Color.Black;
Table1.Rows.Add(tr);
}
However, I I don't see any border between rows and cols of the table.
The table is:
So, how to draw borders between rows and cols of the asp.net table?
You are missing two attributes
GridLines="Both" BorderStyle="Solid"
Should be
<asp:Table ID="Table1" runat="server" BackColor="White" BorderColor="Black"
BorderWidth="1" ForeColor="Black" GridLines="Both" BorderStyle="Solid">
CSS styling is better though
I would just use CSS to draw the borders:
#table1 {
border: solid thin black;
}
#table1 td {
border: solid thin black;
}
Also, creating a table via code is BAD! You should look into using the Repeater control.

GridView Sorting CssClass not applying

I have a gridview with the following markup:
<asp:GridView ID="gv" runat="server" Width="700px" skinid="gridview" HeaderStyle-HorizontalAlign="Left" AllowPaging="true" PageSize="50" AllowSorting="true" CssClass="gv">
<SortedAscendingHeaderStyle CssClass="sort_asc" />
<SortedDescendingHeaderStyle CssClass="sort_desc" />
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="chk" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField HeaderText="Project" DataField="Project" SortExpression="Project" />
<asp:BoundField HeaderText="Type" DataField="Type" SortExpression="Type" />
</Columns>
</GridView>
However, my SortedAscendingHeaderStyle and SortedDescendingHeaderStyle CssClass's are not being applied to the HTML when sorting.
My CSS is:
.gv .sort_asc
{
display:block;
padding:0 4px 0 15px;
background:url(/Admin/Images/Icons/arrow_down.jpg) no-repeat;
}
.gv .sort_desc
{
display:block;
padding:0 4px 0 15px;
background:url(/Admin/Images/Icons/arrow_up.jpg) no-repeat;
}
What are the possible reasons for this?
Below is the way, the task can be accomplished:
In .aspx file
<asp:GridView ID="gvData" runat="server" SkinID="yourskinID"
AllowSorting="True" onsorting="gvData_Sorting">
<HeaderStyle CssClass="ascendingCssClass" /> <%-- put it into your SKIN file,
assume you're showing data in ascending initially --%>
<Columns>
</Columns>
</asp:GridView>
In .cs file
private const string ASCENDING = " ASC";
private const string DESCENDING = " DESC";
public SortDirection GridViewSortDirection
{
get
{
if (ViewState["sortDirection"] == null)
ViewState["sortDirection"] = SortDirection.Ascending;
return (SortDirection)ViewState["sortDirection"];
}
set { ViewState["sortDirection"] = value; }
}
protected void gvData_Sorting(object sender, GridViewSortEventArgs e)
{
string sortExpression = e.SortExpression;
if (GridViewSortDirection == SortDirection.Ascending)
{
GridViewSortDirection = SortDirection.Descending;
//Put your CssClass here for descending
gvData.HeaderStyle.CssClass = "descendingCssClass";
SortGridView(sortExpression, DESCENDING);
}
else
{
GridViewSortDirection = SortDirection.Ascending;
//Put your CssClass here for ascending
gvData.HeaderStyle.CssClass = "ascendingCssClass";
SortGridView(sortExpression, ASCENDING);
}
}
private void SortGridView(string sortExpression, string direction)
{
DataTable dt = GetData();
DataView dv = new DataView(dt);
dv.Sort = sortExpression + direction;
gvData.DataSource = dv;
gvData.DataBind();
}
Update:
The sample/test css is a below: I just have used it test purpose, use your appropriate styling.
tr.ascendingCssClass th a:link
{
color:Green;
background-color:White;
}
tr.ascendingCssClass th a:hover
{
color:Orange;
background-color:White;
}
tr.ascendingCssClass th a:visited
{
color:Black;
background-color:White;
}
tr.descendingCssClass th a:link
{
color: red;
background-color:Gray;
}
tr.descendingCssClass th a:hover
{
color: Yellow;
background-color:Gray;
}
tr.descendingCssClass th a:visited
{
color: Yellow;
background-color:Gray;
}
And, the DataTable function is as below:
DataTable GetData()
{
DataTable table = new DataTable("MyDataTable");
using (SqlConnection connection = new SqlConnection(YourConnectionString))
{
//Your data retrival code goes here
adapter.Fill(table); // Finally fill the datatable
}
return table;
}

Resources