How to give a GridView a SearchResultCollection datasource - asp.net

I am working on a web application (.net framework 4.0), my application role is to search in the active directory and returns the results in a SearchResultCollection.
My question is how to give my GridView the SearchResultCollection as a datasource?

First check that SearchResultsCollection inherits from IEnumerable:
http://msdn.microsoft.com/en-us/library/system.directoryservices.searchresultcollection(v=vs.110).aspx
It does, now you can use the following methods (taken from http://www.telerik.com/help/aspnet-ajax/grid-data-binding-basics.html):
NeedDataSource event - preferred method
The key to the advanced data binding of a RadGrid control is handling the NeedDataSource event. RadGrid fires the NeedDataSource event each time it needs to be bound to a data source. If, at the time of the event, the DataSource property is not set to a valid data source object, the grid will not behave correctly.
Protected Sub RadGrid1_NeedDataSource(ByVal source As Object, ByVal e As Telerik.Web.UI.GridNeedDataSourceEventArgs) Handles RadGrid1.NeedDataSource
' Ensure that SearchResultsCollection is accessible in your code-behind class or <script runat="server"> code block
RadGrid1.DataSource = SearchResultsCollection
End Sub
On Page_Load
Simple data-binding can be used in simple cases when you do not require the grid to perform complex operations such as: Inserting, deleting, and updating records through custom edit forms (WebUserControl or FormTemplate), Grouping, Hierarchy relations, Filtering, Sorting, Paging
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
RadGrid1.DataSource = SearchResultsCollection
End Sub
Edit:
Manipulate the results to get the information you need:
Private Sub rgItems_ItemDataBound(ByVal sender As Object, ByVal e As Telerik.Web.UI.GridItemEventArgs) Handles rgItems.ItemDataBound
Dim result As SearchResult = TryCast(e.Item.DataItem, SearchResult)
If searchResult IsNot Nothing Then
' Get info you need here, perhaps play with result.GetDirectoryEntry()
' Assign this data to variables, name, department , etc
' Use e.Item.FindControl("ltlDepartment").Text = department
End If
End Sub
Ensure that you define each one of these controls:
<telerik:RadGrid runat="server">
<telerik:GridTemplateColumn HeaderText="Department" UniqueName="Department">
<ItemTemplate>
<asp:Literal id="ltlDepartment" runat="server" />
</ItemTemplate>
</telerik:GridTemplateColumn>
</telerik:radGrid>

Related

How to use RadDatePicker inside RadGrid?

Wasn't able to find anything about this situation:
I have two RadDatePicker inside RadGrid for start and end date change
<telerik:RadDatePicker ID="rdpStartDate" Skin="Library" EnableEmbeddedSkins="false" CommandName="StartDateChange" runat="server" />
By itself, they work fine, but now I have a situation when I need to call method when their value has been changed (CommandName was added for this)
I know how to do this outside RadGrid, basically:
Protected Sub rdpStartDateChanged(ByVal sender As Object, ByVal e As Telerik.Web.UI.Calendar.SelectedDateChangedEventArgs) Handles rdpStartDate.SelectedDateChanged
...
...
End Sub
But I wasn't able to do this inside RadGrid, because nothings seems to trigger it.
I tried to catch my command with this (works for buttons at least):
Protected Sub rgLibraryItemCommand(ByVal sender As Object, ByVal e As GridCommandEventArgs) Handles rgLibrary.ItemCommand
But, no, it doesn't see CommandName="StartDateChange"
What I need to do to be able to catch those Date change events if RadDatePicker
is placed inside RadGrid?
You need to identify the control inside the grid which triggers the action. I'm not sure which is the way for Rad to do that but it should be similar this:
Private Sub DataGridView1_ButtonClick(sender As DataGridView, e As DataGridViewCellEventArgs) _
Handles DataGridView1.CellButtonClick
'TODO - Button Clicked - Execute Code Here
End Sub
So you need to find the events for the DataGridViewRow for Rad and substitute them with the ones cell clicking events. This example should get you started.
Subscribing to an event on a control inside a RadGrid does not work the same way, because there could be multiple copies of the control or even none at all, depending on how many records are in the Data Source. Therefore, in order to subscribe to events on these controls, you have to do it manually after the data is bound, either in the ItemCreated event or ItemDataBound event.
Protected Sub rgLibraryItemCreated(ByVal sender as Object, ByVal e As GridItemEventArgs) Handles rgLibrary.ItemCreated
If TypeOf e.Item Is GridDataItem Then
Dim item As GridDataItem = e.Item
Dim rdpStartDate As RadDatePicker = item.FindControl("rdpStartDate")
AddHandler rdpStartDate.SelectedDateChanged, AddressOf rdpStartDateChanged
End If
End Sub

ASP.NET CheckBox not checked on postback without weird hack

I have a GridView with a checkbox column. On clicking a button, all rows with the checkbox checked should be removed. I somehow stumbled upon a strange and hacky solution, and I have no idea why it works. I already searched through related SO questions already.
Related code:
Protected Sub Page_Init(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Init
' I have no idea why this is needed for the checkboxes to work...
Dim x = imageGridView.Rows
End Sub
Protected Sub RemoveButton_Click(ByVal sender As Object, ByVal e As EventArgs) Handles removeButton.Click
For Each row As GridViewRow In imageGridView.Rows
Dim selectCheckBox As CheckBox = DirectCast(row.Cells(0).FindControl("selectCheckBox"), CheckBox)
If selectCheckBox.Checked Then
Dim fileName As String = row.Cells(1).Text
ImageList.Remove(ImageList.FindLast(Function(r) r.FileName = fileName))
End If
Next
imageGridView.DataSource = ImageList
imageGridView.DataBind()
End Sub
Aspx:
<asp:GridView ID="imageGridView" runat="server">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="selectCheckBox" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
The line Dim x = imageGridView.Rows is needed for the rows to be removed. I found this after trying my RemoveButton_Click code in the Page_Init sub, then removing code until it didn't work anymore. Dim x = imageGridView is not enough, and it doesn't work to do the same thing in Page_Load.
My checkboxes are never disabled.
So, simply put, why is it necessary for me to reference imageGridView.Rows in the Page_Init for my code to work?
That is an interesting behavior. I reproduce the problem if I bind the data to the GridView in Page_Load on every postback. In that situation, the check boxes lose their selection state on postback, but not if we refer to imageGridView.Rows in Page_Init, as you observed.
The solution is to bind the data inside an If Not IsPostBack conditional block:
Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
imageGridView.DataSource = ImageList
imageGridView.DataBind()
End If
End Sub
In that case, however, we must NOT refer to imageGridView.Rows in Page_Init. Doing so causes the check boxes to lose their selection state (!?!).
From the source code of the GridView (assuming that this source is reliable), I notice that accessing the Rows collection triggers a call to EnsureChildControls which then calls CreateChildControls. I haven't been able to step into the .NET code to see what happens at that point. Calling these methods in the Page_Init event handler may come earlier than expected in the life cycle of the GridView.
By the way, accessing the HeaderRow and the FooterRow properties also triggers a call to EnsureChildControls, and has the same effect on the selection status of the check boxes.

How to htmlencode body but not heading of gridview

I have a GridView. I want the content of the cells, the actual detail data, to be html-encoded. But I want to keep the raw HTML in the heading.
That is, the heading in this case is the name of a language and the ISO code, for example "English (EN)". I want the name and code on separate lines, so I'm specifying the heading as "English<br/>(EN)".
But for the content, I want to see any HTML. If it says "<p>foobar</p>" I want the p-tags to display.
If I say "htmlencode=false", then the heading doesn't get encoded, but neither does the data.
Is there any way to say, html-encode the data, but not the heading?
If it matters, I'm building the columns in code rather than with tags in the ASP file, depending on which languages I find in my data. So here's how I'm creating the column:
For Each row As DataRow In ds.Tables(0).Rows
Dim iso2 = row("language")
Dim name = row("name")
... other code ...
Dim head = String.Format("{0}<br/>({1})", name, iso2)
gvSnippets.Columns.Add(New BoundField With {.HeaderText = head, .DataField = iso2, .HtmlEncode = False})
... other code ...
End For
(My first draft did not set HtmlEncode.)
Curious observation: In my first couple of test runs, the data did not include any HTML or entities, and the HTML in the heading was NOT encoded, I got the line break and not "<br/>". Then I did a test where there were entities in the data and the entities got html-encoded ... and so did the header. So like, ASP is apparently saying that by default, if the data has no HTML but the heading does, then don't HTML-encode the heading. But if the data has HTML, then HTML-encode both the data and the heading. So like, it's deciding dynamically whether to html-encode the heading or not.
In reply to #fnostro, here's the markup for the GridView:
<asp:GridView ID="gvSnippets" runat="server" AutoGenerateColumns="False" SkinID="skin3" EmptyDataText="No records found" Visible="false">
</asp:GridView>
There is no <Columns> markup. I build the columns completely in code. I haven't tested if the same behavior occurs in what I assume is the more normal case where you specify columns with markup.
Add these lines of code to the beginning of your loop
row("language") = HttpUtility.HtmlEncode(dr("language"))
row("name") = HttpUtility.HtmlEncode(dr("name"))
Based on my reading of the information provided in your post I have the following suggestions:
You should isolate data formatting from raw data.
Your DataTable is the data source for the GridView. The DataTable should contain only raw data, completely unformatted and unadulterated.
The DataTable gets bound to the Gridview by setting the GridView DataSource and making a call to DataBind(). Calling gvSnippets.Databind() will trigger all the databinding events associated with Gridviews which will allow you to:
Manage simple formatting and binding in the GridView Columns in the aspx markup.
Handle more complicated formatting in the code behind for specific GridView events like the RowDataBound event.
Regarding the GridView Header: HeaderText appears once at the top of the Gridview and is stored internally in GridView.HeaderRow, not on a per row basis even though every bound field has a HeaderText property.
Example excerpt gvSnippets Markup per your update:
<asp:GridView ID="gvSnippets" runat="server"
AutoGenerateColumns="False" SkinID="skin3"
EmptyDataText="No records found" Visible="false">
</asp:GridView>
Then you can do things like this in the Code Behind:
Public Class __JunkWebForm1
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
' Fill Dataset first, then:
gvSnippets.DataSource = ds.Tables(0)
' Add Columns...
gvSnippets.Columns.Add(...)
gvSnippets.Columns.Add(...)
gvSnippets.Columns.Add(...)
. . .
' This will trigger data binding events
gvSnippets.DataBind();
End Sub
Private Property HeaderTextLanguage As String
Private Property HeaderTextLanguageIso As String
Dim NeedHeaderText As Boolean = False
Private Sub gvSnippets_DataBinding(sender As Object, e As EventArgs) Handles gvSnippets.DataBinding
NeedHeaderText = True
End Sub
Private Sub gvSnippets_DataBound(sender As Object, e As EventArgs) Handles gvSnippets.DataBound
Dim this As GridView = sender
this.Columns(0).HeaderText = String.Format("{0}<br>({1})", HeaderTextLanguage, HeaderTextLanguageIso)
End Sub
Private Sub gvSnippets_RowDataBound(sender As Object, e As GridViewRowEventArgs) Handles gvSnippets.RowDataBound
Dim this As GridView = sender
Dim drv As DataRowView = e.Row.DataItem
If e.Row.RowType = DataControlRowType.DataRow Then
If NeedHeaderText Then
HeaderTextLanguage = drv("language")
HeaderTextLanguageIso = drv("iso")
NeedHeaderText = False
End If
e.Row.Cells(0).Text = Server.HtmlEncode(drv("Somefieldnameofyours"))
End If
End Sub
End Class
Addendum Dealing with Dynamic cells
For a GridView defined as:
<asp:GridView ID="gvSnippets" runat="server"
AutoGenerateColumns="False">
</asp:GridView>
I don't know how you're populating your ds but I'm using a SqlDataSource to fill a table in the Code Behind. Note there is no GridView DataSourceID above:
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
SelectCommand="select top 10 user_id, user_name, user_logon, 'English' as language, 'en' as iso from tbl_users"
ConnectionString='<%$ ConnectionStrings:MyConnectionString %>'>
</asp:SqlDataSource>
Then in the Code Behind I can do this:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
GetDataSetAndPopulate(gvSnippets)
End Sub
Private Sub GetDataSetAndPopulate(gv As GridView)
Dim view As DataView = SqlDataSource1.Select(DataSourceSelectArguments.Empty)
Dim table As DataTable = view.ToTable()
Dim ds As DataSet = New DataSet()
ds.Tables.Add(table)
For Each dc As DataColumn In ds.Tables(0).Columns
Dim field As New BoundField
field.DataField = dc.ColumnName
field.HeaderText = dc.ColumnName
gv.Columns.Add(field)
Next
gv.DataSource = ds
gv.DataBind()
End Sub
And now the Gridview is populated dynamically and you can still handle all the formatting during the DataBinding events as needed.
Here's a solution I came up with that works in my particular case.
I am building the data to populate the GridView in code. I create a DataTable, add columns to it, and then populate those columns. Like:
dim dslang=GetListOfLanguages()
dim dtgv=new DataTable()
for each row as DataRow in dslang.tables(0).rows
dim language_name=row("name")
dim language_code=row("code")
dtgv.columns.add(String.format("{0}<br/>({1})",language_name, language_code)
end for
... bunch of other stuff ...
... inside a loop that reads the data ...
dim outrow=dtgv.NewRow()
... get data for a specific language ...
outrow(language_code)=text
... later ...
my_gridview.datasource=dtgv
my_gridview.databind()
So my solution:
When creating the GridView, set HtmlEncode=false. This makes the header display correctly.
When populating the data, say
outrow(language_code)=HttpUtility.HtmlEncode(text)
So I add the data to the datatable that will ultimately be used as the datasource for the gridview already encoded, so I don't need to rely on the Gridview encoding it.
I consider this a mediocre solution, as it only works because I am populating GridView from a DataTable that I build with code. If I was populating the GridView directly from a DataSource specified in markup, or from a DataSet created by a database query, there'd be no convenient place to put the HttpUtility.HtmlEncode call.

ASP.NET FormView OnItemInserting and OnItemInserted

My code is executing the OnItemInserting function but not the OnItemInserted. Have I declared the Inserted function correctly?
aspx
<asp:FormView ID="FormView1" runat="server" DefaultMode="Insert" OnItemInserting="Insert" OnItemInserted="Inserted">
vb
Protected Sub Insert(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.FormViewInsertEventArgs) Handles FormView1.ItemInserting
' Works
End Sub
Protected Sub Inserted(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.FormViewInsertedEventArgs) Handles FormView1.ItemInserted
Response.Redirect("Login.aspx") ' Never gets here
End Sub
The code never enters the Inserted function and just refreshes the form after executing the Insert
ItemInserted event will be raised only if FormView is data-bound and the data-source handles the insert (and subsequently call backs the control after insert).
I suspect that you have not bound your form-view to any data source control (such as SqlDataSource). In case, you are planning to handle inserting into the data-store by writing custom code then you should do that part in ItemInserting event itself.

ASP.NET, VB: how to access controls inside a FormView from the code behind?

I have a checkbox and a panel inside of a FormView control, and I need to access them from the code behind in order to use the checkbox to determine whether or not the panel is visible. This is the code that I originally used, but since I put the controls inside of the FormView, it no longer works.
Protected Sub checkGenEd_CheckedChanged(ByVal sender As Object, _
ByVal e As System.EventArgs)
If checkGenEd.Checked = True Then
panelOutcome.Visible = True
Else
panelOutcome.Visible = False
End If
End Sub
I've started to figure this out based on other questions I looked up on here, but all of them were in C# instead of VB, so this is as far as I got:
Protected Sub FormView1_DataBound(ByVal sender As Object, ByVal e As System.EventArgs) Handles FormView1.DataBound
If FormView1.CurrentMode = FormViewMode.Edit Then
End If
End Sub
So yeah I'm not sure exactly how to finish it. I'm sorry, this might be pretty basic, but I'm new at this and any help would be appreciated!
EDIT: here's my code now:
Protected Sub FormView1_DataBound(ByVal sender As Object, ByVal e As System.EventArgs) Handles FormView1.DataBound
If FormView1.CurrentMode = FormViewMode.Edit Then
CheckBox checkGenEd = formview1.FindControl("checkGenEd");
Panel panelOutcome = formview1.FindControl("panelOutcome");
End If
End Sub
It's also saying that checkGenEd and panelOutcome are not declared.
EDIT: I changed my code to this but it still doesn't work:
Protected Sub FormView1_DataBound(ByVal sender As Object, ByVal e As System.EventArgs) Handles FormView1.DataBound
If FormView1.CurrentMode = FormViewMode.Edit Then
Dim checkGenEd As CheckBox = FormView1.FindControl("checkGenEd")
Dim panelOutcome As Panel = FormView1.FindControl("panelOutcome")
If checkGenEd.Checked = True Then
panelOutcome.Visible = True
Else
panelOutcome.Visible = False
End If
End If
End Sub
There aren't any errors anymore, but nothing happens when I click the checkbox. I think there needs to be some kind of event to trigger it but I don't know how you can put an event handler inside of an event handler.
With FormView, you have to use find control, as in:
CheckBox checkGenEd = (CheckBox)formview1.FindControl("checkGenEd");
Panel panelOutcome = (Panel)formview1.FindControl("panelOutcome");
You cannot reference a control directly by ID.
HTH.
In VB you need use Directcast
Dim chk As Checkbox = DirectCast(Me.FormView1.FindControl("checkgen"), Checkbox)
FormView has its own event framework. A normal control within a FormView won't generate the postback events you are looking for. I initially made the same mistake. I wanted, like you, to generate some kind of postback that could be intercepted at the server end. Once we get back to the server we can look at the values in checkboxes etc depending on whatever business rules apply. This is what I did.
First of all put all relevant controls within an
<EditItemTemplate>
section within the FormView. (There are other Template tags that may be more appropriate). To generate the postback have a button (for example) like the one below. (This has to be within the EditItemTemplate section as well):
<asp:linkbutton id="UpdateButton"
text="Update"
commandname="Update"
runat="server"/>
You can intercept this at the server with the FormView event ItemCommand. For example:
Private Sub FormView1_ItemCommand(sender As Object, e As System.Web.UI.WebControls.FormViewCommandEventArgs) Handles FormView1.ItemCommand
'your code here
End Sub
Once you are back at the server you can then start looking at the various controls to see what they hold, using findControl if necessary. The button command shown above is an example so you might want to use another control.

Resources