namespace WindowsFormsApplication5
{
public partial class Form1 : Form
{
string conn = "Data Source=JUTT;Initial Catalog=product;Integrated Security=True";
SqlConnection connection;
SqlCommand command;
SqlDataAdapter adapt;
SqlConnection con;
DataTable dt;
string prnt;
string sql = null;
ReportDocument crystal = new ReportDocument();
public Form1()
{
InitializeComponent();
}
private void crystalReportViewer1_Load(object sender, EventArgs e)
{
}
private void Form1_Load(object sender, EventArgs e)
{
crystal.Load(@"c:\users\asad\documents\visual studio 2013\Projects\WindowsFormsApplication5\WindowsFormsApplication5\CrystalReport1.rpt");
}
private void button1_Click(object sender, EventArgs e)
{
adapt = new SqlDataAdapter("select id,pd_name,price from sale where id like '" + textBox1.Text + "%'", con);
DataSet ds = new DataSet();
adapt.Fill(ds, "sale");
CrystalReport1 rpt = new CrystalReport1();
rpt.SetDataSource(ds);
crystalReportViewer1.ReportSource = rpt;
dt = new DataTable();
}
private void button2_Click(object sender, EventArgs e)
{
adapt = new SqlDataAdapter("select * from sale", con);
DataSet ds = new DataSet();
adapt.Fill(ds, "sale");
CrystalReport1 rpt = new CrystalReport1();
rpt.SetDataSource(ds);
crystalReportViewer1.ReportSource = rpt;
dt = new DataTable();
}
}
}
当我点击按钮2时,我得到例外:
未处理的类型' System.InvalidOperationException' 发生在System.Data.dll的rpt.setdatasource
行
答案 0 :(得分:0)
在您的代码中,您已声明SqlConnection con;
并且从未对其进行初始化,但稍后您会尝试在数据适配器构造函数中使用它:adapt = new SqlDataAdapter(".......", con);
在使用之前初始化连接(使用适当的连接字符串创建它的实例),例如在表单构造函数中:
public Form1()
{
InitializeComponent();
con = new SqlConnection(conn);
}