SO here it goes. I have a model of dataset that works just fine and it imports data from database and gives it to crystal report. this solution works but it is very time consuming I was wondering if there is any other way of doing this...
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Oracle.DataAccess.Client;
using System.Data;
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Shared;
namespace WebApplication1
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
string connetionString = null;
OracleConnection connection;
OracleDataAdapter OracleAdapter;
DataSet ds = new DataSet();
string firstSql = null;
connetionString = "datasoruce";
connection = new OracleConnection(connetionString);
string secondSql = "select statementnumber from erocks.statement_data_domestic";
connection.Open();
//OracleAdapter = new OracleDataAdapter(firstSql, connection);
//OracleAdapter.Fill(ds, "domestic");
OracleAdapter = new OracleDataAdapter(secondSql, connection);
OracleAdapter.Fill(ds, "statement");
connection.Close();
ReportDocument reportDoc = new ReportDocument();
reportDoc.Load(#"c:\users\desktop\statement.rpt");
DataTable stmt = ds.Tables["statement"];
string stmtnumber="";
for (int i = 0; i < stmt.Rows.Count - 1; i++)
{
stmtnumber = stmt.Rows[i][0].ToString();
firstSql = #"SELECT DISTINCT statement_header.statementnumber,
statement_details.invoicedate,
statement_details.invoicenumber,
statement_details.invoicetotal,
statement_details.doc_type,
statement_header.statementtotal,
statement_details.bunumber_ru,
statement_details.bunumber,
statement_details.description,
statement_details.reference_number,
statement_header.remto_zip,
statement_header.remto_city,
statement_header.remto_state,
statement_header.remto_mailname,
statement_header.remto_addr1,
statement_header.remto_addr2,
statement_header.remto_addr3,
statement_header.soldto_city,
statement_header.soldto_state,
statement_header.soldto_zip,
statement_header.soldto_addr1,
statement_header.soldto_addr2,
statement_header.soldto_addr3,
statement_header.balance_forward,
statement_header.statementdate,
statement_header.custid,
statement_header.custname,
statement_header.phone_prefix,
statement_header.phone_number,
statement_details.purchases,
statement_details.payments,
statement_details.misc_credit2,
statement_details.misc_credit1,
statement_header.company_number,
statement_header.statementpurchases,
statement_header.statementpayments,
statement_header.statementmisc_credit1,
statement_header.statementmisc_credit2,
statement_header.nomailnoprint,
statement_header.SOLDTOCOUNTRYCODE,
statement_header.SOLDTOCOUNTRYNAME,
statement_header.CREDITZEROFLAG
FROM STATEMENT_DATA_DOMESTIC statement_header
INNER JOIN STATEMENT_DATA_DETAILS statement_details
ON statement_header.statementnumber =
statement_details.statementnumber
where statement_header.statementnumber="+stmtnumber;
connection.Open();
OracleAdapter = new OracleDataAdapter(firstSql, connection);
OracleAdapter.Fill(ds, "domestic");
OracleAdapter.Dispose();
connection.Close();
reportDoc.SetDataSource(ds.Tables["domestic"]);
ExportOptions CrExportOptions;
DiskFileDestinationOptions CrDiskFileDestinationOptions = new DiskFileDestinationOptions();
PdfRtfWordFormatOptions CrFormatTypeOptions = new PdfRtfWordFormatOptions();
CrDiskFileDestinationOptions.DiskFileName = #"d:\pdf\"+ stmtnumber + ".pdf";
CrExportOptions = reportDoc.ExportOptions;
{
CrExportOptions.ExportDestinationType = ExportDestinationType.DiskFile;
CrExportOptions.ExportFormatType = ExportFormatType.PortableDocFormat;
CrExportOptions.DestinationOptions = CrDiskFileDestinationOptions;
CrExportOptions.FormatOptions = CrFormatTypeOptions;
}
reportDoc.Export();
ds.Tables["domestic"].Clear();
}
}
}
}
It will be faster if you retrieve the data for all statements, group it by statementID inside the report and burst the report by this group. Bursting will generate a separate file for each group. In such way you will be able to generate all the files with one call to the database.
Related
I am trying to connect Teradata using .Net with the below code.
But when I execute it, it throws an error stating Invalid connection string
on
TdDataAdapter adapter = new TdDataAdapter(cn.ConnectionString,cmd.CommandText);
Here's the complete code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Teradata.Client.Provider;
using System.Data;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
TdConnectionStringBuilder connectionStringBuilder = new TdConnectionStringBuilder();
connectionStringBuilder.DataSource = "URK";
connectionStringBuilder.Database = "DB";
connectionStringBuilder.UserId = "USERNAME";
connectionStringBuilder.Password = "PASSWORD";
connectionStringBuilder.AuthenticationMechanism = "LDAP";
TdConnection cn = new TdConnection();
cn.ConnectionString = connectionStringBuilder.ConnectionString;
cn.Open();
TdCommand cmd = new TdCommand("EXEC MACRONAME", cn);
TdDataReader reader = cmd.ExecuteReader();
TdDataAdapter adapter = new TdDataAdapter(cn.ConnectionString,cmd.CommandText);
DataSet ds = new DataSet();
adapter.Fill(ds);
myLabel.Text= ds.Tables[0].Rows[0]["event_id"].ToString();
cmd.Dispose();
cn.Close();
}
}
I tried using connectionStringBuilder.ConnectionString instead of the one used above but I still got the same error.
Just swap parameters
TdDataAdapter adapter = new TdDataAdapter(cmd.CommandText, cn.ConnectionString);
according to signature of TdDataAdapter constructor
public TdDataAdapter(
string commandText,
string connectionString
)
See docs
I'm building a desktop application where when a used logged it in new his Id will be appeared in textBox. But in my case query run successfully but id doesn't appear in textBox..can anyone help me to find it out please?
First form of User logged in (Form1.cs)
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace EmployeeApp
{
public partial class login : Form
{
public login()
{
InitializeComponent();
}
public string employeeID;
private void exitButton_Click(object sender, EventArgs e)
{
this.Close();
}
private void loginButton_Click(object sender, EventArgs e)
{
SqlConnection connection = new SqlConnection(#"Data Source=INCEPSYS-SE\TEST;Initial Catalog=Employee;Integrated Security=True");
connection.Open();
String query = "select * from Employees where Name = '" + nameTextBox.Text + " ' and Password = '" + passwordTextBox.Text + "'";
SqlCommand command = new SqlCommand(query, connection);
SqlDataReader myReader = command.ExecuteReader();
while (myReader.Read())
{
string employeeID = myReader["EmployeeID"].ToString();
}
myReader.Close();
SqlDataAdapter sda = new SqlDataAdapter(query,connection);
connection.Close();
DataTable dt = new DataTable();
sda.Fill(dt);
if (dt.Rows.Count == 1)
{
this.Hide();
Entry ss = new Entry(employeeID);
ss.Show();
}
else
{
MessageBox.Show("Please Check your Username & password");
}
}
}
}
Second form (Entry.cs)
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace EmployeeApp
{
public partial class Entry : Form
{
public Entry()
{
InitializeComponent();
}
public Entry(string employeeId)
{
InitializeComponent();
idTextBox.Text = employeeId;
}
private void reportButton_Click(object sender, EventArgs e)
{
Report report = new Report();
report.Show();
}
}
}
Remove local variable declaration, because employeeID is a global variable and already declared first, so when you prefix it using string its create another local variable which is not accessible outside this scope
while (myReader.Read())
{
employeeID = myReader["EmployeeID"].ToString();
}
You have a local variable. You can correct and optimize you code like this:
private void loginButton_Click(object sender, EventArgs e)
{
//If use set quote into your textbox
string name = nameTextBox.Text.Replace("'", "''");
string pass = passwordTextBox.Text.Replace("'", "''");
String query = string.Format("select * from Employees where Name = '{0}' and Password = '{1}'", name, pass);
string employeeID = "";
using (SqlConnection connection = new SqlConnection(#"Data Source=INCEPSYS-SE\TEST;Initial Catalog=Employee;Integrated Security=True"))
{
connection.Open();
using (SqlDataAdapter sda = new SqlDataAdapter(query, connection))
{
DataTable dt = new DataTable();
sda.Fill(dt);
if (dt.Rows.Count > 0)
{
employeeID = dt.Rows[0]["EmployeeID"].ToString();
this.Hide();
Entry ss = new Entry(employeeID);
ss.Show();
}
else
{
MessageBox.Show("Please Check your Username & password");
}
dt.Dispose();
}
}
}
I have a login_form and an admin_form. whenever I try to login I keep getting an empty form. why do I keep getting it?
this my login_form code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.IO;
namespace InternationalStudentsSociteySmartSystem
{
public partial class login_form : Form
{
public login_form()
{
InitializeComponent();
}
private void login_button_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(#"Data Source=.;Initial Catalog=ISSSS_DB;Integrated Security=True");
SqlDataAdapter sda = new SqlDataAdapter("Select Count(*) from Table_1 where FullName='" + username_text.Text + "' and Password='" + password_text.Text + "' and Role='" + comboBox1.Text + "'", con);
DataTable dt = new System.Data.DataTable();
sda.Fill(dt);
if (dt.Rows[0][0].ToString() == "1")
{
SqlDataAdapter sda1 = new SqlDataAdapter("Select Role from Table_1 where FullName='" + username_text.Text + "' and Password='" + password_text.Text + "'", con);
DataTable dt1 = new System.Data.DataTable();
sda1.Fill(dt1);
if (dt1.Rows[0][0].ToString() == "Administrator")
{
admin_form ss = new admin_form();
ss.Show();
}
if (dt1.Rows[0][0].ToString() == "Committee")
{
committee_form ss = new committee_form();
ss.Show();
}
if (dt1.Rows[0][0].ToString() == "Secretary")
{
secretary_form ss = new secretary_form();
ss.Show();
}
}
}
}
}
and this is my admin_form code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.IO;
namespace InternationalStudentsSociteySmartSystem
{
public partial class admin_form : Form
{
SqlConnection conn = new SqlConnection("Data Source=TAREK-PC;Initial Catalog=ISSSS_DB;Integrated Security=True");
SqlCommand command;
string imgLoc;
SqlDataReader myReader;
public admin_form(string username)
{
InitializeComponent();
}
public admin_form()
{
// TODO: Complete member initialization
}
private void button1_Click(object sender, EventArgs e)
{
welcome_text.Text = "Welcome!";
try
{
string sql = "SELECT Image FROM Table_1 WHERE FullName='" + admin_name_text.Text + "'";
if (conn.State != ConnectionState.Open)
conn.Open();
command = new SqlCommand(sql, conn);
SqlDataReader reader = command.ExecuteReader();
reader.Read();
if (reader.HasRows)
{
byte[] img = (byte[])(reader[0]);
if (img == null)
admin_picturebox.Image = null;
else
{
MemoryStream ms = new MemoryStream(img);
admin_picturebox.Image = Image.FromStream(ms);
}
}
else
{
}
conn.Close();
}
catch (Exception ex)
{
conn.Close();
MessageBox.Show(ex.Message);
}
}
private void admin_form_Load(object sender, EventArgs e)
{
admin_picturebox.SizeMode = PictureBoxSizeMode.StretchImage;
}
private void register_committee_button_Click(object sender, EventArgs e)
{
register_committee_form rcf = new register_committee_form();
rcf.Show();
}
}
}
as you can see I also have to other forms which are committee_form and secretary_form (which they work just fine) but I didn't write their code yet. so I figured the problem is with admin form...
I appreciate the help, thanks.
You are calling the admin_form constructor that doesn't take any parameters. In that constructor the call to InitializeComponent is missing. So your admin_form is totally blank
You should add the call to InitializeComponent also to the parameterless constructor of admin_form.
public admin_form(string username)
{
InitializeComponent();
}
public admin_form()
{
// TODO: Complete member initialization
InitializeComponent();
}
As a side note, not related to your actual problem. Your code that access the database is vulnerable to Sql Injection hacks. And you will have a lot of problems to parse your input data. You should start immediately to use a parameterized query approach instead of string concatenation
i have a slight problem here,I have the following master tables
M_employee
EMPID Name
1 abc
2 xyz
M_Division
DIVID EMPID DIVISON
1 2 arts
2 1 science
M_Designation
DESGID EMPID Designation
1 2 Teacher
2 1 Scientist
and based on the ID's present in the master table i retrieve few fields on a label in a form....What i want to do is when i store these values of the form in a new table i want only the id's to be stored and not the text values which are being displayed in the label of the form.Below is the code I tried..Can anyone help me?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
using System.Data.OleDb;
using System.Configuration;
using System.Web.UI.HtmlControls;
using System.Xml.Linq;
namespace Travel1.Forms
{
public partial class temporaryduty : System.Web.UI.Page
{
SqlConnection conn = new SqlConnection("Server; Database; Integrated security = true");
protected void Page_Load(object sender, EventArgs e)
{
Lbltoday.Text = DateTime.Now.ToString();
if (!IsPostBack)
{
GetName();//adding the group to the dropdownbox
}
}
private void GetName()
{
SqlCommand cmd = new SqlCommand("Select EMPID,Name FROM M_employee where IsActive=1 ORDER BY Name", conn);
DataSet objDs = new DataSet();
SqlDataAdapter sd = new SqlDataAdapter(cmd);
conn.Open();
sd.Fill(objDs);
conn.Close();
if (objDs.Tables[0].Rows.Count > 0)
{
ddlname.DataSource = objDs.Tables[0];
ddlname.DataTextField = "Name";
ddlname.DataValueField = "EMPID";
ddlname.DataBind();
ddlname.Items.Insert(0, "--Select--");
}
}
protected void ddlname_SelectedIndexChanged(object sender, EventArgs e)
{
GetDivision(ddlname.SelectedItem.Value);
}
private void GetDivision(string Name)
{
SqlCommand cmd = new SqlCommand("SELECT M_employee.Name, M_Division.DIVISION, M_Division.DIVID AS Expr1, M_Designation.DesigID AS Expr2, M_Designation.Designation FROM M_employee INNER JOIN M_Division ON M_employee.DIVID = M_Division.DIVID INNER JOIN M_Designation ON M_employee.DesigID = M_Designation.DesigID WHERE M_employee.EMPID=#EMPID ", conn);
cmd.Parameters.AddWithValue("#EMPID", Name);
DataSet objDs = new DataSet();
SqlDataAdapter sd = new SqlDataAdapter(cmd);
conn.Open();
sd.Fill(objDs);
conn.Close();
if (objDs.Tables[0].Rows.Count > 0)
{
lbldiv.Text = objDs.Tables[0].Rows[0]["DIVISION"].ToString();
lbldesig.Text = objDs.Tables[0].Rows[0]["Designation"].ToString();
}
}
protected void btnSubmit_Click2(object sender, EventArgs e)
{
string RelaseDate = Calendar1.SelectedDate.Date.ToString();
SqlCommand cmd = new SqlCommand("Insert into T_TADA_tempform(EMPID,DIVID,DesigID) values(#EMPID,#DIVID,#DesigID)", conn);
cmd.Parameters.AddWithValue("#EMPID", ddlname.SelectedValue);
cmd.Parameters.AddWithValue("#DIVID", lbldesig.Text);
cmd.Parameters.AddWithValue("#DesigID", lbldiv.Text);
if (conn.State == ConnectionState.Closed)
{
conn.Open();
int cnt = cmd.ExecuteNonQuery();
conn.Close();
if (cnt == 1)
{
Response.Redirect("form.aspx");
}
else
Response.Write("Form has not been submitted,Please Try again!");
}
}
}
}
As requested, here is the idiomatic way of using using for IDisposable resources. Note, I've done nothing else with the code's logic but that, so pay attention to other answers :)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
using System.Data.OleDb;
using System.Configuration;
using System.Web.UI.HtmlControls;
using System.Xml.Linq;
namespace Travel1.Forms
{
public partial class temporaryduty : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Lbltoday.Text = DateTime.Now.ToString();
if (!IsPostBack)
{
GetName();//adding the group to the dropdownbox
}
}
private void GetName()
{
using (SqlConnection conn = new SqlConnection("Server; Database; Integrated security = true"))
using (SqlCommand cmd = new SqlCommand("Select EMPID,Name FROM M_employee where IsActive=1 ORDER BY Name", conn))
using (DataSet objDs = new DataSet())
using (SqlDataAdapter sd = new SqlDataAdapter(cmd))
{
conn.Open();
sd.Fill(objDs);
if (objDs.Tables[0].Rows.Count > 0)
{
ddlname.DataSource = objDs.Tables[0];
ddlname.DataTextField = "Name";
ddlname.DataValueField = "EMPID";
ddlname.DataBind();
ddlname.Items.Insert(0, "--Select--");
}
}
}
protected void ddlname_SelectedIndexChanged(object sender, EventArgs e)
{
GetDivision(ddlname.SelectedItem.Value);
}
private void GetDivision(string Name)
{
using (SqlConnection conn = new SqlConnection("Server; Database; Integrated security = true"))
using (SqlCommand cmd = new SqlCommand("SELECT M_employee.Name, M_Division.DIVISION, M_Division.DIVID AS Expr1, M_Designation.DesigID AS Expr2, M_Designation.Designation FROM M_employee INNER JOIN M_Division ON M_employee.DIVID = M_Division.DIVID INNER JOIN M_Designation ON M_employee.DesigID = M_Designation.DesigID WHERE M_employee.EMPID=#EMPID ", conn))
using (DataSet objDs = new DataSet())
using (SqlDataAdapter sd = new SqlDataAdapter(cmd))
{
cmd.Parameters.AddWithValue("#EMPID", Name);
conn.Open();
sd.Fill(objDs);
if (objDs.Tables[0].Rows.Count > 0)
{
lbldiv.Text = objDs.Tables[0].Rows[0]["DIVISION"].ToString();
lbldesig.Text = objDs.Tables[0].Rows[0]["Designation"].ToString();
}
}
}
protected void btnSubmit_Click2(object sender, EventArgs e)
{
string RelaseDate = Calendar1.SelectedDate.Date.ToString();
int cnt;
using (SqlConnection conn = new SqlConnection("Server; Database; Integrated security = true"))
using (SqlCommand cmd = new SqlCommand("Insert into T_TADA_tempform(EMPID,DIVID,DesigID) values(#EMPID,#DIVID,#DesigID)", conn))
{
cmd.Parameters.AddWithValue("#EMPID", ddlname.SelectedValue);
cmd.Parameters.AddWithValue("#DIVID", lbldesig.Text);
cmd.Parameters.AddWithValue("#DesigID", lbldiv.Text);
conn.Open();
cnt = cmd.ExecuteNonQuery();
}
if (cnt == 1)
{
Response.Redirect("form.aspx");
}
else
Response.Write("Form has not been submitted,Please Try again!");
}
}
}
When you read in your division and designation, store the ids somewhere, like in a private filed of this class:
public partial class temporaryduty : System.Web.UI.Page
{
private int divisionId;
private int designationId;
...
if (objDs.Tables[0].Rows.Count > 0)
{
lbldiv.Text = objDs.Tables[0].Rows[0]["DIVISION"].ToString();
lbldesig.Text = objDs.Tables[0].Rows[0]["Designation"].ToString();
divisionId = objDs.Tables[0].Rows[0]["Expr1"];
designationId = objDs.Tables[0].Rows[0]["Expr2"];
}
Then, on your button click use those fields to insert the ids:
cmd.Parameters.AddWithValue("#DIVID", divisionId);
cmd.Parameters.AddWithValue("#DesigID", designationId);
I use C#.NET (WebApp) VS 2008 SP1
I want click next page from crystal report v.10.5.3700 (Framework 3.5) but it's show input data to next page
The report you requested requires further information
Server name:
Database name:
User name:
Password:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.OleDb;
using System.Diagnostics;
using System.Data.SqlClient;
using System.Web.Configuration;
using System.Transactions;
using System.Drawing;
using System.Globalization;
using System.Text;
using System.Text.RegularExpressions;
using System.IO;
using CrystalDecisions.Web;
using CrystalDecisions.CrystalReports;
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Shared;
using CrystalDecisions.ReportSource;
namespace testReport
{
public partial class _cldClass : System.Web.UI.Page
{
SqlConnection objConn = new SqlConnection();
SqlCommand objCmd = new SqlCommand();
SqlDataAdapter dtAdapter = new SqlDataAdapter();
SqlConnection Conn;
DataSet ds = new DataSet();
DataTable dt = null;
string strConnString = WebConfigurationManager.ConnectionStrings["connDB"].ConnectionString;
string strSQL = null;
public string userDB
{
get { return WebConfigurationManager.AppSettings["userDB"]; }
}
public string pwdDB
{
get { return WebConfigurationManager.AppSettings["pwdDB"]; }
}
public string srvDB
{
get { return WebConfigurationManager.AppSettings["srvDB"]; }
}
public string dbName
{
get { return WebConfigurationManager.AppSettings["dbName"]; }
}
//protected void Page_Load(object sender, EventArgs e)
//{
//}
protected void Page_Init(object sender, EventArgs e)
{
TextBox2.Text = DateTime.Now.ToString("yyyy-MM-dd", new CultureInfo("en-US"));
Conn = new SqlConnection(strConnString);
Conn.Open();
if (Conn.State == ConnectionState.Open)
{
this.Label1.Text = "Connected";
}
else
{
this.Label1.Text = "Connect Failed";
}
}
protected void Button2_Click(object sender, EventArgs e)
{
strSQL = "SELECT * FROM fTime WHERE fDate='" + TextBox2.Text + "'";
objConn.ConnectionString = strConnString;
var _with1 = objCmd;
_with1.Connection = objConn;
_with1.CommandText = strSQL;
_with1.CommandType = CommandType.Text;
dtAdapter.SelectCommand = objCmd;
dtAdapter.Fill(ds, "cReport");
dt = ds.Tables[0];
dtAdapter = null;
objConn.Close();
objConn = null;
ReportDocument rpt = new ReportDocument();
rpt.Load(Server.MapPath("Report\\CrystalReport.rpt"));
rpt.SetDataSource(dt);
rpt.SetDatabaseLogon(userDB, pwdDB, srvDB, dbName);
CrystalReportViewer1.ReportSource = rpt;
CrystalReportViewer1.RefreshReport();
}
}
}
Thanks for your time :)
Normally you need to enter these informations when you created the report document directly from a database, that means when you used the report wizard and selected a table from the database. The report document itself contains the connection information to that data source but don't saves the logon information.
To overcome this you may create a typed dataset first from your database table you like to use in the report. Then create a report document and use the wizard to set the dataset (not the database table directly) as data source for your report. In your code you may then fill the dataset and just pass it to the report.
I ran into this today, and the reason I got the error was because I didn't have the correct provider installed on my server.
What I did was this:
CrystalReportViewer1.EnableDatabaseLogonPrompt = false;
That gave me a new error: Logon failed. Details: ADO Error Code: 0x Source: ADODB.Connection Description: Provider cannot be found. It may not be properly installed
After that, I checked the OLE DB provider in the report. Installing the SQL Native Client tools fixed the problem.