Loss of Data after printing my crystal report via PrintToPrinter - c#

after printing the document using PrintToPrinter all data is lost, dont know why ????
this code had one more problem, I hve rectified the problem by adding :
rpt.SetDatabaseLogon("u","p");
and now I have empty document printed.
this is my code:
protected void btnPrintToPrinter_Click(object sender, EventArgs e)
{
int empno = Convert.ToInt32(Session["AnyVal"]);
SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
string strQuery = "SELECT [View_EmplDetail].[Uni-Code], [View_EmplDetail].[FacultyCode], [View_EmplDetail].[EmpIDstr], [View_EmplDetail].[EngGivenName], [View_EmplDetail].[position_eng], [View_EmplDetail].[Emp_no], [View_EmplDetail].[GivenName], [View_EmplDetail].[position_name], [View_EmplDetail].[DariName], [Tbl_Dept].[EName], [View_EmplDetail].[photo] FROM [MoHEDatabase].[dbo].[View_EmplDetail] [View_EmplDetail] INNER JOIN [MoHEDatabase].[dbo].[Tbl_Dept] [Tbl_Dept] ON [View_EmplDetail].[DepCode]=[Tbl_Dept].[DepCode] WHERE [Emp_no] = #empno";
SqlCommand command = new SqlCommand(strQuery, connection);
command.CommandType = System.Data.CommandType.Text;
command.Parameters.AddWithValue("#empno", empno);
command.Connection = connection;
command.Connection.Open();
SqlDataAdapter da = new SqlDataAdapter(command);
DataTable dt = new DataTable();
da.Fill(dt);
ReportDocument rpt = new ReportDocument();
string _reportPath = Server.MapPath("..\\Student\\cardFinal.rpt");
//rpt.Load(AppDomain.CurrentDomain.BaseDirectory + "\\" + #"\\Student\\CardFinal.rpt");
rpt.Load(_reportPath);
rpt.SetDataSource(dt);
emp_card_report_viewer.ReportSource = rpt;
string sq = "";
//{View_OrgStr1.Uni-Code}=0 and {View_OrgStr1.FacultyCode}=119
//sq = "{View_StudentAddNew.Student_ID}=" + Session["AnyVal"];
if (Session["AnyVal"].ToString() != "")
{
sq = "{View_EmplDetail.Emp_no}=" + int.Parse(Session["AnyVal"].ToString());
}
//emp_card_report.Report.FileName = "../Student/CardFinal.rpt";
emp_card_report_viewer.SelectionFormula = sq;
//ConnectionInfo connInfo = new ConnectionInfo();
//connInfo.ServerName = "172.16.0.15";
//connInfo.DatabaseName = "MoHEMISDatabase";
//connInfo.UserID = "hemis_admin";
//connInfo.Password = "hemis#sabir";
//TableLogOnInfos crtt = new TableLogOnInfos();
//TableLogOnInfo crtto = new TableLogOnInfo();
//Tables crtables;
//crtables = rpt.Database.Tables;
//foreach (CrystalDecisions.CrystalReports.Engine.Table crtable in crtables)
//{
// crtto = crtable.LogOnInfo;
// crtto.ConnectionInfo = connInfo;
// //crtable.ApplyLogInInfo(crtto);
//}
ConnectionInfo connInfo1 = new ConnectionInfo();
// connInfo1.ServerName = "server";
setDBLOGONforReport(connInfo1);
//emp_card_report_viewer.RefreshReport();
//ConnectionInfo connInfo = new ConnectionInfo();
//connInfo.ServerName = "server";
//connInfo.DatabaseName = "MoHEDatabase";
//connInfo.UserID = "hemis_admin";
//connInfo.Password = "hemis#sabir";
//setDBLOGONforReport(connInfo);
CrystalDecisions.Shared.PageMargins pageMargins = new
CrystalDecisions.Shared.PageMargins(0, 0, 0, 0);
rpt.PrintOptions.ApplyPageMargins(pageMargins);
rpt.PrintOptions.PrinterName = printerList.SelectedItem.Value;
emp_card_report_viewer.RefreshReport();
rpt.PrintToPrinter(1, false, 1, 1);
rpt.Close();
rpt = null;
}

THE ANSWER:
I was using Select Expert Record in the crystal report , I removed all formula in Select Expert and it worked .... :)

Related

need a quicker way to select data and paste it in an excel sheet

