c# multiple chart error - c#

I want to create a column chart in c#.
this is the code that i uset for that:
private void Vizualizare_profil()
{
myConn = new MySqlConnection(myConnection);
MySqlCommand selectCommand = new MySqlCommand("SELECT * FROM `gomoku`.`informatii` WHERE `id_utilizator` = '" + id_client.ToString() + "';", myConn);
MySqlDataAdapter dataAdap = new MySqlDataAdapter(selectCommand);
DataSet ds = new DataSet();
myConn.Open();
dataAdap.Fill(ds);
myConn.Close();
DataTable dt = new DataTable();
dt.Columns.Add("Nume");
dt.Columns.Add("Meciuri castigate");
dt.Columns.Add("Meciuri pierdute");
dt.Columns.Add("Meciuri remize");
if (ds.Tables[0].Rows.Count != 0)
{
label28.Text = Username;
label29.Text = ds.Tables[0].Rows[0]["nume"].ToString();
label30.Text = ds.Tables[0].Rows[0]["prenume"].ToString();
label31.Text = ds.Tables[0].Rows[0]["varsta"].ToString();
label32.Text = ds.Tables[0].Rows[0]["adresa_email"].ToString();
dt.Rows.Clear();
dt.Rows.Add("Meciuri castigate " + Convert.ToString(ds.Tables[0].Rows[0]["meciuri_castigate"]), ds.Tables[0].Rows[0]["meciuri_castigate"], 0 , 0);
dt.Rows.Add("Meciuri pierdute " + Convert.ToString(ds.Tables[0].Rows[0]["meciuri_pierdute"]), 0, ds.Tables[0].Rows[0]["meciuri_pierdute"], 0);
dt.Rows.Add("Meciuri remize " + Convert.ToString(ds.Tables[0].Rows[0]["meciuri_remiza"]), 0, 0,ds.Tables[0].Rows[0]["meciuri_remiza"]);
chart1.DataSource = dt;
chart1.Series[0].XValueMember = "Nume";
chart1.Series[0].YValueMembers = "Meciuri castigate";
chart1.Series[1].XValueMember = "Nume";
chart1.Series[1].YValueMembers = "Meciuri pierdute";
chart1.Series[2].XValueMember = "Nume";
chart1.Series[2].YValueMembers = "Meciuri remize";
}
else
MessageBox.Show("Database error!");
}
It creates perfect the first chart but if this method is called again it shows the same data.
What is the problem and what can by done?

Related

C# - Trying to check if value exists in Access Database

I am creating a program that I will allow you to enter in a number and it will display the information in the respective row. However, if the number is not found in the num field, I want it to return with showing the text I set for a label (label12). However, I am getting returned with exception errors and I cannot figure out how to create this where if the num doesn't exist it will perform a set action.
olcn = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\TestUser\Documents\testlist.mdb");
OleDbDataAdapter oda = new OleDbDataAdapter("select * from testlist where num = '"+textBox11.Text+"'", olcn);
DataTable dt = new DataTable();
oda.Fill(dt);
if (oda.Fill(dt).Equals(null))
{
label12.Show();
}
else if (!oda.Fill(dt).Equals(textBox11.Text))
{
textBox1.Text = dt.Rows[0][1].ToString();
textBox2.Text = dt.Rows[0][2].ToString();
textBox3.Text = dt.Rows[0][3].ToString();
textBox4.Text = dt.Rows[0][4].ToString();
textBox5.Text = dt.Rows[0][5].ToString();
textBox6.Text = dt.Rows[0][6].ToString();
textBox7.Text = dt.Rows[0][7].ToString();
textBox8.Text = dt.Rows[0][8].ToString();
textBox9.Text = dt.Rows[0][9].ToString();
textBox10.Text = dt.Rows[0][10].ToString();
bool v = String.IsNullOrEmpty(dt.Rows[0][11].ToString());
if (!v)
{
pictureBox1.Load(dt.Rows[0][11].ToString());
}
else
{
pictureBox1.Load(dt.Rows[0][12].ToString());
}
}
The result of the Fill() method is the number of rows returned. Just update your code to check the result of Fill() is greater than zero records.
olcn = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\TestUser\Documents\testlist.mdb");
OleDbDataAdapter oda = new OleDbDataAdapter("select * from testlist where num = '"+textBox11.Text+"'", olcn);
DataTable dt = new DataTable();
int count = oda.Fill(dt);
if (count == 0)
{
label12.Show();
}
else
{
// ... your mapping logic
}
MS Documentation, OleDbDataAdapter.Fill Method

