我正在使用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();
}
您将获得“对象引用未设置为对象的实例。”错误,因为您没有正确使用适配器的SelectCommand
。您需要使用SqlParameter
的SelectCommand
,如下所示:
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;
//..
}