FormConfig.cs_200528

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml;
//using System.Text;
using MT8852B_Driver;
using System.IO;

namespace NRF52382_Test
{

public partial class FormConfig : Form
{
    FormMain frmMain = new FormMain();

    public void LoadXMLToDataGridView()
    {
        XmlTextReader xml = null;
        DataTable dt = null;
        string strMsg = "";
        try
        {
            dt = new DataTable();
            //添加列名
            dt.Columns.Add("TestCase", typeof(string));
            dt.Columns.Add("Parameter", typeof(string));
            dt.Columns.Add("Enable", typeof(string));
            //dt.Columns.Add("1", typeof(DataGridViewButtonColumn));
            //dt.Columns.Add("Description", typeof(string));

            string strJsonfile = System.Environment.CurrentDirectory + "\\TestSrcipt.xml";
            xml = new XmlTextReader(strJsonfile);
            xml.WhitespaceHandling = WhitespaceHandling.None;

            while (xml.Read())
            {
                if (xml.NodeType == XmlNodeType.Element)
                {
                    if (xml.Name == "COM")
                    {
                        tbCOM.Text = xml.ReadString();
                    }
                    if (xml.Name == "GPIB_Index")
                    {
                        List<string> ls = new List<string>();
                        string strTmp = xml.GetAttribute("Elements");
                        List<string> list = new List<string>(strTmp.Split(','));
                        list.ForEach(i => ls.Add(i));

                        string strCurrVaule = xml.ReadString();
                        ls.ForEach(x => cbGpibIndex.Items.Add(x.ToString()));
                        cbGpibIndex.SelectedIndex = cbGpibIndex.Items.IndexOf(strCurrVaule);

                        //cbGpibIndex.Text = xml.ReadString();
                    }
                    if (xml.Name == "GPIB_Address")
                    {
                        tbGpibAddress.Text = xml.ReadString();
                    }

                    if (xml.Name == "TestCase1" || xml.Name == "TestCase2" || xml.Name == "TestCase3" || xml.Name == "TestCase4" || xml.Name == "TestCase5" || xml.Name == "TestCase6" || xml.Name == "TestCase7" || xml.Name == "TestCase8" || xml.Name == "TestCase9")
                    {
                        DataRow dr = dt.NewRow();
                        string strCaseName = xml.GetAttribute("Name");
                        dr["TestCase"] = strCaseName;
                        string strVaule = xml.GetAttribute("Value");
                        dr["Parameter"] = strVaule;
                        string strEnable = xml.GetAttribute("Enable");                            
                        dr["Enable"] = strEnable;
                        dt.Rows.Add(dr);                          
                    }                        
                }                   
            }
            //创建DataSet对象,绑定数据
            DataSet ds = new DataSet();
            ds.Tables.Add(dt);
            dataGridView1.DataSource = dt;
            dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;

            //for(int i = 0;i<dt.Columns.Count-1;i++)
            {
                DataGridViewButtonColumn btn = new DataGridViewButtonColumn();
                btn.Name = "btnModify";
                btn.HeaderText = "修改";
                btn.DefaultCellStyle.NullValue = "修改";
                dataGridView1.Columns.Add(btn);
            }
        }
        catch (XmlException xmlEx)
        {
            strMsg = xmlEx.Message.ToString();
            MessageBox.Show(strMsg);
        }
        catch (DataException dataEx)
        {
            strMsg = dataEx.Message.ToString();
            MessageBox.Show(strMsg);
        }
        catch (SystemException sysEx)
        {
            strMsg = sysEx.Message.ToString();
            MessageBox.Show(strMsg);
        }
        finally
        {
            xml.Close();
        }
    }

