此代码正在生成错误.“系统.无效强制转换异常: 指定的强制转换无效

本文关键字:无效 转换 异常 系统 代码 错误 | 更新日期: 2023-09-27 18:32:32

cmd1.CommandText = "SELECT distinct MbrBtch from Member where MbrStrm='"+DrpDwnStrm .SelectedItem .Text +"'";
            cmd1.Connection = con;
            DataTable Table1;
            Table1 = new DataTable("mbr");
            DataRow Row1;
            DataColumn MbrBatch = new DataColumn("MbrBatch");
            MbrBatch.DataType = System.Type.GetType("System.Int32");
            Table1.Columns.Add(MbrBatch);
            try
            {
                con.Open();
                SqlDataReader RdrMbr = cmd1.ExecuteReader();
                while (RdrMbr.Read())
                {
                    Row1 = Table1.NewRow();
                    Row1["MbrBatch"] = Convert.ToInt32(RdrMbr.GetInt32(0));
                    Table1.Rows.Add(Row1);
                }
                RdrMbr.Close();
            }
            finally
            {
                con.Close();
            }
            DrpDwnBtch.DataSource = Table1;
            this.DrpDwnBtch.DataTextField = "MbrBatch";
            DrpDwnBtch.DataBind();
//here MbrBtch is numeric type attribute of sql server. 

此代码正在生成错误.“系统.无效强制转换异常: 指定的强制转换无效

我的猜测是下面的行会给你一个错误。

更改行

    Row1["MbrBatch"] = Convert.ToInt32(RdrMbr.GetInt32(0));

int mbr = 0;
if (Int32.TryParse(RdrMbr[0], out mbr))
   Row1["MbrBatch"] = mbr;

MbrBtch 列中是否有空值?如果是这样,您需要像这样检查空值:

if (!RdrMbr.IsDBNull(0))
    Row1["MbrBatch"] = Convert.ToInt32(RdrMbr.GetInt32(0));
else
    // Set value to what it should be if null, perhaps a -1 or 0