Invalid case exception - linq

In report page i have dropdown and datepicker fromdate and todate and button
so when i select values from dropdown and datepicker then this show error
on this line
dt=report(Convert.ToDateTime(fromdate), Convert.ToDateTime(todate), Convert.ToString(DropDownList1.SelectedValue));
error
An exception of type 'System.InvalidCastException' occurred in mscorlib.dll but was not handled in user code
Additional information: Unable to cast object of type 'System.Web.UI.HtmlControls.HtmlInputText' to type 'System.IConvertible'
.
code
protected void Button1_Click(object sender, EventArgs e)
{
dt=report(Convert.ToDateTime(fromdate), Convert.ToDateTime(todate), Convert.ToString(DropDownList1.SelectedValue));
GridView1.DataSource = dt;
GridView1.DataBind();
}
DataTable dt = new DataTable();
public DataTable report(DateTime fromdate,DateTime todate,string IMEI)
{
DateTime fromdatee = Convert.ToDateTime(Request.Form["fromdate"]);
DateTime todatee = Convert.ToDateTime(Request.Form["todate"]);
Entities track = new Entities();
DateTime fr_date = new DateTime(fromdatee.Year, fromdatee.Month, fromdatee.Day, 0, 0, 0);
DateTime t_date = new DateTime(todatee.Year, todatee.Month, todatee.Day, 23, 59, 59);
List<spGetReport_Result> report = track.spGetReport(IMEI,fr_date,t_date).ToList();
dt.Columns.Add("Time",typeof(DateTime));
dt.Columns.Add("X",typeof(float));
dt.Columns.Add("valuenumber",typeof(int));
foreach(var c in report)
{
dt.Rows.Add(c.Time, c.X, c.valuenumber);
}
return dt;
}
HTML
<form id="form1" runat="server">
<div>
<span>
<asp:DropDownList ID="DropDownList1" runat="server"></asp:DropDownList>
</span>
<span>
<input id="fromdate" runat="server" clientidmode="static" />
</span>
<span>
<input id="todate" runat="server" clientidmode="static" />
</span>
<span>
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
</span><br />
<asp:Label ID="Label1" style="margin-left: 220px;" runat="server" Text="Export to"></asp:Label>
<asp:GridView ID="GridView1" runat="server" class="display nowrap"
Width="100%" CellPadding="0"
Font-Names="Verdana" BackColor ="White" BorderColor="#CCCCCC" BorderStyle="None"
BorderWidth="1px" Font-Size="9pt">
<FooterStyle BackColor="White" ForeColor="#000066" />
<HeaderStyle BackColor="#006699" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="White" ForeColor="#000066" HorizontalAlign="Left" />
<RowStyle ForeColor="#000066" />
<SelectedRowStyle BackColor="#669999" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#F1F1F1" />
<SortedAscendingHeaderStyle BackColor="#007DBB" />
<SortedDescendingCellStyle BackColor="#CAC9C9" />
<SortedDescendingHeaderStyle BackColor="#00547E" />
</asp:GridView>
</div>
</form>

Because you are sending Convert.ToDateTime the HTML control instead of the string to be converted.
You should be doing this:
dt = report(Convert.ToDateTime(fromdate.Value), Convert.ToDateTime(todate.Value), DropDownList1.SelectedValue);
A very simple debugging process would have quickly showed you where the problem was.
DropDownList1.SelectedValue is already a string, so no point in converting it.
Anyway, you should check first that what's in those inputs are really valid DateTime representations by using a validator.

Related

RadComboBox with checkboxes in Radgrid - select values from the table

