Using LinqDataSource with linq to sharepoint for paging - linq

I am developing a a Sharepoint 2010 visual webpart and I am trying to use LinqDataSource in it to handle paging and sorting in a GridView.
I made my datacontext and entity objects with spmetal. and now this is my code:
my mark up:
<%# Register TagPrefix="asp" Namespace="System.Web.UI.WebControls" Assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" %>
<asp:LinqDataSource runat="server" ID="LinqDataSource1" OnSelecting="MySelecting" />
<asp:GridView ID="GridView1" runat="server" AllowPaging="True" PageSize="3"
AutoGenerateColumns="False" DataSourceID="LinqDataSource1"
EnableModelValidation="True">
<Columns>
<asp:BoundField DataField="title" HeaderText="Title" />
</Columns>
</asp:GridView>
and my code:
protected void MySelecting(object sender, LinqDataSourceSelectEventArgs e)
{
TestEntitiesDataContext dc = new TestEntitiesDataContext("http://sp/sites/test");
e.Result = from item in dc.TestList
select new
{
title = item.Title,
numberField = item.NumberField.ToString()
};
}
Now the problem is when I try to view the webpart on the site I get this error:
Expression of type 'System.Int32' cannot be used for return type 'System.Object'
When I deactivate paging on grid view this error disappears.
Do you have any idea why this is happening?
I 'd be grateful of any help.

for me the following work around has helped:
LinqDataSource1.AutoPage = false;
LinqDataSource1.AutoSort = false;
in MySelecting:
e.Result = [your nice LINQ expression].Skip(e.Arguments.StartRowIndex).Take(e.Arguments.MaximumRows);
e.Arguments.TotalRowCount = [your nice LINQ expression].Count();
And if you need sorting, you should also process e.Arguments.SortExpression.

Related

Setting SelectedValue in a Telerik DropDownList in a RadGrid

I am trying to set the SelectedValue of a RadDropDownList in the EditTemplate of my RadGrid. The DataItemBound event appears to be throwing an error on compilation.
ASP.NET
<telerik:GridTemplateColumn DataField="givenAnswer" HeaderText="givenAnswer" UniqueName="givenAnswer">
<ItemTemplate>
<%# DataBinder.Eval(Container.DataItem, "givenAnswer") %>
</ItemTemplate>
<EditItemTemplate>
<telerik:RadDropDownList ID="ddlGivenAnswer" runat="server" OnItemDataBound="ddlGivenAnswer_DataBound">
<Items>
<telerik:DropDownListItem Text="Yes" Value="Yes" />
<telerik:DropDownListItem Text="No" Value="No" />
</Items>
</telerik:RadDropDownList>
</EditItemTemplate>
</telerik:GridTemplateColumn>
C#
protected void ddlGivenAnswer_DataBound(object sender, GridItemEventArgs e)
{
if ((e.Item.IsInEditMode))
{
GridEditFormItem item = (GridEditFormItem)e.Item;
RadDropDownList ddl = (RadDropDownList)item.FindControl("ddlgivenAnswer");
ddl.SelectedValue = (string)DataBinder.Eval(e.Item.DataItem, "givenAnswer").ToString();
}
}
Error
CS0123: No overload for 'ddlGivenAnswer_DataBound' matches delegate 'DropDownListItemEventHandler'
This error is being throw on the telerik:RadDropDownList open tag line in ASP.NET. What am I missing here?
Main Edit:
Error CS0123:
First typing CS0123 in Google show me that you were using wrong parameter for your event. Probably a copypast fail. Delete the even in the aspx and ask to intelisense to create a new one. Or copypast this one.
protected void ddlGivenAnswer_ItemDataBound(object sender, Telerik.Web.UI.DropDownListItemEventArgs e)
ItemDataBound:
ItemDataBound occure when a data is bound in a control.
I'am pretty sure that inline declaration are not going to fire this event.
Minor Misconception:
Why would someone change the Value of a selected element dynamically?
It's like changing the value of a vote without changing the vote him self or the name on the vote.
What you want is to check the rigth item.
To check Waldo in the drop down list :
ddlGivenAnswer.FindItemByValue("Waldo").Selected = true;
To check the right Item:
ddlGivenAnswer.FindItemByValue(
DataBinder.Eval(e.Item.DataItem, "givenAnswer").ToString()
).Selected = true;

Is it possible to get a SqlDataSource parameter from the ViewState in asp.net web forms?

