问题
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.
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();
Initial output:
Date Time Floor
6/12 18:18:22 1
----------------------
Output next time it is called:
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
----------------------
回答1:
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.
来源:https://stackoverflow.com/questions/13750464/try-block-being-called-twice