I have a RadComboBox with checkboxes in Radgrid. User is able to select multiple values and data is saved into database. The problem I am having is, how to display already selected values when pulling data from database.
<telerik:RadGrid RenderMode="Lightweight" AutoGenerateColumns="false" ID="grd_incontact_settings" BorderWidth="0" Font-Size="Smaller" Width="100%" ShowFooter="True" AllowPaging="True" runat="server" PageSize="250" PagerStyle-AlwaysVisible="true"
OnNeedDataSource="grd_incontact_settings_NeedDataSource" AllowAutomaticInserts="True" OnInsertCommand="grd_incontact_settings_InsertCommand">
<GroupingSettings CaseSensitive="false"></GroupingSettings>
<MasterTableView AutoGenerateColumns="false" CommandItemDisplay="TopAndBottom" DataKeyNames="Id" EditMode="InPlace" ShowHeader="true">
<Columns>
<telerik:GridBoundColumn DataField="Id" UniqueName = "Id" AllowFiltering="false" Display ="false">
</telerik:GridBoundColumn>
<telerik:GridTemplateColumn HeaderText="Days" HeaderStyle-Width="150px" ItemStyle-Width="150px" UniqueName="ScheduleDays">
<ItemTemplate>
<%# Eval("ScheduleDays") %>
</ItemTemplate>
<EditItemTemplate>
<telerik:RadComboBox RenderMode="Lightweight" runat="server" ID="ddl_ScheduleDays" CheckedItemsTexts="DisplayAllInInput" CheckBoxes="true" SelectedValue='<%#Bind("ScheduleDays") %>' >
<Items>
<telerik:RadComboBoxItem Text="None" Value= 0 runat="server" />
<telerik:RadComboBoxItem Text="Monday" Value= 1 runat="server" />
<telerik:RadComboBoxItem Text="Tuesday" Value= 2 runat="server" />
<telerik:RadComboBoxItem Text="Wednesday" Value= 4 runat="server" />
<telerik:RadComboBoxItem Text="Thursday" Value= 8 runat="server" />
<telerik:RadComboBoxItem Text="Friday" Value= 16 runat="server" />
<telerik:RadComboBoxItem Text="Saturday" Value= 32 runat="server" />
<telerik:RadComboBoxItem Text="Sunday" Value= 64 runat="server" />
</Items>
</telerik:RadComboBox>
</EditItemTemplate>
</telerik:GridTemplateColumn>
</Columns>
</MasterTableView>
</telerik:RadGrid>
Code Behind:
protected void grd_incontact_settings_NeedDataSource(object source, GridNeedDataSourceEventArgs e)
{
List<SP_InContactSettings_Get_Result> lst_incontact_settings = new List<SP_InContactSettings_Get_Result>();
using (var db = new data.tarpasql())
{
lst_incontact_settings = db.SP_InContactSettings_Get().ToList();
}
grd_incontact_settings.DataSource = lst_incontact_settings;
}
public partial class SP_InContactSettings_Get_Result
{
public int Id { get; set; }
public List<int> ScheduleDays { get; set; }
}
This is what I am getting:

GridView DynamicField child property generates "table does not have column" error