    public void SaveXMLFromDataGridView()
    {
        string strTmp = "";
        string strMsg = "";
        string strJsonfile = System.Environment.CurrentDirectory + "\\TestSrcipt.xml";
        XmlDocument xml = null;
        try
        {
            xml = new XmlDocument();
            xml.Load(strJsonfile);

            XmlElement pXmlElement = xml.SelectSingleNode(@"configuration/BtTest/Init/COM") as XmlElement;
            pXmlElement.InnerText = tbCOM.Text;

            pXmlElement = xml.SelectSingleNode(@"configuration/BtTest/Init/GPIB_Index") as XmlElement;
            pXmlElement.InnerText = cbGpibIndex.Text;

            pXmlElement = xml.SelectSingleNode(@"configuration/BtTest/Init/GPIB_Address") as XmlElement;
            pXmlElement.InnerText = tbGpibAddress.Text;


            for (int i = 0; i < 9; i++)
            {
                string strTmp2 = string.Format("configuration/BtTest/TestCase/TestCase{0}", (i + 1));
                pXmlElement = xml.SelectSingleNode(strTmp2) as XmlElement;
                strTmp = dataGridView1["Parameter", i].Value.ToString();
                pXmlElement.SetAttribute("Value", strTmp);
                //pXmlElement.InnerText = strTmp;
            }
            xml.Save(strJsonfile);
            MessageBox.Show("数据保存成功!");
            this.Close();
        }
        catch (XmlException xmlEx)
        {
            strMsg = xmlEx.Message.ToString();
            MessageBox.Show(strMsg);
        }
        catch (DataException dataEx)
        {
            strMsg = dataEx.Message.ToString();
            MessageBox.Show(strMsg);
        }
        catch (SystemException sysEx)
        {
            strMsg = sysEx.Message.ToString();
            MessageBox.Show(strMsg);
        }
        finally
        {
        }
    }

    public FormConfig()
    {
        InitializeComponent();
        LoadXMLToDataGridView();
    }


    public FormConfig(FormMain formMain)
    {
        frmMain = formMain;
        InitializeComponent();
    }


    #region 直接删除指定目录下的所有文件及文件夹(保留目录)
    public static void DeleteDir(string file)
    {
        try
        {
            //去除文件夹和子文件的只读属性
            //去除文件夹的只读属性
            System.IO.DirectoryInfo fileInfo = new DirectoryInfo(file);
            fileInfo.Attributes = FileAttributes.Normal & FileAttributes.Directory;

            //去除文件的只读属性
            System.IO.File.SetAttributes(file, System.IO.FileAttributes.Normal);

            //判断文件夹是否还存在
            if (Directory.Exists(file))
            {
                foreach (string f in Directory.GetFileSystemEntries(file))
                {
                    if (File.Exists(f))
                    {
                        //如果有子文件删除文件
                        File.Delete(f);
                        Console.WriteLine(f);
                    }
                    else
                    {
                        //循环递归删除子文件夹
                        DeleteDir(f);
                    }
                }

                //删除空文件夹
                //Directory.Delete(file);
                Console.WriteLine(file);
            }

        }
        catch (Exception ex) // 异常处理
        {
            Console.WriteLine(ex.Message.ToString());// 异常信息
        }
    }

    #endregion

    //public delegate void ShowStatedelegate(string txt);//定义一个委托
    //public event mydelegate myevent;

   
    private void FormConfig_Load(object sender, EventArgs e)
    {
        LoadXMLToDataGridView();
        FormLogin frmLogin = new FormLogin();
        frmLogin.ShowDialog();
        if (frmLogin.DialogResult == DialogResult.OK)//如果登录框返回DialogResult.OK
        {
            //MessageBox.Show("正常登录");
        }
        else
        {
            this.Close();
        }
    }

    private void ReportClear_Click(object sender, EventArgs e)
    {
        //清除文件夹的所有文件
        DeleteDir(System.Environment.CurrentDirectory + "\\Log\\");
        DeleteDir(System.Environment.CurrentDirectory + "\\CSV\\");

        frmMain.tbPass.Text = "0";
        frmMain.tbFail.Text = "0";
        frmMain.tbTotal.Text = "0";
        frmMain.tbFYP.Text = "100%";
        frmMain.ResetFYP();
    }

    private void btSave_Click(object sender, EventArgs e)
    {
        SaveXMLFromDataGridView();
    }