Code execution is not going down

I have a code below and it has strange behavior,Line of code after closing of While Loop is not executing. If i write those lines before While loop they got executed. I have searched a lot on this issue but failed.
if ((Convert.ToInt32(newDt.Rows[i]["qty"])) > (Convert.ToInt32(newDt1.Rows[i]["qty"])))
{
k_batch = Convert.ToInt32(newDt.Rows[i]["batch_num"]);
label20.Content = k_batch.ToString();
var dqty = (from row in Addition_result.AsEnumerable() //retriving value from DataTable
where row.Field<int>("batch_num") == k_batch
select row.Field<int>("qty")).FirstOrDefault();
dqty_y = Convert.ToInt32(dqty);
label16.Content = dqty_y.ToString();
con.Open();
SqlCommand cmd1 = new SqlCommand("SELECT quantity,sold_qty,left_qty FROM batch WHERE id='" + k_batch + "'", con);
SqlDataReader batch_qty_details = null;
batch_qty_details = cmd1.ExecuteReader();
while (batch_qty_details.Read())
{
label16.Content = dqty_y.ToString();
batch_qty = Convert.ToInt32(batch_qty_details["quantity"]);
batch_left = Convert.ToInt32(batch_qty_details["left_qty"]);
batch_sold = Convert.ToInt32(batch_qty_details["sold_qty"]);
} //code after this is not executing
label18.Content = batch_left.ToString();
label19.Content = batch_sold.ToString();
label21.Content = dqty_y.ToString();
label22.Content = batch_qty.ToString();
label16.Content = batch_sold + dqty_y;
label17.Content = batch_left - dqty_y;
if (((batch_sold + dqty_y) <= batch_qty) && ((batch_left - dqty_y) >= 0))
{
SqlCommand command = new SqlCommand("update batch set sold_qty=sold_qty+#soldqty2, left_qty=left_qty-#soldqty2 where id=#id2", con);
command.Parameters.AddWithValue("#soldqty2", Convert.ToInt32(dqty_y));
command.Parameters.AddWithValue("#id2", Convert.ToInt32(k_batch));
rexe = command.ExecuteNonQuery();
}
else
{
MessageBox.Show("Please Check you Ordered Quantity !");
}
con.Close();
}
}
Actually there was issue that connection state was already Open and i was trying to open it again. So then i used try-catch block it told me that connection is already open. Now i have changed my code and here it is.
if ((Convert.ToInt32(newDt.Rows[i]["qty"])) > (Convert.ToInt32(newDt1.Rows[i]["qty"])))
{
k_batch = Convert.ToInt32(newDt.Rows[i]["batch_num"]);
label20.Content = k_batch.ToString();
var dqty = (from row in Addition_result.AsEnumerable() //retriving value from DataTable
where row.Field<int>("batch_num") == k_batch
select row.Field<int>("qty")).FirstOrDefault();
dqty_y = Convert.ToInt32(dqty);
label16.Content = dqty_y.ToString();
try
{
//con.Open();
SqlCommand cmd1 = new SqlCommand("SELECT quantity,sold_qty,left_qty FROM batch WHERE id='" + k_batch + "'", con);
SqlDataReader batch_qty_details = null;
batch_qty_details = cmd1.ExecuteReader();
while (batch_qty_details.Read())
{
label16.Content = dqty_y.ToString();
batch_qty = Convert.ToInt32(batch_qty_details["quantity"]);
batch_left = Convert.ToInt32(batch_qty_details["left_qty"]);
batch_sold = Convert.ToInt32(batch_qty_details["sold_qty"]);
}
con.Close();
}
catch(Exception EX)
{
MessageBox.Show(EX.ToString());
}
label18.Content = batch_left.ToString();
label19.Content = batch_sold.ToString();
label21.Content = dqty_y.ToString();
label22.Content = batch_qty.ToString();
label16.Content = batch_sold + dqty_y;
label17.Content = batch_left - dqty_y;
if (((batch_sold + dqty_y) <= batch_qty) && ((batch_left - dqty_y) >= 0))
{
con.Open();
SqlCommand command = new SqlCommand("update batch set sold_qty=sold_qty+#soldqty2, left_qty=left_qty-#soldqty2 where id=#id2", con);
command.Parameters.AddWithValue("#soldqty2", Convert.ToInt32(dqty_y));
command.Parameters.AddWithValue("#id2", Convert.ToInt32(k_batch));
rexe = command.ExecuteNonQuery();
}
else
{
check_qty = -1;
}
}

