Gridview header issue: call event on header - c#

Now I got this gridview, And I need the headers to be clickable, whereafter an event starts (something like OnClickHeader="header_ClickEvent"?) Ofcourse there is a SortExpression element, which enables to sort the grid, but I want to be able to start any event, like when clicking a button.
I could not find any solution within the asp:BoundField nor asp:TemplateField...
I thought a hyperlink could solve the problem, but that was a bit premature.
Also, when using a TemplateField, I find it very hard to fill the column with data.
Could anyone bring me the solution?
The Gridview:
<asp:GridView CssClass="gridview" ID="GridView1" runat="server" AllowPaging="True" AllowSorting="True" AutoGenerateColumns="False" DataKeyNames="Student_key" OnSelectedIndexChanged="GridView1_SelectedIndexChanged" PagerSettings-Visible="false" PageSize="14">
<HeaderStyle CssClass="headerstyle" />
<RowStyle CssClass="rowstyle"/>
<AlternatingRowStyle CssClass="altrowstyle" />
<Columns>
<asp:BoundField DataField="Studentnumber" HeaderText="Studentnummer" >
<HeaderStyle CssClass="header100" />
</asp:BoundField>
<asp:BoundField DataField="Prefix" HeaderText="Voorletters" >
<HeaderStyle CssClass="header75" />
</asp:BoundField>
<asp:BoundField DataField="prename" HeaderText="Voornaam" SortExpression="Voornaam">
<HeaderStyle CssClass="header75" />
</asp:BoundField>
<asp:BoundField DataField="nickname" HeaderText="Roepnaam" >
<HeaderStyle CssClass="header100" />
</asp:BoundField>
<asp:BoundField DataField="insertion" HeaderText="Tussenvoegsel" >
<HeaderStyle CssClass="header100" />
</asp:BoundField>
<asp:BoundField DataField="surname" HeaderText="Achternaam">
<HeaderStyle CssClass="header100" />
</asp:BoundField>
<asp:CommandField SelectText="show results" ShowSelectButton="True" >
<HeaderStyle CssClass="header100" />
</asp:CommandField>
</Columns>
<EmptyDataTemplate >There are no results shown, please try again.</EmptyDataTemplate>
</asp:GridView>

Funny, I had the same problem today, and, like you, I found the above solution a bit much.
Here's something that I'm happy with.
First, you need to use the CSS Friendly Control adapters. There are a lot of other benefits to this if you're using a GridView and you have any class whatsoever. It is needed in this case because it adds the necessary classes to your header based on sorting properties, which ASP.NET does not.
You don't need to change any of your code to add the adapters, just drop their DLL in your bin folder, and their .browser file in your App_Browsers folder (which you may need to add for this purpose).
(On a side node, I actually found that the adapters broke some of my other control layouts (which were styled against the default ASP.NET markup), so I ripped out all the adapter tags except the one for GridView.)
<browser refID="Default">
<controlAdapters>
<adapter controlType="System.Web.UI.WebControls.GridView"
adapterType="CSSFriendly.GridViewAdapter" />
</controlAdapters>
</browser>
Now, to get to the good part. This bit of jQuery in your document.ready event will have the desired effect.
// Make the entire column header clickable, not just the text
$('#your-table thead th.sortable').each( function() {
var href = $('a', this).attr('href');
$(this).click( new Function(href.replace(/^javascript:/, '')) );
$('a', this).attr('href', 'javascript: return false;');
});
Basically, it strips the javascript out of the link that ASP.NET places in the header, which looks like this
Qty
and puts the code into the header's click event. Then it disables the link, so that the event bubbling does not cause a conflict.
Of course, you'll need to add style rules to give the desired visual cues.
This solution degrades well, since those mythical non-javascript browsers will simply exhibit the default behavior (where you have to click on the header text).
Hope this works for you!
EDIT: I just realized that I hadn't read your question very carefully the first time. My code was designed to get the default sorting behavior when you click anywhere in the header (not just the link text). But I guess this was close enough :)
By the way, to get data into a template field similar to what ASP.NET would put there, you just add
<ItemTemplate>
<%# Eval("FieldName") %>
</ItemTemplate>
See the documentation on formatting, etc.

This is old code mind you. It can be optimized.
http://weblogs.asp.net/rajbk/archive/2006/08/04/Clickable-GridView-Headers.aspx

Related

adding GridView DataKeyNames values gives Resources.ExceptionPolicyNotFound