It took me a while to just find a way to select data from my database and then paste it in an excel spreadsheet. Now that I've found it, it runs dirt slow. Like I said before, I've looked at a lot of different ways to accomplish this but have not been able to correctly implement any of them except for this. I'm not married to this option but it is the only one I could get to work. Could someone help me out by suggesting a quicker way to accomplish this simple task? Please see my code below.
Record850 rec850 = new Record850();
List<Record850> lst850records = new List<Record850>();
//SqlConnection connStr = new SqlConnection("Server = 172.18.211.76; Database = Processstage; User Id = brendon.davies; Password = mypassword;");
SqlConnection conn = new SqlConnection("Server = 172.18.211.76; Database = Processstage; User Id = brendon.davies; Password = mypassword;");
//SqlConnection sqlConnection1 = new SqlConnection(conn);
SqlCommand cmd = new SqlCommand();
SqlDataReader reader;
cmd.CommandText = Select_850;
cmd.CommandType = CommandType.Text;
cmd.Connection = conn;
conn.Open();
Record850 reco850 = new Record850();
string strComplete = "";
reader = cmd.ExecuteReader();
while (reader.Read())
{
try
{
reco850.OrgName = reader.GetString(0);
reco850.WholeSalerAccountDivisionCode = reader.GetString(1);
reco850.File_Process_Name = reader.GetString(2);
reco850.Pur_Ord_Num_BEG03 = reader.GetString(3);
reco850.File_Process_ID = reader.GetInt64(4);
reco850.CECode = reader.GetString(5);
reco850.CEName = reader.GetString(6);
reco850.Modified_Date = reader.GetDateTime(7);
lst850records.Add(reco850);
reco850 = new Record850();
}
catch(Exception e)
{
Console.WriteLine(e.ToString());
}
}
conn.Close();
eWorkSheet = (Excel.Worksheet)oSheets.get_Item("850_Template");
eWorkSheet.Activate();
int int850counter = 0;
int int850RowCounter = 3;
foreach (Record850 r850 in lst850records)
{
strComplete = lst850records[int850counter].OrgName + "\t" +
lst850records[int850counter].WholeSalerAccountDivisionCode + "\t" +
lst850records[int850counter].File_Process_Name + "\t" +
lst850records[int850counter].Pur_Ord_Num_BEG03 + "\t" +
lst850records[int850counter].File_Process_ID + "\t" +
lst850records[int850counter].CECode + "\t" +
lst850records[int850counter].CEName+ "\t" +
lst850records[int850counter].Modified_Date;
CR = (Excel.Range)eWorkSheet.Cells[int850RowCounter,3];
Clipboard.SetText(strComplete);
CR.Select();
eWorkSheet.Paste(CR, false);
Clipboard.Clear();
int850RowCounter++;
int850counter++;
strComplete = ""
}
Here's an answer that also runs quickly, just about the same as the use of EPPlus above. Do not attempt the cell by cell approach (commented out below) as that indeed runs at a snail's pace by comparison.
[STAThread]
static void Main(string[] args)
{
Excel.Application xl = null;
try {
xl = new Excel.Application();
xl.ScreenUpdating = false;
xl.Visible = false;
xl.UserControl = false;
var wb = xl.Workbooks.Open(SOURCE_PATH);
var ws = (Microsoft.Office.Interop.Excel.Worksheet)wb.Sheets.Item["850_Template"];
StringBuilder sb = new StringBuilder();
//int row = 3;
// var a1 = ws.Range["A1", Missing.Value];
using (SqlConnection cn = new SqlConnection(CN_STR)) {
cn.Open();
using (SqlCommand cmd = new SqlCommand(SQL, cn)) {
cmd.CommandType = CommandType.Text;
using (SqlDataReader dr = cmd.ExecuteReader()) {
while (dr.Read())
{
sb.AppendFormat("{0}\t{1}\t{2}\t{3}\t{4}\t{5}\t{6}\t{7}\r\n",
(string)dr["OrgName"],
(string)dr["WholeSalerAccountDivisionCode"],
(string)dr["File_Process_Name"],
(string)dr["Pur_Ord_Num_BEG03"],
(long)dr["File_Process_ID"],
(string)dr["CECode"],
(string)dr["CEName"],
(DateTime)dr["Modified_Date"]
);
//a1.Offset[row, 0].Value = (string)dr["OrgName"];
//a1.Offset[row, 1].Value = (string)dr["WholeSalerAccountDivisionCode"];
//a1.Offset[row, 2].Value = (string)dr["File_Process_Name"];
//a1.Offset[row, 3].Value = (string)dr["Pur_Ord_Num_BEG03"];
//a1.Offset[row, 4].Value = (long)dr["File_Process_ID"];
//a1.Offset[row, 5].Value = (string)dr["CECode"];
//a1.Offset[row, 6].Value = (string)dr["CEName"];
//a1.Offset[row, 7].Value = (DateTime)dr["Modified_Date"];
//row++;
}
}
}
cn.Close();
}
Clipboard.SetText(sb.ToString(),
TextDataFormat.Text);
var rng = ws.Range["A3", Missing.Value];
rng.Select();
ws.Paste(rng, Missing.Value);
Clipboard.Clear();
wb.Save();
wb.Close();
xl.Quit();
} catch (Exception ex) {
Console.WriteLine(ex.Message);
if (xl != null) {
xl.ScreenUpdating = true;
xl.Visible = true;
xl.UserControl = true;
}
}
}
Here's an alternative that uses the EPPlus approach, much faster.
try {
var app = new ExcelPackage(new FileInfo(SOURCE_PATH));
var ws = app.Workbook.Worksheets["850_Template"];
int row = 3;
using (SqlConnection cn = new SqlConnection(CN_STR)) {
cn.Open();
using (SqlCommand cmd = new SqlCommand(SQL, cn)) {
cmd.CommandType = CommandType.Text;
using (SqlDataReader dr = cmd.ExecuteReader()) {
while (dr.Read())
{
ws.SetValue(row, 1, (string) dr["OrgName"]);
ws.SetValue(row, 2, (string) dr["WholeSalerAccountDivisionCode"]);
ws.SetValue(row, 3, (string) dr["File_Process_Name"]);
ws.SetValue(row, 4, (string) dr["Pur_Ord_Num_BEG03"]);
ws.SetValue(row, 5, (long) dr["File_Process_ID"]);
ws.SetValue(row, 6, (string) dr["CECode"]);
ws.SetValue(row, 7, (string) dr["CEName"]);
ws.SetValue(row, 8, (DateTime) dr["Modified_Date"]);
row++;
}
}
}
cn.Close();
}
app.Save();
} catch (Exception ex) {
Console.WriteLine(ex.Message);
}

sap crystalreport c# add-on logonfailed