Search for all days of a week using dateTimePicker

I want to retrieve all days of a week, selecting any day of that given week.
Example: Wanna retrieve 31/07/2016 (dd/MM/yyyy) to 06/08/2016 (dd/MM/yyyy)
Ocurrences by selecting any day of the presented week.
Is it possible?
My current code:
private void AutoLoadCalendar()
{
string constringF = #"Data Source=|DataDirectory|\cadastramentodb.sdf;Persist Security Info=False";
string QueryF = "select * from Funcionarios where (status = N'Ativo') and datepart(year, datafimcontrato) = #ano and datepart(month, datafimcontrato) = #mes ";
SqlCeConnection conDataBaseF = new SqlCeConnection(constringF);
SqlCeCommand cmdDataBaseF = new SqlCeCommand(QueryF, conDataBaseF);
cmdDataBaseF.Parameters.Add("#mes", SqlDbType.Int).Value = Convert.ToInt32(monthCalendar1.SelectionStart.Month);
cmdDataBaseF.Parameters.Add("#ano", SqlDbType.Int).Value = Convert.ToInt32(monthCalendar1.SelectionStart.Year);
try
{
SqlCeDataAdapter sda = new SqlCeDataAdapter();
sda.SelectCommand = cmdDataBaseF;
System.Data.DataTable dbdatasetF = new System.Data.DataTable();
sda.Fill(dbdatasetF);
BindingSource bSourceF = new BindingSource();
bSourceF.DataSource = dbdatasetF;
dataGridView1.DataSource = bSourceF;
sda.Update(dbdatasetF);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Best regards
You can use the DATEPART function to know witch day of the week has your selected date and knowing that number is easy to solve your problem n___n
Try with this:
private void AutoLoadCalendar()
{
string constringF = #"Data Source=|DataDirectory|\cadastramentodb.sdf;Persist Security Info=False";
string QueryF =
"DECLARE #DiaSemana AS INT " +
"SET #DiaSemana=DATEPART(DW,#Fecha) " +
" " +
"SELECT * " +
"FROM Funcionarios " +
"WHERE [status] = N'Ativo' AND datafimcontrato >= DATEADD(DD,#DiaSemana*-1,#Fecha) AND datafimcontrato <= DATEADD(DD,7-#DiaSemana,#Fecha) ";
SqlCeConnection conDataBaseF = new SqlCeConnection(constringF);
SqlCeCommand cmdDataBaseF = new SqlCeCommand(QueryF, conDataBaseF);
cmdDataBaseF.Parameters.Add("#Fecha", monthCalendar1.Value);
try
{
SqlCeDataAdapter sda = new SqlCeDataAdapter();
sda.SelectCommand = cmdDataBaseF;
System.Data.DataTable dbdatasetF = new System.Data.DataTable();
sda.Fill(dbdatasetF);
BindingSource bSourceF = new BindingSource();
bSourceF.DataSource = dbdatasetF;
dataGridView1.DataSource = bSourceF;
sda.Update(dbdatasetF);
}
catch (Exception ex)
{
MessageBox.Show(ex.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
//=======================================================

Loss of Data after printing my crystal report via PrintToPrinter

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 .... :)

Categories

Resources