索引在使用C#[duplicate]的ReportViewer的数组范围之内

问题描述 投票:0回答:1

我正在使用ReportViewer创建一个简单的报告。基于使用C#在ReportViewer上显示的选定id结果。我写了下面显示的代码,但出现错误

索引在数组的边界之外

代码:

SqlConnection con = new SqlConnection("Data Source=.; Initial Catalog= employees; User ID=sa; Password=admin123");

        using (SqlCommand myCommand = new SqlCommand())
        {
            string id = "1";


            SqlParameter paramId = new SqlParameter();
            paramId.ParameterName = "@id";
            paramId.Value = id;

            myCommand.Parameters.Add(paramId);

            myCommand.Connection = con;
            myCommand.CommandText = "SELECT * from records where id =  @id ";
            this.recordsTableAdapter.Adapter.SelectCommand = myCommand;

            Microsoft.Reporting.WinForms.ReportParameter[] @params = new Microsoft.Reporting.WinForms.ReportParameter[0];

          @params[0] = new Microsoft.Reporting.WinForms.ReportParameter("@id", id);

          reportViewer1.LocalReport.SetParameters(@params);

           this.recordsTableAdapter.Fill(this.employeesDataSet.records);

            this.reportViewer1.RefreshReport();

        }

enter image description here

c#
1个回答
0
投票

您将获得“对象引用未设置为对象的实例。”错误,因为您没有正确使用适配器的SelectCommand。您需要使用SqlParameterSelectCommand,如下所示:

using (SqlCommand myCommand = new SqlCommand())
{
    //..
    SqlParameter paramId = new SqlParameter();
    paramId.ParameterName = "@id";
    paramId.Value = id;

    myCommand.Parameters.Add(paramId);

    myCommand.Connection = con;
    myCommand.CommandText = "SELECT * from records where id =  @id ";
    this.exampleTableAdapter.Adapter.SelectCommand = myCommand;
    //..
}
© www.soinside.com 2019 - 2024. All rights reserved.