C#&Crystal Reports, Failed to Load database error

64 views Asked by At

But when I try to run, I got the following exception. I tried various solutions, but all did fail.

Of course, I added startup code already. Please give me an idea.

private void SearchButton_Click(object sender, EventArgs e)
        {
          SqlConnection con;
          string source = @"Data Source = 1.2.3.4; Initial Catalog = Sales; USER ID = user1; PASSWORD = 87665;";

        try
        {
            con.Open();
            SqlCommand cmd = new SqlCommand("select * from dbo.SS where ADM01F = '@sBox'", con);
            cmd.Parameters.AddWithValue("@scBox", SearchTBox.Text);
            SqlDataAdapter adt = new SqlDataAdapter("select * from dbo.SS where ADM01F = '@sBox'", con);
            DataSet DS = new DataSet();
            adt.Fill(DS);
            ReportDocument cryRpt = new ReportDocument();
            string reportpath = Application.StartupPath + "\\SNIReport.rpt";
            cryRpt.Load(@"C:\SalesReport\SNIReport.rpt");
            cryRpt.SetDataSource(DS);
            crystalReportViewer1.ReportSource = cryRpt;
            crystalReportViewer1.Refresh();
            con.Close();
        }

        catch(Exception ex)
        {
            MessageBox.Show(ex.Message, "Error");
        }
1

There are 1 answers

0
Soner Gönül On

First thing I see..

You should not use single quotes with your parameters. With single quotes, your query see them as a string literal, not a parameter. And you should use that command in your SqlDataAdapter constructor as a first parameter, not create an another sql query that expects a parameter.

SqlCommand cmd = new SqlCommand("select * from dbo.SS where ADM01F = @sBox", con);
cmd.Parameters.AddWithValue("@scBox", SearchTBox.Text);
SqlDataAdapter adt = new SqlDataAdapter(cmd, con);

Don't use AddWithValue as much as possible. It may generate unexpected results sometimes. Use .Add() method overloads to specify your parameter type and it's size.

And don't forget to use using statement to dispose your connections, commands and adapsters automatically instead of calling .Close() or .Dispose() methods manually.

As mentioned, your SqlConnection object does not have any connection string. You either create your object with this parameter as;

SqlConnection con = new SqlConnection(source);

or set it's ConnectionString property as;

SqlConnection con;
con.ConnectionString = source;