i'm too getting too stuck trying to solve this issue i try to print directly value from my sap add-on using c# in visualstudio 2010 it's return for me this error:
'logonfailed' here is my code :
try
{
DataTable matable = new DataTable();
DataSet madataset = new DataSet();
SqlConnection maconnexion = new SqlConnection();
maconnexion.ConnectionString = Menu.connectionString_formatsql;
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "select oitm.ItemCode ,OITM .ItemName ,OITM .CodeBars,ITM1.Price,#codebars " +
" from OITM,ITM1 where OITM .ItemCode=ITM1 .ItemCode" +
" and OITM.ItemCode =#itemCode" +
" and ITM1 .PriceList = #pricelist ";
cmd.Parameters.Clear();
//cmd.Parameters.Add("#codebars", SqlDbType.VarChar );
//cmd.Parameters["#codebars"].Value = get_codebarre_dessin();
//cmd.Parameters.Add("#itemCode", SqlDbType.VarChar);
//cmd.Parameters["#itemCode"].Value = this.EditText1.Value;
//cmd.Parameters.Add("#pricelist", SqlDbType.SmallInt);
//cmd.Parameters["#pricelist"].Value = Convert.ToInt32(this.ComboBox0.Value);
cmd.Parameters.Add("#codebars", SqlDbType.VarChar);
cmd.Parameters["#codebars"].Value = get_codebarre_dessin();
cmd.Parameters.Add("#itemCode", SqlDbType.VarChar);
cmd.Parameters["#itemCode"].Value = this.EditText1.Value;
cmd.Parameters.Add("#pricelist", SqlDbType.Int);
cmd.Parameters["#pricelist"].Value = Convert.ToInt32(this.ComboBox0.Value);
cmd.Connection = maconnexion;
if (maconnexion.State == ConnectionState.Closed)
{
maconnexion.Open();
}
SqlDataAdapter madataadapter = new SqlDataAdapter(cmd);
// SqlCommandBuilder madatabuilder = new SqlCommandBuilder(madataadapter );
matable.Load(cmd.ExecuteReader());
madataset.Tables.Add(matable);
ReportDocument report = new ReportDocument();
report.Load("BARCODE.rpt");
report.Refresh();
report.DataSourceConnections.Clear();
foreach (CrystalDecisions.CrystalReports.Engine.Table table in report.Database.Tables)
{
TableLogOnInfo tableLogOnInfo = table.LogOnInfo;
MessageBox.Show( tableLogOnInfo.ConnectionInfo.ServerName );
MessageBox.Show( tableLogOnInfo.ConnectionInfo.DatabaseName);
MessageBox.Show(tableLogOnInfo.ConnectionInfo.UserID);
MessageBox.Show(tableLogOnInfo.ConnectionInfo.Password.ToString());
MessageBox.Show(tableLogOnInfo.ConnectionInfo.IntegratedSecurity.ToString() );
//table.ApplyLogOnInfo(tableLogOnInfo);
//table.Location = Menu.company.CompanyDB + ".dbo." + table.Name.ToString();
}
foreach (CrystalDecisions.CrystalReports.Engine.Table table in report.Database.Tables)
{
TableLogOnInfo tableLogOnInfo = table.LogOnInfo;
tableLogOnInfo.ConnectionInfo.AllowCustomConnection = true;
tableLogOnInfo.ConnectionInfo.ServerName = Menu.company.Server;
tableLogOnInfo.ConnectionInfo.DatabaseName = Menu.company.CompanyDB;
//tableLogOnInfo.ConnectionInfo.UserID = Menu.company.UserName;
//tableLogOnInfo.ConnectionInfo.Password = Menu.company.Password;
tableLogOnInfo.ConnectionInfo.UserID = Menu .company.DbUserName;
tableLogOnInfo.ConnectionInfo.Password = Menu.company.DbPassword;
tableLogOnInfo.ConnectionInfo.IntegratedSecurity = false ;
table.ApplyLogOnInfo(tableLogOnInfo);
table.Location = Menu.company.CompanyDB + ".dbo." + table.Name.ToString();
}
foreach (CrystalDecisions.CrystalReports.Engine.Table table in report.Database.Tables)
{
TableLogOnInfo tableLogOnInfo = table.LogOnInfo;
MessageBox.Show(tableLogOnInfo.ConnectionInfo.ServerName);
MessageBox.Show(tableLogOnInfo.ConnectionInfo.DatabaseName);
MessageBox.Show(tableLogOnInfo.ConnectionInfo.UserID);
MessageBox.Show(tableLogOnInfo.ConnectionInfo.Password.ToString());
MessageBox.Show(tableLogOnInfo.ConnectionInfo.IntegratedSecurity.ToString());
//table.ApplyLogOnInfo(tableLogOnInfo);
//table.Location = Menu.company.CompanyDB + ".dbo." + table.Name.ToString();
}
report.SetDataSource(matable);
report.SetDatabaseLogon(Menu.company.DbUserName, Menu.company.DbPassword);
PrinterSettings settings = new PrinterSettings();
PrintDialog pdialog = new PrintDialog();
pdialog.PrinterSettings = settings;
pdialog.AllowPrintToFile = true;
pdialog.AllowSomePages = true;
pdialog.UseEXDialog = true;
// ParameterFields parameterFields = report.ParameterFields;
//report.SetParameterValue(0, this.ComboBox0.Value);
//report.SetParameterValue(1, EditText1.Value.ToString());
//report.SetParameterValue(2, get_codebarre_dessin());
report.SetParameterValue(2, this.ComboBox0.Value);
report.SetParameterValue(1, EditText1.Value.ToString());
report.SetParameterValue(0, get_codebarre_dessin());
report.PrintOptions.PrinterName = ComboBox1.Value;
//report.PrintToPrinter(settings, new PageSettings() { }, false);
report.PrintToPrinter(1, true, 1, System.Convert.ToInt32(EditText0.Value));
maconnexion.Close();
}
catch (LogOnException engEx)
{
MessageBox.Show("Incorrect Logon Parameters. Check your user name and password." + engEx.ErrorID);
}
catch (DataSourceException engEx)
{
MessageBox.Show("An error has occurred while connecting to the database.");
}
catch (EngineException engEx)
{
MessageBox.Show(engEx.Message);
}

