簡體   English   中英

System.InvalidCastException:指定的強制轉換無效的C#

[英]System.InvalidCastException: Specified cast is not valid C#

您能幫忙解決此錯誤嗎? 我遵循了一個教程為我的項目創建論壇,但是我遇到了上述錯誤。謝謝您的任何建議。 錯誤行:

Int64 Forum_Id = (Int64)GridView1.SelectedValue;

我的代碼

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Forum : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        string course_Id = DropDownList1.Text;
        int ccourse_Id = Convert.ToInt32(course_Id);
        string question = TextBox1.Text;
        string posterName = TextBox2.Text;
        DateTime blog_date = DateTime.Now;
        PostForum.INSERTforum(ccourse_Id, question, posterName, blog_date);

        GridView1.DataBind();
        }



    protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
    {
        Int64 Forum_Id = (Int64)GridView1.SelectedValue;


        Session["forum_Id"] = Forum_Id;


        Response.Redirect("Thread.aspx");
    }

    protected void Button2_Click(object sender, EventArgs e)
    {

    }
}

在我的數據庫中,我有一個名為Forum的表,帶有forum_id,它是Integer不為null

嘗試這個:

Int64 Forum_Id = Convert.ToInt64(GridView1.SelectedValue.ToString());

SelectedValue可能不是Int64。 嘗試解析以獲取數值。

Int64 Forum_Id;
Int64.TryParse( GridView1.SelectedValue.ToString(), out Forum_Id);

如果您確定所選值僅包含數字字符,則可以使用以下行。

Int64值= Int64.Parse(GridView1.SelectedValue.ToString());

否則,它將引發異常。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM