关于错误“对象不能从 DBNull 转换为其他类型”

版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/zhaobw831/article/details/48754643

对象不能从 DBNull 转换为其他类型。
对于可用类型hit:
newsModel.hit = Convert.ToInt64(reader[6]);
此句会导致错误。
修正:
先判断是否为空
newsModel.hit=reader[6]==DBNull.Value?0:Convert.ToInt64(reader[6]);

展开阅读全文

对象能从 DBNull换为其他类型(c#中)

09-23

我想把access留言本转成SQL版的,结果出现如上问题,暴错71行,代码如下:rnusing System;rnusing System.Collections;rnusing System.ComponentModel;rnusing System.Data;rnusing System.Drawing;rnusing System.Web;rnusing System.Web.SessionState;rnusing System.Web.UI;rnusing System.Web.UI.WebControls;rnusing System.Web.UI.HtmlControls;rnusing System.Data.SqlClient;rnusing System.Configuration;rnnamespace baogelybrnrn /// rn /// showguestbook 的摘要说明。rn /// rn public class showguestbook : System.Web.UI.Pagern rn protected System.Web.UI.WebControls.DataList DataList1;rn protected System.Web.UI.WebControls.Label Label1;rn protected System.Web.UI.WebControls.Label Label2;rn protected System.Web.UI.WebControls.Label Label3;rn protected System.Web.UI.WebControls.Button Button3;rn protected System.Web.UI.WebControls.Button Button1;rn protected System.Web.UI.WebControls.Button Button2;rn protected System.Web.UI.WebControls.Button Button4;rn protected System.Web.UI.WebControls.TextBox TextBox1;rn protected System.Web.UI.WebControls.Button Button5;rn rn private void Page_Load(object sender, System.EventArgs e)rn rn if(!this.IsPostBack)rn rn this.Label2.Text="1";rn this.databind();rn this.TextBox1.Text="1";rn rn rnrnrnrn public string ShowReply(bool IsReplyed, string replytime, string replycontent)rn rn if (!IsReplyed)rn rn return "";rn rn elsern rn return " 管理员于 '"+replytime+"' 回复 '"+replycontent.Replace("\r\n"," ")+"";rn rn rn private void databind()rn rn // int CID=Convert.ToInt32(Request.QueryString["id"]);rn int curPage=Convert.ToInt32(this.Label2.Text);rn// string dbPath=System.Configuration.ConfigurationSettings.AppSettings["lyb"];rn// //定义连接字符串rn// string ConnStr="Provider=Microsoft.Jet.Sql.4.0;Data Source="+Server.MapPath(dbPath);rn //创建数据库对像rn// SqlConnection connection=new SqlConnection(ConnStr);rn SqlConnection connection=db.createconnection();rnrn// String mysql="SELECT * FROM lyb order by id desc";rn // String mysql="SELECT * FROM Article where ispic=true order by ArticleID desc";rn SqlDataAdapter sda=new SqlDataAdapter();rn rn sda.SelectCommand=new SqlCommand("select * from lyb",connection);rn DataSet ds=new DataSet();rn sda.Fill(ds,"lyb");rn System.Web.UI.WebControls.PagedDataSource ps=new PagedDataSource();rn ps.DataSource=ds.Tables["lyb"].DefaultView;rn ps.AllowPaging=true;rn ps.PageSize=5;rn ps.CurrentPageIndex=curPage-1;rn this.Button1.Enabled=true;rn this.Button2.Enabled=true;rn rn if(curPage==1)rn rn this.Button1.Enabled=false;rn rn if(curPage==ps.PageCount)rn rn this.Button2.Enabled=false;rn rn rn rn this.DataList1.DataSource=ps;rn this.DataList1.DataBind();rn this.Label3.Text=Convert.ToString(ps.PageCount);rn rnrn #region Web 窗体设计器生成的代码rn override protected void OnInit(EventArgs e)rn rn //rn // CODEGEN: 该调用是 ASP.NET Web 窗体设计器所必需的。rn //rn InitializeComponent();rn base.OnInit(e);rn rn rn /// rn /// 设计器支持所需的方法 - 不要使用代码编辑器修改rn /// 此方法的内容。rn /// rn private void InitializeComponent()rn rn this.Button3.Click += new System.EventHandler(this.Button3_Click);rn this.Button1.Click += new System.EventHandler(this.Button1_Click);rn this.Button2.Click += new System.EventHandler(this.Button2_Click);rn this.Button4.Click += new System.EventHandler(this.Button4_Click);rn this.Button5.Click += new System.EventHandler(this.Button5_Click);rn this.Load += new System.EventHandler(this.Page_Load);rnrn rn #endregionrnrn private void Button1_Click(object sender, System.EventArgs e)rn rn this.Label2.Text=Convert.ToString(Convert.ToInt32(this.Label2.Text)-1);rn this.databind();rn rnrn private void Button2_Click(object sender, System.EventArgs e)rn rn this.Label2.Text=Convert.ToString(Convert.ToInt32(this.Label2.Text)+1);rn this.databind();rn rnrn private void Button3_Click(object sender, System.EventArgs e)rn rn this.Label2.Text="1";rn this.databind();rn rnrn private void Button4_Click(object sender, System.EventArgs e)rn rn this.Label2.Text=Convert.ToString(Convert.ToInt32(this.Label3.Text));rn this.databind();rn rnrn private void Button5_Click(object sender, System.EventArgs e)rn rn if(this.TextBox1.Text.ToString()=="0")rn rn this.Label2.Text="1";rn this.databind();rn rn else if(this.TextBox1.Text.ToString()=="")rn rn this.Label2.Text="1";rn this.databind();rn rn rn elsern rn this.Label2.Text=Convert.ToString(this.TextBox1.Text);rn this.databind();rn rn rn rnrn 论坛

急求助:对象能从 DBNull换为其他类型

08-22

说明: 执行当前 Web 请求期间,出现未处理的异常。请检查堆栈跟踪信息,以了解有关该错误以及代码中导致错误的出处的详细信息。 rnrn异常详细信息: System.InvalidCastException: 对象不能从 DBNull 转换为其他类型。rnrn源错误: rnrnrn行 225:rn行 226: // TempStr += ""; rn行 227: if (showtime > 0) TempStr += "" + Convert.ToDateTime(dt.Rows[i]["ApprovalTime"]).ToString("M.d"); rn行 228: // if (hit > 0) TempStr += "[" + dt.Rows[i]["Hits"].ToString() + "]"; rn行 229: // if (ShowTime >0) TempStr += "[" + Convert.ToDateTime(dt.Rows[i][5].ToString()).Month + "." + Convert.ToDateTime(dt.Rows[i][5].ToString()).Day + "]";rn rnrn源文件: d:\新劳教局\template\NewsList.ascx.cs 行: 227 rnrn堆栈跟踪: rnrnrn[InvalidCastException: 对象不能从 DBNull 转换为其他类型。]rn System.DBNull.System.IConvertible.ToDateTime(IFormatProvider provider) +54rn System.Convert.ToDateTime(Object value) +29rn template_NewsList.txtList(DataTable dt) in d:\新劳教局\template\NewsList.ascx.cs:227rn template_NewsList.Page_Load(Object sender, EventArgs e) in d:\新劳教局\template\NewsList.ascx.cs:181rn System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e) +15rn System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) +34rn System.Web.UI.Control.OnLoad(EventArgs e) +99rn System.Web.UI.Control.LoadRecursive() +47rn System.Web.UI.Control.LoadRecursive() +131rn System.Web.UI.Control.LoadRecursive() +131rn System.Web.UI.Control.LoadRecursive() +131rn System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1061rnrn 请问这是什么原因?怎么修改啊rn谢谢了rn 论坛

C# 对象能从 DBNull换为其他类型

01-13

foreach (DataRow dr in dtData.Rows) //遍历行 in 行的集合rn rn byte[] EDS = new byte[183];rn EDS[0] = 0x82; // emm table idrn EDS[1] = 0x40; // rn EDS[2] = 0x3f;rn EDS[3] = 0x02;// emm secton lengthrn byte[] groupid = HexStrToHexBytes(dr["Group_name"].ToString());rn EDS[4] = groupid[0];rn EDS[5] = groupid[1];rn // emm secton lengthrn //发送emmrnrn rn rn string strConn = "Data Source=127.0.0.1;Initial Catalog=yz;User ID=sa;Password=sa123456";rn SqlConnection ConnAcc = new SqlConnection(strConn);rn string strSQL = "SELECT SGK FROM Group_SGK3 ";rn SqlDataAdapter de = new SqlDataAdapter(strSQL, ConnMdb);rn tryrn rn //da.Fill(dt);rn dtData.Clear();rn de.Fill(dtData);rn rn catchrn rn break;rn rnrn for (int n = 0; n < 7; n++)rn rn int GK;rn foreach (DataRow rdr in dtData.Rows)rn rnrn int SGK = Convert.ToInt32(rdr["SGK"]);rn GK = SGK << n;rnrn rn if (Convert.ToBoolean(rdr["state1"]))rn rn rnrn byte[] gk = new byte[8];rn Array.Copy(HexStrToHexBytes(GK.ToString()), 0, gk, 7, 1);rn rn ;rn SKeyValue = SKeyValue1;rn byte[] EncryptSk = EncryptDES(SKeyValue, gk);rn rnrn EDS[6] = 0x01;rn Array.Copy(EncryptSk, 0, EDS, 7, EncryptSk.Length);rn //Thread.Sleep(5);rn rn elsern rnrnrn rn EDS[6] = 0x01;rnrnrnrnrn rn EDS[7] = 0xff;rn EDS[8] = 0xff;rn for (int i = 9; i < 15; i++)rn rn EDS[i] = 0x00;rnrn rnrn rnrnrnrnif (Convert.ToBoolean(rdr["state1"]))这句话出错说“对象不能从 DBNull 转换为其他类型”,可是我的数据库不是空的呀,这是怎么回事?请高人指点! 论坛

还是那个问题,System.InvalidCastException: 对象能从 DBNull换为其他类型

11-09

论坛注册出现如上问题?论坛页面为:http://www.chunsky.net/forum/Register.aspxrn谁能帮我看看到底是什么问题!!rnRegister.aspx源码是:rnrnrn<%@ Page Language="C#" ContentType="text/html" trace="false" debug=true%>rn<%@ Register TagPrefix="DotNetForums" Namespace="DotNetForums.Controls" Assembly="DotNetForums" %>rnrnrn 用户登录 rn rn rn rn rn rnrnrnrn rnrnrnrnrnrnrnrn出错提示:rnrn对象不能从 DBNull 转换为其他类型。 rn说明: 执行当前 Web 请求期间,出现未处理的异常。请检查堆栈跟踪信息,以了解有关该错误以及代码中导致错误的出处的详细信息。 rnrn异常详细信息: System.InvalidCastException: 对象不能从 DBNull 转换为其他类型。rnrn源错误: rnrn执行当前 Web 请求期间生成了未处理的异常。可以使用下面的异常堆栈跟踪信息确定有关异常原因和发生位置的信息。 rnrn堆栈跟踪: rnrnrn[InvalidCastException: 对象不能从 DBNull 转换为其他类型。]rn System.DBNull.System.IConvertible.ToInt32(IFormatProvider provider) +48rn System.Convert.ToInt32(Object value) +36rn DotNetForums.Data.SqlDataProvider.CreateNewUser(ForumUser user) +626rn DotNetForums.Controls.Register.LoginButton_Click(Object sender, EventArgs e) +299rn System.Web.UI.WebControls.Button.OnClick(EventArgs e) +108rn System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +57rn System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +18rn System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +33rn System.Web.UI.Page.ProcessRequestMain() +1266 论坛

=====高手请进,他人帮顶,对象能从 DBNull换为其他类型,三天不解其意?????

08-24

孟老大,思哥,吴旗兄等高手来看看:rn rn 本人做会员注册程序,其实很简单的,会员id,密码和会员姓名是必填项,年龄和所在诚市是可选项,提交数据后,程序执行有错,提示:”对象不能从 DBNull 转换为其他类型“,搞了三天了,不知如何搞??请各位大哥指导一下,rnrn我把我的设置再说一下:rnrn会员id,密码和会员姓名是必填项,其他字段不写也没事,在sqlserver数据库表中已经将可选项的字段加了默认值。rnrn程序是调用类和存储过程来实现的。rnrn存储过程如下:rnCREATE PROCEDURE [insert_newuser]rn (rn @UserId [char](20),rn @UserPassword [char](32), rn @UserName [char](20), rn @UserAge [int] , rn @UserCity [char](20),rn @RegIp [char](20),rn @Count1 int outputrn )rn rnrnAS rnrnrnSELECT @Count1 = COUNT (UserId) From UserInfo Where UserId = @UserIdrnrnIF(@Count1 > 0)rnrn RETURN @Count1 rnrnrnELSErnrnrnBEGINrnrnINSERT INTO [ UserInfo]rn (rn [UserId] ,rn [UserPassword] , rn [UserName] , rn [UserAge] , rn [UserCity] ,rn [RegIp] rn rn )rn rn rnrnrnVALUES rn ( rn @UserId ,rn @UserPassword , rn @UserName , rn @UserAge , rn @UserCity , rn @RegIp rn )rnrnrnrnrnRETURN @Count1 rnrnENDrnGOrnrn类文件部分原码如下:rnrnpublic int insertdata(string UserId,string UserPassword,string UserName,int UserAge,string UserCity,string RegIp)rn rnrn//-----以下所有功能就是:在数据库中增加一条记录,增加一个用户rnrnOpenConn(); //打开数据库,当然是调用类;rn rn rnSqlCommand cm=new SqlCommand("insert_newuser",Conn); //实例化存储过程对象,相关属性赋给cm,请注意,这里不能写Conn,要从类中调rnrnrncm.CommandType=CommandType.StoredProcedure; //当然操作类型为操作存储过程 rn rntryrn rncm.Parameters.Add(new SqlParameter("@UserId",SqlDbType.Char,20));//增加或实例化一个参数rncm.Parameters["@UserId"].Value=UserId;//给要传递的参数赋值rnrncm.Parameters.Add(new SqlParameter("@UserPassword",SqlDbType.Char,32));rncm.Parameters["@UserPassword"].Value=UserPassword;rnrncm.Parameters.Add(new SqlParameter("@UserName",SqlDbType.Char,20));rncm.Parameters["@UserName"].Value=UserName;rnrncm.Parameters.Add(new SqlParameter("@UserAge",SqlDbType.Int,4));rncm.Parameters["@UserAge"].Value=UserAge;rn rncm.Parameters.Add(new SqlParameter("@UserCity",SqlDbType.Char,20));rncm.Parameters["@UserCity"].Value=UserCity;rn rncm.Parameters.Add(new SqlParameter("@RegIp",SqlDbType.Char,20));rncm.Parameters["@RegIp"].Value=RegIp;rnrnrncm.Parameters.Add("@Count1", SqlDbType.Int, 4);//RoleId就是要返回的参数,先传过去rncm.Parameters["@Count1"].Direction = ParameterDirection.Output;rnrn//大概是返回的参数名是:Count1rn rncm.ExecuteNonQuery(); rn rnrnrn rn rncatchrn //如果有异常,则提示rn//Response.Write (" ");rnrnrnrn CloseConn();//关闭数据库rn rnrnint flag = Convert.ToInt32(cm.Parameters["@Count1"].Value);//取回返回值rnreturn flag;rnrn rnrnrnrnrn主程序文件RegUser.cs调用代码如下:rnrn//以下功能,增加一个用户到数据表中rnrn//myclass.OpenConn(); //打开数据库,当然是调用类;rn rnstring UserId,UserPassword,UserCity,UserName,RegIp1;rn int UserAge;rn rnUserId=UserId1.Text;rnUserName=UserName1.Text;rnrnUserPassword=System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(UserPassword1.Text,"md5"); //以上这句为接收密码字符,且转为32MD5;rnrnrn rnUserAge=Convert.ToInt32(UserAge1.Text.ToString());rnUserCity=UserCity1.Text;rnRegIp1=Request.ServerVariables["REMOTE_ADDR"];//用户注册时的ip地址rnrn rnrnrnint flagint;rnflagint=myclass.insertdata(UserId,UserPassword,UserName,UserAge,UserCity,RegIp1);rn//以上这句调用类的insertdata过程,并把相关参数传过去,增加一条记录,并且把执行结果返回rnrnif (flagint>0)rnrn//如果返回值>0,表示该用户名已经存在rnResponse.Write (" ");rnrnrnelsernrn//如果<=0表示可以增加rnResponse.Write (" ");rn rnrnrn rnmyclass.CloseConn();//调用类 Class1对象myclass的过程closeconn(),关闭数据库rnrnrnrn程序运行全没问题!rnrn麻烦各位大哥了,谢谢,真的搞了三天了,也没搞过来!rn 论坛

【初学者求教】急...对象能从 DBNull换为其他类型

05-12

在公司调试挺好的。rn现在人在现场,没有编程环境,不清楚到底是那地方出错了,求高手帮忙分析下代码,看在哪地方加点什么东西能过关。rn万分感激rnrn[code=C#]rnSqlConnection connection = new SqlConnection(connnectionString);rnrn string sql = "select top 1 DatapointID from DatapointValue2 order by LastModified desc";rnrn SqlCommand cmdDatapointID = new SqlCommand(sql, connection);// 定义Command对象rnrn connection.Open();rn object a = cmdDatapointID.ExecuteScalar();rn connection.Close();rn int ab = Convert.ToInt32(a);rnrn /*___________________________________________取PropID值______________________________________*/rn SqlConnection connectionPropID = new SqlConnection(connnectionString);rnrn string sqlPropID = "select top 1 PropID from DatapointValue2 order by LastModified desc";rnrn SqlCommand cmdPropID = new SqlCommand(sqlPropID, connectionPropID);// 定义Command对象rnrn connectionPropID.Open();rn object objCmdPropID = cmdPropID.ExecuteScalar();rn connectionPropID.Close();rn int propID = Convert.ToInt32(objCmdPropID);rn /****************************************根据DatapointID取出时间********************************************/rn OdbcConnection connection2 = new OdbcConnection(connnectionString2);rnrn string sql2 = "select LastModified from DBA.DatapointValue where DatapointID=" + ab + "and PropID=" + propID;rnrn OdbcCommand cmd3 = new OdbcCommand(sql2, connection2);// 定义Command对象rnrn connection2.Open();rn object abc = cmd3.ExecuteScalar();rn connection2.Close();rn double abcd = Convert.ToDouble(abc);rnrn /*******************************************Sybase数据库中的表数据迁移到Server中**********************************************/rn OdbcConnection conn1 = new OdbcConnection();rn SqlConnection conn2 = new SqlConnection();rn OdbcCommand cmd1 = new OdbcCommand();rn SqlCommand cmd2 = new SqlCommand();rn System.Data.Odbc.OdbcDataReader dr;rn conn1.ConnectionString = connnectionString2;rn conn2.ConnectionString = connnectionString;rnrn cmd1.Connection = conn1;rn cmd2.Connection = conn2;rn cmd1.CommandText = "SELECT DatapointID,Value,Persist,PropID,LastModified FROM DBA.DatapointValue where LastModified >" + abcd;rn conn1.Open();rn dr = cmd1.ExecuteReader();rn conn2.Open();rn while (dr.Read())rn rn string insertString = "INSERT INTO DatapointValue2(DatapointID,Value,Persist,PropID,LastModified) VALUES ('0','1','2','3','4')";rn insertString = string.Format(insertString, dr[0], dr[1], dr[2], dr[3], dr[4]);rnrn cmd2.CommandText = insertString;rn cmd2.ExecuteNonQuery();rn rn dr.Close();rn conn1.Close();rn conn2.Close();rnrn label2.Text = "第" + i + "次传递成功!3分钟后再次传递...";rn i = i + 1;rn btn_Stop.Enabled = true;rn[/code] 论坛

没有更多推荐了,返回首页