尝试阻止被调用两次

Jak*_*eam 1 c# try-catch visual-studio-2010

所以我有一个从数据库中检索数据并输出它的函数.它被封装在一个try块中,因此处理了用尽行的错误.

这是在加载时调用的函数(用于生成初始输出),稍后调用以更新日志框.

问题是,每当我再次调用该函数时,它会输出两次数据.由于只有数据在try块中,而不是标题,因此指向try/catch是问题.

为凌乱/骇客的代码道歉:

    private void NavigateRecords()
    {
        da.Fill(ds1, "LogOutput");
        textlog4.Text = "Date \t\t Time \t\t Floor\r\n";
        try
        {
            for (int i = 0; i <= 20; i++)
            {
                DataRow dRow = ds1.Tables["LogOutput"].Rows[i];
                for (int i2 = 1; i2 <= 3; i2++)
                {
                    textlog4.Text += dRow.ItemArray.GetValue(i2).ToString() + "\t\t";
                }
                textlog4.Text += "\r\n";

            }
        }
        catch { textlog4.Text += "----------------------"; }  
    }
Run Code Online (Sandbox Code Playgroud)

这是执行连接的一部分的代码,可能有用:

        string sql = "SELECT * From tblLog";
        da = new System.Data.SqlClient.SqlDataAdapter(sql, con);
        NavigateRecords();
Run Code Online (Sandbox Code Playgroud)

初始输出:

Date         Time        Floor
6/12        18:18:22        1       
----------------------
Run Code Online (Sandbox Code Playgroud)

下次调用时输出:

Date         Time        Floor
6/12        18:18:22        1       
6/12        18:46:19        2       
6/12        18:18:22        1       
6/12        18:46:19        2       
----------------------
Run Code Online (Sandbox Code Playgroud)

Sor*_*eri 7

它不是你的try catch的问题,它是你的变量的问题.在向其添加新数据之前清除变量.我没有在方法范围内看到您的变量声明,因此它保留了您原始放入其中的数据.