I have a SqlDataSource defined in my aspx file that I use to call a StoredProcedure. It takes a hiddenField as its control parameter.
<asp:HiddenField ID="input" runat="server" />
<asp:SqlDataSource ID="source" runat="server"
ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
SelectCommand="sp" SelectCommandType="StoredProcedure">
<SelectParameters>
<asp:ControlParameter ControlID="input" Name="input" Type="String" />
</SelectParameters>
</asp:SqlDataSource>
Is there a way I can grab that parameter from the ViewState instead? Preferably while keeping the datasource definition in the aspx file.
The solution in your case is very easy. Just create your own class inherit it from Parameter and override Evaluate method.
[DefaultProperty("ViewStateKey")]
public class ViewStateParameter : Parameter
{
public string ViewStateKey
{
get
{
return (string)ViewState["ViewStateKey"] ?? string.Empty;
}
set
{
if (ViewStateKey == value)
return;
ViewState["ViewStateKey"] = value;
OnParameterChanged();
}
}
protected override object Evaluate(HttpContext context, Control control)
{
if (control == null || string.IsNullOrEmpty(ViewStateKey))
return null;
return ViewState[ViewStateKey];
}
}
After that you will be able to use your parameter like following (just remember to register it at the top of your page or in web.config):
<asp:SqlDataSource ID="source" runat="server"
ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
SelectCommand="sp" SelectCommandType="StoredProcedure">
<SelectParameters>
<my:ViewStateParameter Name="input" Type="String" ViewStateKey="input" />
</SelectParameters>
</asp:SqlDataSource>
And your parameter will get its value from viewstate by key input.
I dont feel that the code for ViewStateParameter is of the first class. Maybe you will want to decorate it with more attributes and/or extra parameter checks with assertions.
I have similar problem. I dont want to use hidden fields to bind data source parameters because of security reasons.
I have googled one work-around - use asp:label instead of hidden field (make sure Visible=false). And then your label goes to view state and you can bind label to data source parameters.

RadGrid Shows "No records to display" when there are records

I have a peculiar problem and I am not sure if anyone had come across this problem earlier. however the issue goes like this..
I have a grid with combination of TemplateColumns and BoundColumns and when I filter the grid using the filters under template columns I can see the results in UI (grid) but when I do the same in BoundColumns I do not see any results.. !!!
Funny thing is I can see the output from the query and its returns the correct number of results from DB. and its also assigned to the GridDataSource in the NeedDataSource event. however I cannot find the GridDataItem in the ItemDataBoundItem, I can fetch only headeritem, filteritem and footeritem.
It shows "No records to display" even when there are lot of records assigned to the DataSource.
Here I am attaching the screenshot, where you can see that the records count is displayed but not the records.. !!
Any help is highly appreciated.
here is the code sample
<ps:MassApprovalAjaxPanel runat="server" ID="m_UIRadAjaxPanel" LoadingPanelID="m_UIAsynBindLoadPanelInMasterPage">
<ps:MassApprovalRadGrid
runat="server"
ID="m_UIListingGrid"
SkinID="Grid_MassApproval"
OnNeedDataSource="ListingGrid_NeedDataSource"
OnItemDataBound="ListingGrid_ItemDataBound"
AllowFilteringByColumn="true"
EnableViewState="true">
<MasterTableView
DataKeyNames="CardID, WeekEnding, ClientPONumber"
ShowFooter="true">
<Columns>
<ps:NumericTextBoxTemplateColumn
UniqueName="CardID"
Width="70"
RelativeWidthRatio="90">
<ItemTemplate>
<asp:Label
runat="server"
Text='<%# string.Format("{0}/{1}", Eval(Constants.CARD_ID), Eval(Constants.VERSION)) %>' />
</ItemTemplate>
</ps:NumericTextBoxTemplateColumn>
<ps:TextBoxBoundColumn
UniqueName="ClientPONumber"
DataField="ClientPONumber"
Width="60"
RelativeWidthRatio="80" />
<telerik:GridClientSelectColumn UniqueName="SelectAll" HeaderText="All" />
</Columns>
</MasterTableView>
</ps:MassApprovalRadGrid>
</ps:MassApprovalAjaxPanel>
protected void ListingGrid_NeedDataSource(object sender, GridNeedDataSourceEventArgs e)
{
m_UIListingGrid.DataSource = RadGridUtilUI.MassApprovalResultsGet();
}
protected void ListingGrid_ItemDataBound(object sender, GridItemEventArgs e)
{
GridDataItem gridDataItem = e.Item as GridDataItem;
if (gridDataItem != null)
{
AddClientScripts(gridDataItem);
}
}
Thanks,
Preetham.
I found fix for this issue, it was quite simple and straight forward but we did not notice it.
protected void ListingGrid_NeedDataSource(object sender, GridNeedDataSourceEventArgs e)
{
m_UIListingGrid.MasterTableView.FilterExpression = string.Empty;
m_UIListingGrid.DataSource = RadGridUtilUI.MassApprovalResultsGet();
}
Telerik has two types of filtering which is inbuilt filtering and user defined filtering that we do it through our SP's and Code. so we always have to set the filter value to null before doing our custom filtering.
Mark this as answer.
Thanks,
Preetham.

unable to insert Telerik RadGrid In-Place insert using OnInsertCommand e.item