How To insert data into SQL Sever with C# without using the database wizard(visual studio)

I'm having trouble inserting data into my table called "client" in my database called "vet".
I'm trying to do the connection manually as opposed to using the database wizard. I want to do it this way so that i can hide the majority of my code in a separate class.
I have a feeling I have the logic for this all wrong as I'm not making use of a data set, I was hoping someone could point me in the right direction.
This is for a school assignment and not for real world use. I have read a number of similar posts but am still unable to come to a solution.
public void CommitToDatabase()
{
using (var con = new SqlConnection(CLSDatabaseDetails.GlobalConnectionString))
{
DataTable client = new DataTable();
DataSet ds = new DataSet();
string commandString = "SELECT * FROM client";
SqlCommand cmd = new SqlCommand(commandString, con);
con.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(client);
DataRow newClientRow = ds.Tables["client"].NewRow();
newClientRow["ClientID"] = ClientID;
newClientRow["FirstName"] = FirstName;
newClientRow["LastName"] = LastName;
newClientRow["Phone"] = PhoneNumber;
newClientRow["CAddress"] = Address;
newClientRow["Email"] = Email;
newClientRow["CUsername"] = Username;
newClientRow["CPassword"] = Password;
client.Rows.Add(newClientRow);
da.Update(client);
}
}
A DataSet is a collection of DataTables. In your example, you're only referring to one table. The SqlDataAdapter.Fill method will populate either DataSet or DataTable. You're calling da.Fill(client) which is fine - it will fill the DataTable client. You could also call da.Fill(ds, "client") which will fill the DataSet ds. You can then extract your table via ds.Tables["client"]. Using a DataSet in this example is overkill, but you can show your tutor how a DataSet works.
You're filling the DataTable but then adding the new row with reference to the DataSet. But in your example, the DataSet ds has nothing in it, because you filled the DataTable not the DataSet. Try this:
DataSet ds = new DataSet();
string commandString = "SELECT TOP 0 * FROM client";
SqlCommand cmd = new SqlCommand(commandString, con);
con.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
SqlCommandBuilder builder = new SqlCommandBuilder(da);
da.Fill(ds, "client");
DataTable client = ds.Tables["client"];
DataRow newClientRow = client.NewRow();
... ... ...
client.Rows.Add(newClientRow);
builder.GetInsertCommand();
da.Update(client);
If you only want to insert a row, you don't need to SELECT all the rows. If you SELECT TOP 0 * from client you'll get the column names (which you need) but without the overhead of returning all the rows.
Try something like this:
public void CommitToDatabase()
{
using (var con = new SqlConnection(CLSDatabaseDetails.GlobalConnectionString))
{
DataTable client = new DataTable();
string commandString = "SELECT * FROM client";
SqlCommand cmd = new SqlCommand(commandString, con);
con.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(client);
DataRow newClientRow = client.NewRow();
newClientRow["ClientID"] = ClientID;
newClientRow["FirstName"] = FirstName;
newClientRow["LastName"] = LastName;
newClientRow["Phone"] = PhoneNumber;
newClientRow["CAddress"] = Address;
newClientRow["Email"] = Email;
newClientRow["CUsername"] = Username;
newClientRow["CPassword"] = Password;
client.Rows.Add(newClientRow);
da.Update(client);
}
}
I can't tell what the source of your data is. Anyway, here are two examples of moving data from a CSV file to SQL Server and from a DataGridView to SQL Server.
using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Data.SqlClient;
using System.IO;
using Microsoft.VisualBasic.FileIO;
using System.Data.Odbc;
using System.Data.OleDb;
using System.Configuration;
public class Form1
{
private void Button1_Click(System.Object sender, System.EventArgs e)
{
dynamic headers = (from header in DataGridView1.Columns.Cast<DataGridViewColumn>()header.HeaderText).ToArray;
dynamic rows = from row in DataGridView1.Rows.Cast<DataGridViewRow>()where !row.IsNewRowArray.ConvertAll(row.Cells.Cast<DataGridViewCell>.ToArray, c => c.Value != null ? c.Value.ToString : "");
string str = "";
using (IO.StreamWriter sw = new IO.StreamWriter("C:\\Users\\Excel\\Desktop\\OrdersTest.csv")) {
sw.WriteLine(string.Join(",", headers));
//sw.WriteLine(String.Join(","))
foreach (void r_loopVariable in rows) {
r = r_loopVariable;
sw.WriteLine(string.Join(",", r));
}
sw.Close();
}
}
private void Button2_Click(System.Object sender, System.EventArgs e)
{
//Dim m_strConnection As String = "server='Server_Name';Initial Catalog='Database_Name';Trusted_Connection=True;"
//Catch ex As Exception
// MessageBox.Show(ex.ToString())
//End Try
//Dim objDataset1 As DataSet()
//Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
//Dim da As OdbcDataAdapter
System.Windows.Forms.OpenFileDialog OpenFile = new System.Windows.Forms.OpenFileDialog();
// Does something w/ the OpenFileDialog
string strFullPath = null;
string strFileName = null;
TextBox tbFile = new TextBox();
// Sets some OpenFileDialog box options
OpenFile.Filter = "CSV Files (*.csv)|*.csv|All files (*.*)|*.*";
// Shows only .csv files
OpenFile.Title = "Browse to file:";
// Title at the top of the dialog box
// Makes the open file dialog box show up
if (OpenFile.ShowDialog() == DialogResult.OK) {
strFullPath = OpenFile.FileName;
// Assigns variable
strFileName = Path.GetFileName(strFullPath);
// Checks to see if they've picked a file
if (OpenFile.FileNames.Length > 0) {
tbFile.Text = strFullPath;
// Puts the filename in the textbox
// The connection string for reading into data connection form
string connStr = null;
connStr = "Driver={Microsoft Text Driver (*.txt; *.csv)}; Dbq=" + Path.GetDirectoryName(strFullPath) + "; Extensions=csv,txt ";
// Sets up the data set and gets stuff from .csv file
OdbcConnection Conn = new OdbcConnection(connStr);
DataSet ds = default(DataSet);
OdbcDataAdapter DataAdapter = new OdbcDataAdapter("SELECT * FROM [" + strFileName + "]", Conn);
ds = new DataSet();
try {
DataAdapter.Fill(ds, strFileName);
// Fills data grid..
DataGridView1.DataSource = ds.Tables(strFileName);
// ..according to data source
// Catch and display database errors
} catch (OdbcException ex) {
OdbcError odbcError = default(OdbcError);
foreach ( odbcError in ex.Errors) {
MessageBox.Show(ex.Message);
}
}
// Cleanup
OpenFile.Dispose();
Conn.Dispose();
DataAdapter.Dispose();
ds.Dispose();
}
}
}
private void Button3_Click(System.Object sender, System.EventArgs e)
{
SqlConnection cnn = default(SqlConnection);
string connectionString = null;
string sql = null;
connectionString = "data source='Server_Name';" + "initial catalog='Database_Name';Trusted_Connection=True";
cnn = new SqlConnection(connectionString);
cnn.Open();
sql = "SELECT * FROM [Order Details]";
SqlDataAdapter dscmd = new SqlDataAdapter(sql, cnn);
DataSet ds = new DataSet();
dscmd.Fill(ds);
DataGridView1.DataSource = ds.Tables(0);
cnn.Close();
}
private void ProductsDataGridView_CellFormatting(object sender, System.Windows.Forms.DataGridViewCellFormattingEventArgs e)
{
if (e.ColumnIndex == DataGridView1.Columns(3).Index && e.Value != null) {
//
if (Convert.ToInt32(e.Value) < 10) {
e.CellStyle.BackColor = Color.OrangeRed;
e.CellStyle.ForeColor = Color.LightGoldenrodYellow;
}
//
}
//
}
//Private Sub ProductsDataGridView_CellFormatting(ByVal sender As Object, _
// ByVal e As System.Windows.Forms.DataGridViewCellFormattingEventArgs) _
// Handles DataGridView1.CellFormatting
// '
// If e.ColumnIndex = DataGridView1.Columns("DataGridViewTextBoxColumn8").Index _
// AndAlso e.Value IsNot Nothing Then
// '
// If CInt(e.Value) < 5 Then
// e.CellStyle.BackColor = Color.OrangeRed
// e.CellStyle.ForeColor = Color.LightGoldenrodYellow
// End If
// '
// End If
// '
//End Sub
//If e.ColumnIndex = ProductsDataGridView.Columns(4).Index _
//AndAlso e.Value IsNot Nothing Then
//'
// If CInt(e.Value) = 0 Then
// e.CellStyle.BackColor = Color.OrangeRed
// e.CellStyle.ForeColor = Color.LightGoldenrodYellow
// End If
//End If
// ''To (you need to change the column name)
// If e.ColumnIndex = ProductsDataGridView.Columns("YourColumnName").Index _
// AndAlso e.Value IsNot Nothing Then
//'
// If CInt(e.Value) = 0 Then
// e.CellStyle.BackColor = Color.OrangeRed
// e.CellStyle.ForeColor = Color.LightGoldenrodYellow
// End If
//End If
private void Button4_Click(System.Object sender, System.EventArgs e)
{
DataTable tblReadCSV = new DataTable();
tblReadCSV.Columns.Add("FName");
tblReadCSV.Columns.Add("LName");
tblReadCSV.Columns.Add("Department");
TextFieldParser csvParser = new TextFieldParser("C:\\Users\\Excel\\Desktop\\Employee.txt");
csvParser.Delimiters = new string[] { "," };
csvParser.TrimWhiteSpace = true;
csvParser.ReadLine();
while (!(csvParser.EndOfData == true)) {
tblReadCSV.Rows.Add(csvParser.ReadFields());
}
SqlConnection con = new SqlConnection("Server='Server_Name';Database='Database_Name';Trusted_Connection=True;");
string strSql = "Insert into Employee(FName,LName,Department) values(#Fname,#Lname,#Department)";
//Dim con As New SqlConnection(strCon)
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = strSql;
cmd.Connection = con;
cmd.Parameters.Add("#Fname", SqlDbType.VarChar, 50, "FName");
cmd.Parameters.Add("#Lname", SqlDbType.VarChar, 50, "LName");
cmd.Parameters.Add("#Department", SqlDbType.VarChar, 50, "Department");
SqlDataAdapter dAdapter = new SqlDataAdapter();
dAdapter.InsertCommand = cmd;
int result = dAdapter.Update(tblReadCSV);
}
private void Button5_Click(System.Object sender, System.EventArgs e)
{
string SQLConnectionString = "Data Source=Excel-PC\\SQLEXPRESS;" + "Initial Catalog=Northwind;" + "Trusted_Connection=True";
// Open a connection to the AdventureWorks database.
using (SqlConnection SourceConnection = new SqlConnection(SQLConnectionString)) {
SourceConnection.Open();
// Perform an initial count on the destination table.
SqlCommand CommandRowCount = new SqlCommand("SELECT COUNT(*) FROM dbo.Orders;", SourceConnection);
long CountStart = System.Convert.ToInt32(CommandRowCount.ExecuteScalar());
Console.WriteLine("Starting row count = {0}", CountStart);
// Get data from the source table as a AccessDataReader.
//Dim ConnectionString As String = "Provider=Microsoft.Jet.OLEDB.4.0;" & _
// "Data Source=" & "C:\Users\Excel\Desktop\OrdersTest.txt" & ";" & _
// "Extended Properties=" & "text;HDR=Yes;FMT=Delimited"","";"
string ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + "C:\\Users\\Excel\\Desktop\\" + ";" + "Extended Properties=\"Text;HDR=No\"";
System.Data.OleDb.OleDbConnection TextConnection = new System.Data.OleDb.OleDbConnection(ConnectionString);
OleDbCommand TextCommand = new OleDbCommand("SELECT * FROM OrdersTest#csv", TextConnection);
TextConnection.Open();
OleDbDataReader TextDataReader = TextCommand.ExecuteReader(CommandBehavior.SequentialAccess);
// Open the destination connection.
using (SqlConnection DestinationConnection = new SqlConnection(SQLConnectionString)) {
DestinationConnection.Open();
// Set up the bulk copy object.
// The column positions in the source data reader
// match the column positions in the destination table,
// so there is no need to map columns.
using (SqlBulkCopy BulkCopy = new SqlBulkCopy(DestinationConnection)) {
BulkCopy.DestinationTableName = "dbo.Orders";
try {
// Write from the source to the destination.
BulkCopy.WriteToServer(TextDataReader);
} catch (Exception ex) {
Console.WriteLine(ex.Message);
} finally {
// Close the AccessDataReader. The SqlBulkCopy
// object is automatically closed at the end
// of the Using block.
TextDataReader.Close();
}
}
// Perform a final count on the destination table
// to see how many rows were added.
long CountEnd = System.Convert.ToInt32(CommandRowCount.ExecuteScalar());
//Console.WriteLine("Ending row count = {0}", CountEnd)
//Console.WriteLine("{0} rows were added.", CountEnd - CountStart)
}
}
//Dim FILE_NAME As String = "C:\Users\Excel\Desktop\OrdersTest.csv"
//Dim TextLine As String
//If System.IO.File.Exists(FILE_NAME) = True Then
// Dim objReader As New System.IO.StreamReader(FILE_NAME)
// Do While objReader.Peek() <> -1
// TextLine = TextLine & objReader.ReadLine() & vbNewLine
// Loop
//Else
// MsgBox("File Does Not Exist")
//End If
//Dim cn As New SqlConnection("Data Source=Excel-PC\SQLEXPRESS;Initial Catalog=Northwind;Trusted_Connection=True;")
//Dim cmd As New SqlCommand
//cmd.Connection = cn
//cmd.Connection.Close()
//cmd.Connection.Open()
//cmd.CommandText = "INSERT INTO Orders (OrderID,CustomerID,EmployeeID,OrderDate,RequiredDate,ShippedDate,ShipVia,Freight,ShipName,ShipAddress,ShipCity,ShipRegion,ShipPostalCode,ShipCountry) values & OrdersTest.csv"
//cmd.ExecuteNonQuery()
//cmd.Connection.Close()
}
private void Button6_Click(System.Object sender, System.EventArgs e)
{
// Define the Column Definition
DataTable dt = new DataTable();
dt.Columns.Add("OrderID", typeof(int));
dt.Columns.Add("CustomerID", typeof(string));
dt.Columns.Add("EmployeeID", typeof(int));
dt.Columns.Add("OrderDate", typeof(System.DateTime));
dt.Columns.Add("RequiredDate", typeof(System.DateTime));
dt.Columns.Add("ShippedDate", typeof(System.DateTime));
dt.Columns.Add("ShipVia", typeof(int));
dt.Columns.Add("Freight", typeof(decimal));
dt.Columns.Add("ShipName", typeof(string));
dt.Columns.Add("ShipAddress", typeof(string));
dt.Columns.Add("ShipCity", typeof(string));
dt.Columns.Add("ShipRegion", typeof(string));
dt.Columns.Add("ShipPostalCode", typeof(string));
dt.Columns.Add("ShipCountry", typeof(string));
using (cn == new SqlConnection("Server='Server_Name';Database='Database_Name';Trusted_Connection=True;")) {
cn.Open();
Microsoft.VisualBasic.FileIO.TextFieldParser reader = default(Microsoft.VisualBasic.FileIO.TextFieldParser);
string[] currentRow = null;
DataRow dr = default(DataRow);
string sqlColumnDataType = null;
reader = My.Computer.FileSystem.OpenTextFieldParser("C:\\Users\\Excel\\Desktop\\OrdersTest.csv");
reader.TextFieldType = Microsoft.VisualBasic.FileIO.FieldType.Delimited;
reader.Delimiters = new string[] { "," };
while (!reader.EndOfData) {
try {
currentRow = reader.ReadFields();
dr = dt.NewRow();
for (currColumn = 0; currColumn <= dt.Columns.Count - 1; currColumn++) {
sqlColumnDataType = dt.Columns(currColumn).DataType.Name;
switch (sqlColumnDataType) {
case "String":
if (string.IsNullOrEmpty(currentRow(currColumn))) {
dr.Item(currColumn) = "";
} else {
dr.Item(currColumn) = Convert.ToString(currentRow(currColumn));
}
break;
case "Decimal":
if (string.IsNullOrEmpty(currentRow(currColumn))) {
dr.Item(currColumn) = 0;
} else {
dr.Item(currColumn) = Convert.ToDecimal(currentRow(currColumn));
}
break;
case "DateTime":
if (string.IsNullOrEmpty(currentRow(currColumn))) {
dr.Item(currColumn) = "";
} else {
dr.Item(currColumn) = Convert.ToDateTime(currentRow(currColumn));
}
break;
}
}
dt.Rows.Add(dr);
} catch (Microsoft.VisualBasic.FileIO.MalformedLineException ex) {
Interaction.MsgBox("Line " + ex.Message + "is not valid." + Constants.vbCrLf + "Terminating Read Operation.");
reader.Close();
reader.Dispose();
//Return False
} finally {
dr = null;
}
}
using (SqlBulkCopy copy = new SqlBulkCopy(cn)) {
copy.DestinationTableName = "[dbo].[Orders]";
copy.WriteToServer(dt);
}
}
}
public static bool GetCsvData(string CSVFileName, ref DataTable CSVTable)
{
Microsoft.VisualBasic.FileIO.TextFieldParser reader = default(Microsoft.VisualBasic.FileIO.TextFieldParser);
string[] currentRow = null;
DataRow dr = default(DataRow);
string sqlColumnDataType = null;
reader = My.Computer.FileSystem.OpenTextFieldParser(CSVFileName);
reader.TextFieldType = Microsoft.VisualBasic.FileIO.FieldType.Delimited;
reader.Delimiters = new string[] { "," };
while (!reader.EndOfData) {
try {
currentRow = reader.ReadFields();
dr = CSVTable.NewRow();
for (currColumn = 0; currColumn <= CSVTable.Columns.Count - 1; currColumn++) {
sqlColumnDataType = CSVTable.Columns(currColumn).DataType.Name;
switch (sqlColumnDataType) {
case "String":
if (string.IsNullOrEmpty(currentRow(currColumn))) {
dr.Item(currColumn) = "";
} else {
dr.Item(currColumn) = Convert.ToString(currentRow(currColumn));
}
break;
case "Decimal":
if (string.IsNullOrEmpty(currentRow(currColumn))) {
dr.Item(currColumn) = 0;
} else {
dr.Item(currColumn) = Convert.ToDecimal(currentRow(currColumn));
}
break;
case "DateTime":
if (string.IsNullOrEmpty(currentRow(currColumn))) {
dr.Item(currColumn) = "";
} else {
dr.Item(currColumn) = Convert.ToDateTime(currentRow(currColumn));
}
break;
}
}
CSVTable.Rows.Add(dr);
} catch (Microsoft.VisualBasic.FileIO.MalformedLineException ex) {
Interaction.MsgBox("Line " + ex.Message + "is not valid." + Constants.vbCrLf + "Terminating Read Operation.");
reader.Close();
reader.Dispose();
return false;
} finally {
dr = null;
}
}
reader.Close();
reader.Dispose();
return true;
}
}
//=======================================================
//Service provided by Telerik (www.telerik.com)
//Conversion powered by NRefactory.
//Twitter: #telerik
//Facebook: facebook.com/telerik
//=======================================================

