C#调用CodeSoft打印条码 ,未将对象引用设置到对象的实例怎么解决?


public bool PrintMAC(DataTable dtb, string barcode, string Prefix, string SerNum, int ptnum, string model, out string error)
{
    Kill("lppa");
    model = AppDomain.CurrentDomain.BaseDirectory + model;//取当前应用程序域运行的目录
    LabelManager2.ApplicationClass PrintApp = new LabelManager2.ApplicationClass();


    try
    {
        LabelManager2.Document PrintDoc = PrintApp.ActiveDocument;
        PrintDoc = PrintApp.Documents.Open(model, false);
        if (PrintDoc == null)
        {
            error = "模版未找到";
            return false;
        }

        if (!string.IsNullOrEmpty(barcode))
        {
            PrintDoc.Variables.Counters.Item(barcode).Prefix = Prefix;
            PrintDoc.Variables.Counters.Item(barcode).Value = SerNum;
        }

        for (int j = 0; j < dtb.Rows.Count; j++) //行
        {
            for (int i = 0; i < dtb.Columns.Count; i++) //列
            {
                try
                {
                    string col = dtb.Columns[i].ColumnName.ToString();
                    string txt = dtb.Rows[j][col].ToString();
                    PrintDoc.Variables.FormVariables.Item(col).Value = txt;
                }
                catch (Exception ex)
                {
                    error = ex.Message;
                    return false;
                }
            }
            PrintDoc.PrintDocument(1);

        }
        error = "打印成功";
        return true;

    }
    catch (Exception ex)
    {
        error = ex.Message;
        return false;
    }
    finally
    {
        PrintApp.Documents.CloseAll(false);
        PrintApp.Quit();
    }

}

问题是调试的时候报错,错误信息就是“未将对象引用设置到对象的实例”,我也找到了为空的那一句,但是,我不知道它为什么会为空。

阅读 7k
2 个回答

下个断点,F10一步一步来,能找到哪个对象为空的。

谢邀!不过不知道楼主问题是啥。C#代码报错最好可以截图一并传来,看了VS的报错信息,一般也就知道哪里出错了。
直接贴这么多代码,而且还是片段,一般很少有人会看的!把问题描述清楚,图文并茂!

常见的未将对象引用设置到对象的实例原因
一、网络上的一般说法

1、ViewState对象为Null。

2、DateSet空。

3、sql语句或Datebase的原因导致DataReader空。

4、声明字符串变量时未赋空值就应用变量。

5、未用new初始化对象。

6、Session对象为空。

7、对控件赋文本值时,值不存在。

8、使用Request.QueryString()时,所获取的对象不存在,或在值为空时未赋初始值。

9、使用FindControl时,控件不存在却没有做预处理。

10、重复定义造成未将对象引用设置到对象的实例错误.

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进