I am trying to perform an insert using teleriks rad grid. I am doing an in-place insert and using the onInsertCommand method to set the values that are to be insertted. i found this statement in telerik's documnetation:
GridEditableItem editedItem = e.Item as GridEditableItem; when i use it editedItem is getting null value and i dont know how to make it work:
Here is my code behind for InsertCommand
protected void RadGrid1_InsertCommand(Object Sender, Telerik.Web.UI.GridCommandEventArgs e)
{
GridEditableItem editedItem = e.Item as GridEditableItem;
Hashtable newValues = new Hashtable();
e.Item.OwnerTableView.ExtractValuesFromItem(newValues, editedItem);
editedItem.Edit = false;
Yieldco.RS.Libraries.BusinessObjects.UnitType u1 = new Yieldco.RS.Libraries.BusinessObjects.UnitType();
u1.Description = newValues["Description"].ToString();
u1.UnitTypeID = Convert.ToInt32(e.Item.OwnerTableView.DataKeyValues[editedItem.ItemIndex]["UnitTypeID"]);
u1.CommunityID = 1;
u1.CompanyID = 1;
u1.Bathrooms = (float)Convert.ToDouble(newValues["Bathrooms"]);
u1.Bedrooms = Convert.ToInt32(newValues["Bedrooms"]);
u1.SqFtHigh = (float)Convert.ToDouble(newValues["SqFtHigh"]);
u1.SqFtLow = (float)Convert.ToDouble(newValues["SqFtLow"]);
u1.NumOfUnits = Convert.ToInt32(newValues["NumOfUnits"]);
u1.ProCon = Convert.ToInt32(newValues["ProCon"]);
u1.OthCon = Convert.ToInt32(newValues["OthCon"]);
u1.RentHigh = (float)Convert.ToDouble(newValues["RentHigh"]);
u1.RentLow = (float)Convert.ToDouble(newValues["RentLow"]);
u1.Status = 1;
int id = MSController.SaveUnitTypes(u1);
}
and my aspx radgrid
AutoGenerateColumns="false" AllowAutomaticUpdates="false" AllowAutomaticInserts="false" DataKeyNames="UnitTypeID" GridLines="Both"
EditItemStyle-Width="24px">
<%--
--%>
' runat="server" ID="Addnew" Text="Add New" CommandName="InitInsert" />
' runat="server" ID="CancelAdd" Text="Cancel" CommandName="CancelAll" />
' runat="server" ID="InsertNew" Text="Perform Insert" CommandName="PerformInsert" />
' runat="server" ID="EditAll" Text="Edit All" CommandName="EditAll" />
0 %>' runat="server" ID="CancelEdit" Text="Cancel" CommandName="CancelAll" />
0 %>' runat="server" ID="UpdateAll" Text="Update All" CommandName="UpdateAll" OnClientClick='javascript:return confirm("Are you sure you want to Update All Records?")' />
<asp:ObjectDataSource ID="odsGetUnitTypes" runat="server"
TypeName="Yieldco.RS.Libraries.Controllers.MSController"
DataObjectTypeName="Yieldco.RS.Libraries.BusinessObjects.UnitType"
SelectMethod="GetUnitTypesByCommunityID"
InsertMethod="SaveUnitTypes"
UpdateMethod="SaveUnitTypes"
>
<SelectParameters>
<asp:Parameter DefaultValue="1" Name="CommunityID" />
</SelectParameters>
</asp:ObjectDataSource>
Please help me out to make a sucessful insertion.
Also in the Telerik documentation I saw them using e.ite.item index for getting the vdatakeyvalue but if I use it the index is always showing up as -1 so I used editedItem.ItemIndex and it works fine
Thanks in advance
To reference the insert item, you should use the following syntax (as opposed to edited item):
if(e.CommandName = RadGrid.PerformInsertCommandName)
{
GridEditableItem editItem = e.Item.OwnerTableView.GetInsertItem();
}

Binding custom property in Entity Framework

I have an employee entity in my EF model. I then added a class to the project to add a custom property
public partial class Employee
{
public string Name
{
get { return string.Format("{0} {1}", this.FirstName, this.LastName); }
}
}
On a aspx form (inside a FormView), I want to bind a DropDownList to the employee collection:
<asp:Label runat="server" AssociatedControlID="ddlManagerId"
Text="ManagerId" />
<asp:DropDownList ID="ddlManagerId" runat="server"
DataSourceID="edsManagerId"
DataValueField="Id"
DataTextField="Name"
AppendDataBoundItems="true"
SelectedValue='<%# Bind("ManagerId") %>'>
<asp:ListItem Text="-- Select --" Value="0" />
</asp:DropDownList>
<asp:EntityDataSource ID="edsManagerId" runat="server"
ConnectionString="name=Entities"
DefaultContainerName="Entities"
EntitySetName="Employees"
EntityTypeFilter="Employee"
EnableFlattening="true">
</asp:EntityDataSource>
Unfortunately, when I fire up the page, I get an error:
DataBinding: 'System.Web.UI.WebControls.EntityDataSourceWrapper' does not contain a property with the name 'Name'.
Any ideas what I'm doing wrong?
After much searching I discovered that that the EntityDataSource does not support custom properties in the partial classes. It only returns the entity that is in the model.
As per this article:
The issue is that we’re using the EntityDataSourceWrapper and not our actual entity. The solution? Stop using the wrapper!
Disable flattening, like this:
<asp:EntityDataSource
...
EnableFlattening="False"
...
</asp:EntityDataSource>
More information on Flattening is here.
Could you verify that both your partial Employee classes are in the same namespace?

Resources