    private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
    {
        if (dataGridView1.Columns[e.ColumnIndex].Name == "btnModify" && e.RowIndex >= 0)
        {
            TxTestCase TxTestPara = new TxTestCase();
            RxTestCase RxTestPara = new RxTestCase();

            
            string strVaule = Convert.ToString(dataGridView1.CurrentRow.Cells[1].Value);
            List<string> listPara = new List<string>(strVaule.Split(','));
            TxTestPara.iTxBLEStandard = Convert.ToInt16(listPara[1]);
            TxTestPara.channel = (E_Channel)Convert.ToInt16(listPara[2]);
            TxTestPara.iRange = Convert.ToInt16(listPara[3]);
            TxTestPara.sFixedOffset = listPara[4];

            TxTestPara.iTrigger = Convert.ToInt16(listPara[5]);
            TxTestPara.sCapturePeriod = listPara[6];
            TxTestPara.sSyscWord0x = listPara[7];
            TxTestPara.iPayload = Convert.ToInt16(listPara[8]);
            TxTestPara.sAnternnaPattern = listPara[9];

            TxTestPara.IsTest_OutputPower = listPara[10] == "1" ? true : false;
            TxTestPara.IsTest_CarrierDrift = listPara[11] == "1" ? true : false;
            TxTestPara.IsTest_ModulationIndex = listPara[12] == "1" ? true : false;

            RxTestPara.iRxBLEStandard = Convert.ToInt16(listPara[14]);
            RxTestPara.channel = (E_Channel)Convert.ToInt16(listPara[15]);
            RxTestPara.sPowerLevel = listPara[16];
            RxTestPara.sLoss = listPara[17];
            RxTestPara.iPayload = Convert.ToInt16(listPara[18]);
            RxTestPara.sSyscWord0x = listPara[19];
            RxTestPara.sSpacing = listPara[20];
            RxTestPara.sPackets = listPara[21];
            RxTestPara.sCTELength = listPara[22];

            RxTestPara.iSlotDuration = Convert.ToInt16(listPara[23]);
            RxTestPara.iDirtyTransmitter = Convert.ToInt16(listPara[24]);
            RxTestPara.iAlternateBadCRC = Convert.ToInt16(listPara[25]);
                        

            string strTxRxEnable = Convert.ToString(dataGridView1.CurrentRow.Cells[2].Value);
            List<string> listRxTxEnable = new List<string>(strTxRxEnable.Split(','));
            if(listRxTxEnable[0] == "1")
            {
                TxTestPara.bTxCaseEnable = true;
            }
            else
            {
                TxTestPara.bTxCaseEnable = false;
            }
            if(listRxTxEnable[1] == "0")
            {
                RxTestPara.bRxCaseEnable = true;
            }
            else
            {
                RxTestPara.bRxCaseEnable = false;
            }
            FormTxRxParaConfig formTRCfg = new FormTxRxParaConfig(TxTestPara,RxTestPara);
             formTRCfg.ShowDialog();
        }          
    }
}

}