How to View Crystal report in Visual Studio 2013?

I'm working on ASP.Net with C#, and installed CrystalReport 13 for Visual Studio 2013. I wrote code to fill a Datasource and pass it into my `CrystalReport file, but my website doesn't show anything. How can I execute my report?
Here is my PageLoad:
SqlConnection cnn = new SqlConnection(connectionstring);
cnn.Open();
SqlCommand command = new SqlCommand();
SqlDataAdapter adapter = new SqlDataAdapter();
DataSet ds = new DataSet();
command.Connection = cnn;
command.CommandType = CommandType.StoredProcedure;
command.CommandText = "STP_T00050030";
command.Parameters.Add("#F_CNTRowID", SqlDbType.Int).Value = Convert.ToInt32("20");
command.Parameters.Add("#F_CNTid", SqlDbType.Int).Value = Convert.ToInt32("45");
adapter = new SqlDataAdapter(command);
adapter.Fill(ds);
ReportDocument crystalReport = new ReportDocument();
crystalReport.Load(Server.MapPath("~/Report1.rpt"));
crystalReport.SetDataSource(ds);
CrystalReportViewer1.ReportSource = crystalReport;
In your solution, right mouse click on each report (.rpt file) and go properties --> Build Action=Content, Copy To Output Directory=Copy Always
Here's a complete block of code for setting data source. Notice how data source must also be set for each subreport.
public static CrystalReportSource Crystal_SetDataSource(string reportName, object par1, object par2, object par3)
{
CrystalReportSource CrystalReportSource2 = new CrystalReportSource();
CrystalReportSource2.CacheDuration = 10;
CrystalReportSource2.Report.FileName = #"~\App_Pages\Secure\Reports\" + reportName;
CrystalDecisions.CrystalReports.Engine.Database crDatabase = CrystalReportSource2.ReportDocument.Database;
ConnectionInfo crConnectionInfo = new ConnectionInfo();
crConnectionInfo.ServerName = server;
crConnectionInfo.DatabaseName = db;
crConnectionInfo.UserID = crystalUser;
crConnectionInfo.Password = pwd;
crConnectionInfo.IntegratedSecurity = false;
// First we assign the connection to all tables in the main report
TableLogOnInfo crTableLogOnInfo = new TableLogOnInfo();
foreach (CrystalDecisions.CrystalReports.Engine.Table crTable in crDatabase.Tables)
{
crTableLogOnInfo = crTable.LogOnInfo;
crTableLogOnInfo.ConnectionInfo = crConnectionInfo;
crTable.ApplyLogOnInfo(crTableLogOnInfo);
}
//SET DATASOURCE FOR EACH SUBREPORT IN REPORT
foreach (CrystalDecisions.CrystalReports.Engine.Section section in CrystalReportSource2.ReportDocument.ReportDefinition.Sections)
{
// In each section we need to loop through all the reporting objects
foreach (CrystalDecisions.CrystalReports.Engine.ReportObject reportObject in section.ReportObjects)
{
if (reportObject.Kind == ReportObjectKind.SubreportObject)
{
SubreportObject subReport = (SubreportObject)reportObject;
ReportDocument subDocument = subReport.OpenSubreport(subReport.SubreportName);
foreach (CrystalDecisions.CrystalReports.Engine.Table table in subDocument.Database.Tables)
{
// Cache the logon info block
TableLogOnInfo logOnInfo = table.LogOnInfo;
// Set the connection
logOnInfo.ConnectionInfo = crConnectionInfo;
// Apply the connection to the table!
table.ApplyLogOnInfo(logOnInfo);
}
}
}
}
if (CrystalReportSource2.ReportDocument.DataSourceConnections.Count > 0)
CrystalReportSource2.ReportDocument.DataSourceConnections[0].SetConnection(server, db, crystalUser, pwd);
CrystalReportSource2.ReportDocument.SetDatabaseLogon(crystalUser, pwd, server, db);
if (par1 != null)
CrystalReportSource2.ReportDocument.SetParameterValue(0, par1);
if (par2 != null)
CrystalReportSource2.ReportDocument.SetParameterValue(1, par2);
if (par3 != null)
CrystalReportSource2.ReportDocument.SetParameterValue(2, par3);
return CrystalReportSource2;
}

