2

我有几天的动态查询不会给我带来要在报告中显示的数据。我所做的是编写一个代码,帮助我使用从 Windows 窗体获得的参数构建动态查询。例如,这是我用来获取表格的代码部分之一:

DataTable result = new DataTable();
String sqlQuery = "SELECT";
String myTable = getInfoReport();
SqlCommand myCommand;

switch (myTable)
{
    case "tbProducts":
        sqlQuery += String.Format(" DateTime AS [{0}]", _DBFields.Date);
        sqlQuery += String.Format(",ProductID AS [{0}]", _DBFields.MatNr);
        sqlQuery += String.Format(",Material AS [{0}]", _DBFields.Material);
        break;
    case "tbErrors":
        sqlQuery += String.Format(" DateTime AS [{0}]", _DBFields.Date);
        sqlQuery += String.Format(",Message  AS [{0}]", _DBFields.Message);
        break;
}
sqlQuery += " FROM dbo." + myTable;
sqlQuery += " WHERE (DateTime between @StartDate and @EndDate)";
sqlQuery += " ORDER BY DateTime";

myCommand = new SqlCommand(sqlQuery);
myCommand.CommandType = CommandType.Text;

myCommand.Parameters.AddWithValue("@StartDate", myReportData.StartDate);
myCommand.Parameters.AddWithValue("@EndDate", myReportData.EndDate);

if (myTable.Equals("tbErrors")) { result = myErrorsAdapter.fillErrorsDataTable(myCommand); }
else { result = myProductsAdapter.fillProductsDataTable(myCommand); }

然后我的 DataSet 类中有下一个代码:

partial class tbProductsTableAdapter
{
    internal DataTable fillProductsDataTable(SqlCommand myCommand)
    {
        MyDataSet.tbProductsDataTable result = new MyDataSet.tbProductsDataTable();

           try
           {
               this.Connection.Open();
               myCommand.Connection = this.Connection;
               this.Adapter.SelectCommand = myCommand;

               result.Load(this.Adapter.SelectCommand.ExecuteReader());

               this.Connection.Close();
           }
           catch (Exception e)
           {
           }

        return result;
    }
}

我的问题来了,当我试图加载我一开始声明的 DataTable 中的数据时,适配器没有执行查询,也没有给我带来我想要显示的数据。我对 C# 有点陌生,我试图找到一个解决方案很长一段时间,但我在尝试检查与我类似的其他问题时遇到了困难。

在此先感谢您的帮助!

4

1 回答 1

2

我发现了发生了什么:它必须与我发送给查询的参数的值有关。有时是好的,有时不是,所以我必须留意他们。当我使用 type 时,我还发现了一些东西tbProductsDataTable。我将其更改为简单DataTable类型并且也可以完美运行。所以第二个过程的代码是:

partial class tbProductsTableAdapter
{
    internal DataTable fillProductsDataTable(SqlCommand myCommand)
    {
        DataTable result = new DataTable();

           try
           {
               this.Connection.Open();
               myCommand.Connection = this.Connection;
               this.Adapter.SelectCommand = myCommand;

               this.Adapter.fill(result);

               this.Connection.Close();
           }
           catch (Exception e)
           {
           }

        return result;
    }
}
于 2013-05-24T12:28:53.943 回答