I'm having a problem with DynamicFields in a GridView. I'm trying to get a field with a property from a related entity, something like "Customer.Name" in an Order entity but always get the error "The table 'Order' does not have a column named 'Customer.Name'."
I'm including the Customer entity in linq query.
If I change DynamicField by BoundField all works fine.
Edit: This is the code...
<asp:GridView ID="grvActivities" runat="server"
Caption="<%$ Resources:QuasarApp, MyOpenActivities %>" AutoGenerateColumns="false"
DataKeyNames="ActivityId" ItemType="Quasar.Model.Activity"
ShowHeaderWhenEmpty="True" AllowSorting="True"
ShowFooter="True" CssClass="table table-striped table-bordered table-hover table-condensed table-responsive"
SelectMethod="grvActivities_GetData"
UpdateMethod="grvActivities_UpdateItem"
OnRowCommand="grvActivities_RowCommand">
<Columns>
<asp:HyperLinkField ControlStyle-CssClass="nounderline fa fa-edit"
DataNavigateUrlFields="ActivityId" DataNavigateUrlFormatString="~/Activities/Edit.aspx?RecordId={0}"
ItemStyle-Width="25px" ItemStyle-HorizontalAlign="Center" ItemStyle-VerticalAlign="Middle" />
<asp:TemplateField ShowHeader="false">
<ItemTemplate>
<asp:LinkButton ID="Complete" runat="server" CommandName="Complete" CommandArgument='<%# Eval("ActivityId") %>'
CssClass="nounderline fa fa-check-square-o" ToolTip="<%$ Resources:QuasarApp, MarkAsCompleted %>" />
</ItemTemplate>
</asp:TemplateField>
<asp:DynamicField DataField="StartDate" DataFormatString="{0:g}" />
<asp:DynamicField DataField="DueDate" DataFormatString="{0:g}" />
<asp:DynamicField DataField="EndDate" DataFormatString="{0:g}" />
<asp:DynamicField DataField="Name" />
<asp:DynamicField DataField="Activity.Customer.Name" />
<asp:DynamicField DataField="Lead" />
<asp:DynamicField DataField="PriorityLevel" />
<asp:DynamicField DataField="ActivityType" />
<asp:DynamicField DataField="Status" />
<asp:DynamicField DataField="CreatedBy" />
<asp:ButtonField ButtonType="Link" CommandName="Delete" ControlStyle-CssClass="nounderline fa fa-eraser"
ItemStyle-Width="25px" ItemStyle-HorizontalAlign="Center" ItemStyle-VerticalAlign="Middle" />
</Columns>
</asp:GridView>
Codebehind:
public IQueryable<Activity> grvActivities_GetData()
{
var query = _uow.Activities.GetMany(a =>
a.IsActive
&& a.AccountManagerId == currentAccountManager
&& a.EndDate == null,
q => q.OrderByDescending(s => s.StartDate),
includeProperties: "Customer, Lead, ActivityType");
return query;
}
Edit2:
Hi, I've found that with this column:
<asp:TemplateField HeaderText="<%$ Resources:QuasarApp, Customer %>">
<ItemTemplate>
<asp:Label Text="<%# Item.Customer != null ? Item.Customer.Name : String.Empty %>" runat="server" />
</ItemTemplate>
</asp:TemplateField>
it works fine, but I'm loosing all sorting, etc., capabilities. Why if navigation property is comming in the datasource, DynamicField cannot found this property?
For navigational properties you should use only this:
<asp:DynamicField DataField="Customer" />
Dynamic data will show the first string property of your class. Or you can force with annotations:
[DisplayColumn("Name")]
public class Customer
But if you are using EF6 it's necessary to install the provider
[http://blogs.msdn.com/b/webdev/archive/2014/02/28/announcing-the-release-of-dynamic-data-provider-and-entitydatasource-control-for-entity-framework-6.aspx][1]
and register your model in global.asax.cs:
void Application_Start(object sender, EventArgs e)
{
MetaModel DefaultModel = new MetaModel();
DefaultModel.RegisterContext(new Microsoft.AspNet.DynamicData.ModelProviders.EFDataModelProvider(
() => new YOURCONTEXT()),
new ContextConfiguration { ScaffoldAllTables = false });
}
and finally set the page_init code:
protected void Page_Init()
{
grvActivities.SetMetaTable(MetaTable.GetTable(typeof(Activity)));
}

0x800a139e - SyntaxError - Telerik RadGrid

i'm trying to execute one jquery function, but it giver me an error and i don't know what is going on. It is really kiling me. I don't know what else i can do.
If someone know's how to fix it, please help me.
error:
Exception was thrown at line 5263, column 7 in localhost:8538/Scripts/jquery-1.8.2.js
0x800a139e - JavaScript runtime error: SyntaxError
<%# Page Title="Home Page" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication1._Default" %>
<%# Register assembly="Telerik.Web.UI" namespace="Telerik.Web.UI" tagprefix="telerik" %>
<asp:Content runat="server" ID="FeaturedContent" ContentPlaceHolderID="FeaturedContent">
<script src="Script/jquery-1.8.2.js"></script>
<script>
$(document).ready(function () {
setpager();
});
function setpager() {
$("#grdTeste .rgPagerCell:first").find('div').not(".rgInfoPart").css('display', 'none');
$("#grdTeste .rgPagerCell:last").find('.rgInfoPart').css('display', 'none');
}
</script>
<section class="featured">
<div class="content-wrapper">
<hgroup class="title">
<h1><%: Title %></h1>
</hgroup>
</div>
</section>
<table width="100%" height="100%" cellspacing="0" cellpadding="0" border="0">
<tbody>
<tr>
<td width="50%" valign="bottom" height="25">
<font id="tituloTela" style="padding-left:6px"> Feriados </font>
<input id="Button1" type="button" value="button" onclick="setpager();"/>
</td>
</tr>
</tbody>
</table>
</asp:Content>
<asp:Content runat="server" ID="BodyContent" ContentPlaceHolderID="MainContent">
<telerik:RadGrid ID="grdTeste" runat="server" AllowAutomaticDeletes="True" AllowAutomaticInserts="True" AllowAutomaticUpdates="True" AllowPaging="True" AllowSorting="True" CellSpacing="0"
DataSourceID="SqlDataSource" GridLines="None" PageSize="5" OnNeedDataSource="RadGrid1_NeedDataSource" >
<ExportSettings>
<Pdf PageWidth="">
</Pdf>
</ExportSettings>
<MasterTableView AutoGenerateColumns="False" DataKeyNames="COD_FERIADO" DataSourceID="SqlDataSource" CommandItemDisplay="Top" >
<CommandItemSettings AddNewRecordText="Adicionar Novo Registro" RefreshText="Atualizar"/>
<Columns>
<telerik:GridBoundColumn DataField="DATA" FilterControlAltText="Filter DATA column" HeaderText="DATA" SortExpression="DATA" UniqueName="DATA">
</telerik:GridBoundColumn>
<telerik:GridBoundColumn DataField="NOME" FilterControlAltText="Filter NOME column" HeaderText="NOME" SortExpression="NOME" UniqueName="NOME">
</telerik:GridBoundColumn>
<telerik:GridBoundColumn DataField="COD_FERIADO" DataType="System.Int32" FilterControlAltText="Filter COD_FERIADO column" HeaderText="COD_FERIADO" ReadOnly="True" SortExpression="COD_FERIADO" UniqueName="COD_FERIADO">
</telerik:GridBoundColumn>
</Columns>
<EditFormSettings>
<EditColumn UniqueName="EditCommandColumn1" FilterControlAltText="Filter EditCommandColumn1 column"></EditColumn>
</EditFormSettings>
</MasterTableView>
<PagerStyle Position="TopAndBottom" AlwaysVisible="true"/>
</telerik:RadGrid>
<asp:SqlDataSource ID="SqlDataSource" runat="server" ConnectionString="<%$ ConnectionStrings:StringConexao %>"
DeleteCommand="DELETE FROM feriados WHERE (COD_FERIADO = #COD_FERIADO)"
SelectCommand="SELECT DATA, NOME, COD_FERIADO FROM feriados"
UpdateCommand="UPDATE feriados SET NOME = #NOME, DATA = #DATA WHERE (COD_FERIADO = #COD_FERIADO)"
InsertCommand="INSERT INTO feriados VALUES (NEXT VALUE FOR SEQ_FERIADO_NOVA, #DATA, #NOME)">
<DeleteParameters>
<asp:Parameter Name="COD_FERIADO" />
</DeleteParameters>
<InsertParameters>
<asp:Parameter Name="DATA" />
<asp:Parameter Name="NOME" />
</InsertParameters>
<UpdateParameters>
<asp:Parameter Name="NOME" />
<asp:Parameter Name="DATA" />
<asp:Parameter Name="COD_FERIADO" />
</UpdateParameters>
</asp:SqlDataSource>
</asp:Content>
The error is because your are using plain javascript for finding radgrid(telerik controls).
The javascript used for telerik contols is different than the normal javascript for html contols:
To find radgrid with id="grdTeste":
var grdTeste=$find("<%=grdTeste.ClientID%>"); //find radgrid
This will help you to work with radgrid on client side:
Working with Radgrid on client side

Unable to download file using AsyncPostBackTrigger in RadGrid

Hi all I am using RadGrid in my application, as I want my RadGrid not to refresh I had my RadGrid in an Update Panel as follows
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Always">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="RadGrid1" EventName="ItemCommand" />
<%--<asp:PostBackTrigger ControlID="RadGrid1" />--%>
</Triggers>
<ContentTemplate>
<telerik:RadGrid ID="RadGrid1" runat="server" AutoGenerateColumns="false" OnItemCommand="RadGrid1_ItemCommand"
OnNeedDataSource="RadGrid1_NeedDataSource">
<MasterTableView Width="950" AutoGenerateColumns="false" DataKeyNames="EmpID" GridLines="None"
TableLayout="Auto">
<Columns>
<telerik:GridBoundColumn DataField="EmpID" HeaderText="Emp ID" ReadOnly="true" HeaderStyle-HorizontalAlign="Left"
ItemStyle-HorizontalAlign="Left" UniqueName="EmpID" FilterControlWidth="30px"
AutoPostBackOnFilter="true" CurrentFilterFunction="Contains" />
<telerik:GridButtonColumn DataTextField="ButtonName" ItemStyle-ForeColor="Blue" CommandName="Generate"
ConfirmTextFields="ButtonName" ConfirmTextFormatString="Would you like to {0} ACH file ?"
ConfirmDialogType="RadWindow" Reorderable="false" UniqueName="ButtonName" ConfirmTitle="ACH File">
</telerik:GridButtonColumn>
<telerik:GridBoundColumn DataField="EmployeeName" HeaderText="Employee Name" ReadOnly="true"
HeaderStyle-HorizontalAlign="Left" ItemStyle-HorizontalAlign="Left" UniqueName="EmployeeName"
FilterControlWidth="60px" AutoPostBackOnFilter="true" CurrentFilterFunction="Contains" />
</Columns>
</MasterTableView>
</telerik:RadGrid>
</ContentTemplate>
</asp:UpdatePanel>
When I click on download button I am unable to download the file this is my code in Itemcommand
protected void RadGrid1_ItemCommand(object sender, Telerik.Web.UI.GridCommandEventArgs e)
{
if (e.CommandName == "Generate")
{
Response.ContentType = "text/plain";
Response.AppendHeader("Content-Disposition", "attachment;filename= errorLog.txt");
Response.AddHeader("content-length", "0");
Response.Flush();
Response.End();
}
}
Can some one help me how can I work out this using AsyncPostBackTrigger
You cannot call Response with AsyncPostBack. It is Ajax Framework limitation.
Updated 1/28/2013
Since you are using telerik, I prefer using RadAjaxManager. Basically, when Generate button is clicked, it uses regular post back instead of ajax. In my example, sorting still uses ajax.
<telerik:RadGrid ID="RadGrid1" AutoGenerateColumns="false" AllowSorting="True" runat="server"
OnNeedDataSource="RadGrid1_NeedDataSource" OnItemCommand="RadGrid1_ItemCommand">
<MasterTableView DataKeyNames="EmpID">
<Columns>
<telerik:GridTemplateColumn>
<ItemTemplate>
<asp:Button runat="server" CommandName="Generate" ID="GenerateButton"
Text="Generate" OnClientClick="Generate(this, event); return false;" />
</ItemTemplate>
</telerik:GridTemplateColumn>
<telerik:GridBoundColumn DataField="EmpID" HeaderText="Emp ID" UniqueName="EmpID" SortExpression="EmpID" />
<telerik:GridBoundColumn DataField="EmployeeName" HeaderText="Employee Name" UniqueName="EmployeeName" />
</Columns>
</MasterTableView>
</telerik:RadGrid>
<%-- RadAjaxManager --%>
<telerik:RadAjaxManager ID="RadAjaxManager1" runat="server">
<AjaxSettings>
<telerik:AjaxSetting AjaxControlID="RadGrid1">
<UpdatedControls>
<telerik:AjaxUpdatedControl ControlID="RadGrid1" LoadingPanelID="RadAjaxLoadingPanel1" />
</UpdatedControls>
</telerik:AjaxSetting>
</AjaxSettings>
</telerik:RadAjaxManager>
<%-- RadAjaxLoadingPanel --%>
<telerik:RadAjaxLoadingPanel ID="RadAjaxLoadingPanel1" runat="server" Skin="Default">
</telerik:RadAjaxLoadingPanel>
<telerik:RadCodeBlock ID="RadCodeBlock1" runat="server">
<script type="text/javascript">
function Generate(sender, e) {
$find("<%= RadAjaxManager1.ClientID %>").__doPostBack(sender.name, "");
}
</script>
</telerik:RadCodeBlock>
public class Employee
{
public int EmpID { get; set; }
public string EmployeeName { get; set; }
}
protected void RadGrid1_NeedDataSource(object sender, GridNeedDataSourceEventArgs e)
{
RadGrid1.DataSource = new List<Employee>
{
new Employee {EmpID = 1, EmployeeName = "John"},
new Employee {EmpID = 2, EmployeeName = "Marry"},
new Employee {EmpID = 3, EmployeeName = "Eric"}
};
}
protected void RadGrid1_ItemCommand(object sender, GridCommandEventArgs e)
{
if (e.CommandName == "Generate")
{
Response.ContentType = "text/plain";
Response.AppendHeader("Content-Disposition", "attachment;filename= errorLog.txt");
Response.AddHeader("content-length", "0");
Response.Flush();
Response.End();
}
}

Getting error while updating LINQDatasource

When I try to update a LINQ data source bound to a grid view, I get the following error:
Could not find a row that matches the given keys in the original values stored in ViewState. Ensure that the 'keys' dictionary contains unique key values that correspond to a row returned from the previous Select operation.
I have specified DataKeyNames in the grid view.
Here's the HTML:
<asp:GridView ID="TaskGridView" runat="server" AutoGenerateColumns="False"
DataKeyNames="taskid,statusid,taskdescription" DataSourceID="GridDataSource"
onrowcreated="TaskGridView_RowCreated">
<Columns>
<asp:TemplateField HeaderText="taskid" InsertVisible="False"
SortExpression="taskid">
<ItemTemplate>
<asp:Label ID="TaskId" runat="server" Text='<%# Bind("taskid") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="taskdescription"
SortExpression="taskdescription">
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("taskdescription") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="TaskDesc" runat="server" Text='<%# Bind("taskdescription") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="url" HeaderText="url" SortExpression="url" />
<asp:TemplateField HeaderText="Status">
<ItemTemplate>
<asp:DropDownList runat="server" ID="ddStatus" DataSourceID="DropDownDataSource" DataValueField="statusid" SelectedValue="<%# Bind('Statusid') %>" DataTextField="statusdescription" ></asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:LinqDataSource ID="GridDataSource" runat="server"
ContextTypeName="DailyTask.DailyTaskDBDataContext" TableName="tbl_tasks"
EnableUpdate="True">
</asp:LinqDataSource>
<asp:Button ID="btnUpdate" runat="server" onclick="btnUpdate_Click"
Text="Update" />
<asp:LinqDataSource ID="DropDownDataSource" runat="server"
ContextTypeName="DailyTask.DailyTaskDBDataContext" TableName="tbl_status">
</asp:LinqDataSource>
Here's the corresponding code:
protected void btnUpdate_Click(object sender, EventArgs e)
{
ListDictionary keyValues = new ListDictionary();
ListDictionary newValues = new ListDictionary();
ListDictionary oldValues = new ListDictionary();
try
{
keyValues.Add("taskid", ((Label)TaskGridView.Rows[0].FindControl("TaskId")).Text);
oldValues.Add("taskdescription", ((Label)TaskGridView.Rows[0].FindControl("TaskDesc")).Text);
newValues.Add("taskdescription", "New Taskk");
GridDataSource.Update(keyValues, newValues, oldValues);
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
}
I got the problem it was in the code
I just have to use int.Parse() here because taskid is primary key
keyValues.Add("taskid", int.Parse(((Label)TaskGridView.Rows[0].FindControl("TaskId")).Text));

Resources