Slow data Selection from MDB file to C# Desktop application

Although everything is correct, but data selection process is very slow in my Application, while retriving data from access .mdb file. Is there any idea that data can be accessed fast. Is there any mechanism??
This below code Runs when Button Clicked .
public class GetData {
OleDbConnection con = new OleDbConnection(DatabseConnection.ConnectionStringAccessDatabase);
public string lblPolicyNumber, lblInsuredName, lblIssuedDatePolicy, lblStatusPolicy,
lblModalPremium, lblDueDate, lblNextDueDate, lblAgentCode,
lblMode, lblType1, lblAmount1, lblDate1, lblPremAmt1,
lblDueDate1, lbPaidDate1, lblPremAmt2, lblDueDate2,
lblPaidDate2, lblPremAmt3, lbDueDate3, lblPadiDate3,
lblOwnersName, lblOwnersCode, lblAddress1, lblAddress2,
lblPlan, lblCoverageAmt, lblSex, lblBirthDate, lblAge,
lblAutomaticPrmloan, lblAPLCount, lblLoanType, lblLoanPrincipleamt,
lblLoanDate, lblRatedNotRated, lblUnderWritingApproved , LateFee,
TotalAmountDue, AmountInDeposit, NetPayableAmount, Overdueprem,
CurrentPremiumDue, lblPMFlastUpdated = null;
public void getData(string policyNumber)
{
try
{
con.Open();
}
catch { MessageBox.Show("Please Download the File From the Server, Or Contact IT Department"); }
OleDbCommand cmd = con.CreateCommand();
cmd.CommandText = "(Select capolnum, cainame, iss_dte, castatus, mod_prm, due_dte1, nxt_due, agent_code, cabmode, casustyp1, casusamt1, casusdate1, chbldpm1, pd_dte1, chbldpm2, due_dte2, pd_dte2, chbldpm3, due_dte3, pd_dte3 , caoname, ocode, Addr1, addr2, plan, cbcovamt, cbsex, birth_dte, cbissage, apl, as400_cl_aplcnt, as400_cl_lntype, as400_cl_lnprinc, apl_date, cstype, approved FROM agy_pmf where capolnum ='" + policyNumber + "' )";
OleDbDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
SetData.lblPolicyNumber = lblPolicyNumber = dr.GetValue(0).ToString();
SetData.lblInsuredName = lblInsuredName = dr.GetValue(1).ToString();
lblIssuedDatePolicy = dr.GetValue(2).ToString();
lblStatusPolicy = dr.GetValue(3).ToString();
lblModalPremium = dr.GetValue(4).ToString();
lblDueDate = dr.GetValue(6).ToString();
lblNextDueDate = dr.GetValue(6).ToString();
lblAgentCode = dr.GetValue(7).ToString();
SetData.lblMode = lblMode = dr.GetValue(8).ToString();
lblType1 = dr.GetValue(9).ToString();
lblAmount1 = dr.GetValue(10).ToString();
lblDate1 = dr.GetValue(11).ToString();
lblPremAmt1 = dr.GetValue(12).ToString();
lblDueDate1 = dr.GetValue(5).ToString();
lbPaidDate1 = dr.GetValue(13).ToString();
lblPremAmt2 = dr.GetValue(14).ToString();
lblDueDate2 = dr.GetValue(15).ToString();
lblPaidDate2 = dr.GetValue(16).ToString();
lblPremAmt3 = dr.GetValue(17).ToString();
lbDueDate3 = dr.GetValue(18).ToString();
lblPadiDate3 = dr.GetValue(19).ToString();
lblOwnersName = dr.GetValue(20).ToString();
lblOwnersCode = dr.GetValue(21).ToString();
lblAddress1 = dr.GetValue(22).ToString();
lblAddress2 = dr.GetValue(23).ToString();
lblPlan = dr.GetValue(24).ToString();
lblCoverageAmt = dr.GetValue(25).ToString();
lblSex = dr.GetValue(26).ToString();
lblBirthDate = dr.GetValue(27).ToString();
lblAge = dr.GetValue(28).ToString();
lblAutomaticPrmloan = dr.GetValue(29).ToString();
lblAPLCount = dr.GetValue(30).ToString();
lblLoanType = dr.GetValue(31).ToString();
lblLoanPrincipleamt = dr.GetValue(32).ToString();
lblLoanDate = dr.GetValue(33).ToString();
lblRatedNotRated = dr.GetValue(34).ToString();
lblUnderWritingApproved = dr.GetValue(35).ToString();
con.Close();
}
}}

Categories

Resources