I'm adding a tooltip to a GridView, and am running across an interesting error. Everything works fine when I have the bound field I'm using to populate my tooltip visible. When it is hidden, the tooltips are blank (which I expected, since the data doesn't get sent when hidden). To get around this, I'm using the DataKeyNames attribute to keep the data. When this is added, it results in the Resources.ExceptionPolicyNotFound exception.
Here is the grid view (with reject reason):
<asp:GridView ID="GrdSearchResult" runat="server" AutoGenerateColumns="False" OnRowDataBound="GrdSearchResult_RowDataBound"
Width="100%" AllowPaging="True" OnPageIndexChanging="GrdSearchResult_PageIndexChanging"
EmptyDataText="No record found." PageSize="20" CssClass="GridStyle" PagerStyle-CssClass="PagerStyle" EmptyDataRowStyle-CssClass="EmptyStyle"
DataKeyNames="RejectReason">
<Columns>
<asp:BoundField HeaderText="Reject Code" DataField="RejectCode"/>
<asp:BoundField HeaderText="Claim #" DataField="ClaimNbr" />
<asp:BoundField HeaderText="Member Medicaid #" DataField="MemberMedicaidNbr" />
<asp:BoundField HeaderText="Member Name" DataField="MemberName" />
<asp:BoundField HeaderText="Provider Name" DataField="ProviderName" />
<asp:BoundField HeaderText="Check(s) Details" />
<asp:BoundField HeaderText="Date of Service" DataFormatString="{0:MM-dd-yyyy}" DataField="ServiceRange" />
<asp:BoundField HeaderText="Claims Link" />
<asp:BoundField HeaderText="RejectReason" DataField="RejectReason" Visible="false" />
</Columns>
</asp:GridView>
This is the code that uses the column, but it never gets hit prior to the error.
e.Row.Cells[0].ToolTip = e.Row.Cells[8].Text.ToString();
The goal is to set the first column's tooltip to the value of the last (9th) column.
I am still not sure what caused the error, but I've decided to handle this in a different way. Instead of hiding the data field by default, I'm hiding it after I set the tooltip.
e.Row.Cells[0].ToolTip = e.Row.Cells[8].Text.ToString();
e.Row.Cells[8].Visible = false;
The only wrinkle was getting the column header hidden as well, but I managed that with identical code in another section. The existing code uses
if (e.Row.Cells[0].Text != string.Empty)
To look at only data rows and not the header row, so I added.
else
{
e.Row.Cells[8].Visible = false;
}
After the data manipulation was done.

How to encode html data in asp / vb.net boundcolumn datagrid?

I have some data in database which I am binding it to a bound column.
Data contains many html tags.
But I want to display it as TEXT only "NOT TO RENDER IT"
I am not sure because HTMLENCODE property doesn't work with boundcolumn.
Please help.
Also just to add I have multiple datagrids binding with bind() function and are using one event handler Itemdatabound.
<asp:boundcolumn datafield="content" readonly="True" headertext="Product ID ">
<headerstyle horizontalalign="Center" width="100px"></headerstyle>
<itemstyle horizontalalign="Left" width="100px"></itemstyle>
</asp:boundcolumn>
Prevent HTML encoding in auto-generated GridView columns
extract from possible solution from above link:
<asp:TemplateField HeaderText="myLink" SortExpression="myLink">
<ItemTemplate>
<asp:Literal ID="litHyperLink" runat="server" Text='<%# Bind("myLink", "{0}") %>' />
</ItemTemplate>
</asp:TemplateField>
Or bind your own columns, also shown in above link
Server.HtmlDecode()
This will allow you to print the tags without rendering them to html.
http://msdn.microsoft.com/en-us/library/hwzhtkke(v=vs.110).aspx

AutoGenerateInsertButton in Gridview

I have the following GridView
<asp:GridView ID="GridView1" runat="server" AllowPaging="True"
OnRowCommand="GridView1_RowCommand" DataKeyNames="Chart_Id"
AutoGenerateColumns="False" EnableModelValidation="True" >
<Columns>
<asp:CommandField ShowEditButton="False" ShowDeleteButton="False" ShowInsertButton="False" />
<asp:BoundField DataField="Week" HeaderText="Week" SortExpression="Week" />
<asp:BoundField DataField="Date" HeaderText="Date" SortExpression="Date" ItemStyle-Wrap="False" />
<asp:BoundField DataField="Host" HeaderText="Host" SortExpression="Host" />
<asp:BoundField DataField="Topic_1" HeaderText="Topic 1" SortExpression="Topic_1" />
<asp:BoundField DataField="Topic_2" HeaderText="Topic 2" SortExpression="Topic_2"
HeaderStyle-Wrap="False" />
<asp:BoundField DataField="Topic_3" HeaderText="Topic 3" SortExpression="Topic_3" />
<asp:BoundField DataField="Topic_4" HeaderText="Topic 4" SortExpression="Topic_4" />
</Columns>
</asp:GridView>
By default, I have the edit/insert/cancel buttons set to false.
Then in the code behind, I want to be able to set these to true during certain conditions.
string theUser = Helpers.GetUser();
string admin = "adminName";
if (theUser == admin) {
// Set the buttons to true
}
I've been looking for ways to do this, and someone suggested to use the AutoGenerate properties, and then enable them like so:
GridView1.AutoGenerateEditButton = true;
GridView1.AutoGenerateDeleteButton = true;
GridView1.AutoGenerateInsertButton = true; // This one throws an error
Only problem is, AutogenerateInsertButton does not seem to exist, in the main ASPX page or in the code behind.
Can anyone suggest some ways for me to access these properties and set them to true?
Thank you.
Why do you think that a GridView should have an AutoGenerateInsertButton property?
A GridView is a list of GridViewRows, where each row represents a record/element/item which can be edited or deleted. But it doesn't make sense to have a insert-button for each record because it already exists.
You could follow this tutorial which shows how to use the footer-row of the GridView to insert a new record.
The property AutoGenerateInsertButton exists on the DetailsView control. Whoever designed the control probably figured that you don't need an insert button for each row in the grid, since each would essentially do the same thing.
So, maybe you could display an empty DetailsView at the bottom of the grid, or just create your own insert command using a regular Button.

How to programmatically iterate through pages of a GridView

I've created a wallboard application to display outstanding support calls for my ICT department. I've bound a number of gridviews to sqldatasources which execute a stored procedure. This is automated via asp.net ajax controls and partially refreshes the page/data every 30 seconds.
At the moment, when the number of records in the gridview goes over 9, the gridview automatically pages and shows the number of pages in the bottom right hand corner. The helpdesk can then VNC to the box which controls the screen and manually click to see what's on the next page.
What I am after is a way to programmatically (using the c# code-behind file) changing the current displayed page after 10/15 seconds or so, obviously if this is possible in the scope of the gridview. I trailed using javascript (and failed at jquery) of scrolling the gridview within a div, however this didn't work as expected.
Can anyone point me in the right example? I can't find anyone else querying this functionality via a quick Google. Any help/advice of how to fix this issue would be greatly appreciated!!
Gridview Code:
<asp:GridView ID="GridView1" ShowHeader="False" runat="server" AutoGenerateColumns="False" DataSourceID="SqlDataSource1"
GridLines="None" CellPadding="2" Font-Size="35pt" AllowPaging="True" PageSize="9">
<Columns>
<asp:BoundField DataField="ID" HeaderText="ID" SortExpression="ID">
<ItemStyle Width="15%" />
</asp:BoundField>
<asp:BoundField DataField="ASSIGNEES" HeaderText="ASSIGNEES" SortExpression="ASSIGNEES">
<ItemStyle Width="32%" Wrap="false"/>
</asp:BoundField>
<asp:BoundField DataField="title" HeaderText="title" SortExpression="title">
<ItemStyle Width="53%" Wrap="false"/>
</asp:BoundField>
</Columns>
</asp:GridView>
SqlDataSource Code:
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:FPConnectionString %>" SelectCommand="HDMonitoringOutstandingToday" SelectCommandType="StoredProcedure"></asp:SqlDataSource>
Printscreen of wallboard:
You can try something like this in a timer.
if(GridView1.PageIndex == GridView1.PageCount)
{
GridView1.PageIndex = 0;
}
else
{
GridView.PageIndex = GridView.PageIndex + 1;
}
I cant remember if you would need to add one to the PageIndex or not.
But anyway, the properties you need to work with are PageIndex and PageCount.
GridView.PageIndex
You can change pages by setting the PageIndex, how you do it is up to you see here for some examples: http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.pageindex.aspx

ASP.NET GridView doesn't display my PagerTemplate

I have the following code in my user control:
<asp:LinqDataSource ID="myLinqDataSource" runat="server" AutoSort="true"
ContextTypeName="MyDBContext" TableName="myTable" AutoPage="true"
Select="new(Edited, Activity)" Where="UserID == 4" />
<asp:GridView ID="gvTable" runat="server" ShowHeader="true"
PageSize="5" AllowPaging="true" AllowSorting="true"
DataSourceID="myLinqDataSource" AutoGenerateColumns="false"
OnRowDataBound="GridView_DataBound">
<Columns>
<asp:BoundField DataField="Edited" HeaderText="Date" DataFormatString="{0:d}" />
<asp:BoundField DataField="Activity" HeaderText="Notes" />
</Columns>
<PagerSettings Position="Bottom" />
<PagerStyle BackColor="Black" ForeColor="White" Wrap="false" />
<PagerTemplate>
Hello there
</PagerTemplate>
</asp:GridView>
For some reason, no matter what I do, the pager isn't rendered at all. Why?
It isn't even shown if I remove the PagerTemplate tag and use some standard Mode setting in PagerSettings. I'm going crazy!
UPDATE:
After doing some exhaustive googling, I find that I'm probably using a very old version of the CSS Friendly Control Adapters. I believe so since this bug has struck me as well! So how do I know what version of these adapters that I'm using? I wasn't even aware I was using them!
UPDATE 2:
The problem was that I was using an old version of CSS Friendly Control Adapters. I downloaded the latest source code, compiled it, used the new DLL and .browser file and now it works just fine. I'm leaving this question here so anyone experiencing the same issue may find help from it.
The problem was that I was using an old version of CSS Friendly Control Adapters. I downloaded the latest source code, compiled it, used the new DLL and .browser file and now it works just fine.

Categories

Resources