<think>好的,我需要解决用户关于System.NullReferenceException和System.Threading.ThreadExceptionEventArgs的问题,并提供针对CTCGUI中GUIConfigFolder和FirstNaviPanel错误的解决方案。首先,根据用户提供的引用内容,特别是引用[3],已经列举了多种导致NullReferenceException的原因,我需要将这些原因与用户提到的具体场景结合起来。 首先,System.NullReferenceException通常发生在尝试访问未初始化的对象引用时。用户提到的CTCGUI中的GUIConfigFolder和FirstNaviPanel可能是界面控件或配置对象,可能在这些地方出现了未正确实例化的情况。例如,可能在代码中没有对GUIConfigFolder进行初始化,或者在访问FirstNaviPanel时,该控件尚未被正确创建或绑定。 接下来,关于System.Threading.ThreadExceptionEventArgs,这通常与多线程编程中的异常处理有关。在Windows窗体应用中,如果在非UI线程上直接操作控件,可能会引发跨线程异常,而如果没有正确捕获和处理这些异常,可能会触发ThreadException事件。需要检查代码中是否有在后台线程中更新UI而没有使用Invoke或BeginInvoke方法的情况。 现在结合引用[3]中的原因,逐步排查: 1. **检查对象是否实例化**:确保GUIConfigFolder和FirstNaviPanel在使用前已经被正确初始化,特别是如果它们是控件,可能在设计器中删除或重命名后,代码中的引用没有更新,导致找不到控件。 2. **数据绑定问题**:如果GUIConfigFolder与数据源绑定,检查数据源是否为空。例如,DataSet或DataReader是否返回了空数据,导致在绑定时出现空引用。 3. **ViewState或Session状态**:如果是Web应用,检查ViewState或Session是否保存了相关对象,但在回发时未能正确恢复,导致对象为null。 4. **控件名称一致性**:确认代码中的控件名称(如FirstNaviPanel)是否与前端设计文件(如.aspx或.xaml)中的名称完全一致,包括大小写。 5. **线程安全操作**:检查是否有在后台线程中访问或修改FirstNaviPanel等UI控件的情况,必须使用Control.Invoke来确保线程安全。 6. **异常处理**:在事件处理程序中添加try-catch块,捕获NullReferenceException,并记录详细的堆栈信息,帮助定位问题源头。 可能的解决方案步骤包括: - **代码审查**:检查所有使用GUIConfigFolder和FirstNaviPanel的地方,确认对象在使用前已实例化。 - **调试与日志**:在访问这些对象之前添加空值检查,并记录日志,查看具体哪个步骤出现了null。 - **线程检查**:确保所有UI操作都在主线程执行,必要时使用Invoke。 - **数据源验证**:确认绑定的数据源是否存在且已正确填充数据。 此外,引用[3]提到的第14点指出程序异常可能导致实例化失败,因此需要检查是否有其他异常在对象初始化之前被抛出,导致后续代码无法正确执行。 最后,可能需要用户提供更多具体的代码片段或错误堆栈信息,以进一步缩小问题范围。如果用户无法提供,建议按照上述步骤逐一排查常见原因。</think>### System.NullReferenceException 错误解析及解决方案 #### **错误原因分析** 1. **GUIConfigFolder/FirstNaviPanel 未实例化** - 若 `GUIConfigFolder` 或 `FirstNaviPanel` 是类成员变量或控件,可能未通过 `new` 初始化[^3]。 - **示例代码问题**: ```csharp private Panel FirstNaviPanel; // 仅声明,未实例化 void LoadConfig() { FirstNaviPanel.Text = "Loading..."; // 触发NullReferenceException } ``` 2. **控件未正确绑定或命名不一致** - 前端设计文件(如ASPX/XAML)中控件名称与代码中引用的名称不一致(如大小写错误或拼写错误)。 3. **多线程访问UI控件未同步** - 在后台线程直接操作 `FirstNaviPanel` 等控件,未使用 `Invoke` 方法,导致跨线程异常,进而可能引发 `System.Threading.ThreadExceptionEventArgs`。 4. **数据源为空时未处理** - 若 `GUIConfigFolder` 依赖配置文件或数据库数据,未检查数据源是否返回 `null`。 --- #### **具体解决步骤** 1. **添加空值检查** 在访问对象前显式检查是否为 `null`: ```csharp if (FirstNaviPanel != null) { FirstNaviPanel.Text = "Loaded"; } else { // 记录日志或初始化控件 } ``` 2. **确保控件正确初始化** - **WinForms/WPF**:检查设计器文件(如 `Form1.Designer.cs`)中控件是否被正确声明和初始化。 - **ASP.NET**:检查前端控件ID与代码中的引用是否一致,如: ```html <asp:Panel ID="FirstNaviPanel" runat="server"></asp:Panel> ``` ```csharp Panel firstNaviPanel = (Panel)FindControl("FirstNaviPanel"); // 注意大小写 ``` 3. **多线程操作使用Invoke** 在后台线程中更新UI时,强制通过主线程执行: ```csharp this.Invoke((MethodInvoker)delegate { FirstNaviPanel.Text = "Update from thread"; }); ``` 4. **验证数据源有效性** 若 `GUIConfigFolder` 依赖外部数据: ```csharp var config = LoadConfigFromFile(); if (config != null) { GUIConfigFolder = config; // 确保数据源非空 } ``` 5. **启用全局异常捕获** 在 `Application` 级别捕获未处理的异常(适用于 `System.Threading.ThreadExceptionEventArgs`): ```csharp Application.ThreadException += (sender, e) => { MessageBox.Show($"线程异常: {e.Exception.Message}"); }; AppDomain.CurrentDomain.UnhandledException += (sender, e) => { MessageBox.Show($"未处理异常: {(e.ExceptionObject as Exception)?.Message}"); }; ``` --- #### **拓展建议** - **日志记录**:在关键操作处添加日志,记录对象状态(如 `GUIConfigFolder == null` 的具体位置)。 - **单元测试**:编写测试用例模拟 `null` 场景,验证代码健壮性。 - **静态代码分析**:使用工具(如Roslyn Analyzer)检测可能的空引用风险。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值