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");
}
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
SqlDataAdapterconstructor as a first parameter, not create an another sql query that expects a parameter.Don't use
AddWithValueas 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
usingstatement to dispose your connections, commands and adapsters automatically instead of calling.Close()or.Dispose()methods manually.As mentioned, your
SqlConnectionobject does not have any connection string. You either create your object with this parameter as;or set it's
ConnectionStringproperty as;