尝试块被调用两次 [英] Try block being called twice

查看:45
本文介绍了尝试块被调用两次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有一个函数可以从数据库中检索数据并输出它.它被封装在一个 try 块中,以便处理由于行数不足而导致处理的错误.

So I have a function that retrieves data from a database, and outputs it. It's encased in a try block, so that the error from running out of rows to process is dealt with.

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

Here's the function that is called on load (to make the initial output), and called later on to update the log box.

问题是,每当我再次调用该函数时,它都会输出两次数据.由于 try 块中只有数据,而不是标头,这表明 try/catch 是问题所在.

Problem is, whenever I call the function again, it outputs the data twice. Since only the data is in the try block, and not the headers, this points to the try / catch being the issue.

为凌乱/乱七八糟的代码道歉:

Apologies for the messy / hacky code:

    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 += "----------------------"; }  
    }

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

This is the code that does part of the connecting, and may be of use:

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

初始输出:

Date         Time        Floor
6/12        18:18:22        1       
----------------------

下次调用时输出:

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       
----------------------

推荐答案

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

its not an issue with your try catch , its an issue with your variables. Clear out the variable before you add the new data to it. I do not see your variable declared in the scope of the method so it retains the data you original put in it.

这篇关于尝试块被调用两次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