将带有DateTime列的GridView.DataSource转换为datatable

时间:2013-08-21 15:19:25

标签: c# asp.net entity-framework gridview

我正在尝试最终对gridview进行排序,但是当我转换时:

DataTable dt = (DataTable)gridAllTests.DataSource;

有一个例外 - 无法将对象DateTime转换为String。

数据源来自数据库sql server,使用Entity GridView的:

<asp:GridView ID="gridAllTests" runat="server" AutoGenerateColumns="false" 
DataKeyNames="testId" AllowSorting="true">

 <Columns>    
    <asp:BoundField DataField="courseName" HeaderText="Course" SortExpression="courseName"/>
    <asp:BoundField DataField="onDate" HeaderText="Date" SortExpression="onDate" 
        DataFormatString="{0:d}" HtmlEncode="false"/>
    <asp:BoundField DataField="lastRegisterDate" HeaderText="LastDate" 
        SortExpression="lastRegisterDate" DataFormatString="{0:d}" HtmlEncode="false"/>   
    <asp:TemplateField>
        <ItemTemplate>
        <asp:LinkButton ID="btnRegister" runat="server" text="Register" 
            CommandName="Register" CommandArgument='<%#Eval("testId") %>' />
            <asp:Literal ID="litAlreadyRegisterd" runat="server" Text="Registered"/>
            <asp:Literal ID="litTooLate" runat="server" Text="Registration Over"/>
        </ItemTemplate>
        </asp:TemplateField>
    </Columns>

SecondTestEntities1 db = new SecondTestEntities1();
    protected void Page_Load(object sender, EventArgs e)
    {      
        if (!Page.IsPostBack)
        {
            User currUser = (User)Session["user"];
            gridAllTests.DataSource = from test in db.Tests
                                     select new
                                     {
                                         testId= test.TestId,
                                         courseName = test.Course.Name,
                                         onDate = test.OnDate,
                                         lastRegisterDate = test.LastRegisterDate
                                     };
            try
            {
                gridAllTests.DataBind();
                DataTable dt = (DataTable)gridAllTests.DataSource;
                Session["taskTable"] = dt;
            }
            catch (Exception err)
            {
                lblError.Text = err.Message.ToString();
            }
        }

        if (gridAllTests.Rows.Count < 1)
        {
            lblMessage.Visible = true;
        }       
    }

3 个答案:

答案 0 :(得分:0)

试试这种方式

          DataView dv=(DataView) from test in db.Tests
                                     select new
                                     {
                                         testId= test.TestId,
                                         courseName = test.Course.Name,
                                         onDate = test.OnDate,
                                         lastRegisterDate = test.LastRegisterDate
                                     };
         gridAllTests.DataSource = dv;

        DataTable dt = new DataTable();      

        DataSourceSelectArguments args = new DataSourceSelectArguments();

        DataView dv = new DataView();
        dv = (DataView)dv.Select(args);// This SqlDataSourceObject means your sql query return object ,like dataset or dataview, etc

        dt = dv.ToTable();

答案 1 :(得分:0)

尝试将日期对象转换为字符串

test.OnDate.ToString(//format here);

test.LastRegisterDate.ToString(//format here);

我想我遇到过类似的问题,DataTable不知道如何处理DateTime对象。

答案 2 :(得分:0)

if (!Page.IsPostBack)
        {
            User currUser = (User)Session["user"];
           //  Dataset dsGrdDource = new Dataset();
            IEnumerable<DataRow> result = from test in db.Tests
                                  select new
                               {
                                  testId= test.TestId,
                                  courseName = test.Course.Name,
                                  onDate = test.OnDate.ToShortDateString() ,
                                  lastRegisterDate = test.LastRegisterDate
                               };

          DataTable dtgrdSource= query.CopyToDataTable<DataRow>();
       try
         { 

                 gridAllTests.DataSource =dtgrdSource;
                 gridAllTests.DataBind();
               //  DataTable dt = (DataTable)dsGrdDource.Tables[0];
                Session["taskTable"] = dtgrdSource;
            } 

            catch (Exception err)
            {
                lblError.Text = err.Message.ToString();
            }
        }

如果您使用的是ToShortDateString(),请不要在boundfield应用格式,因为日期格式无法应用于字符串。 如果您不想使用ToShortDateString(),请尝试使用上面没有ToShortDateString()的代码,并在BoundField上使用格式。