Convert date format on fly in asp.net c# - c#

i am uploading an excel file which has a date column having this format "dd-mm-yyyy". I am trying to convert it on fly into this format mm/dd/yyyy.
string[] dsplit = row[6].ToString().Split('-');
obj.ExpiryDate = string.Format("{0}/{1}/{2}", dsplit[1], dsplit[0], dsplit[2]).ToDate();
but it throws error, some hidden error.
Here is the whole code. I have tried a alot and nothing works expectedly
protected void SaveEmployeefrom_Click(object sender, EventArgs e)
{
uploadExcelfile();
}
public List<ClsEmployee> uploadExcelfile()
{
List<ClsEmployee> list = new List<ClsEmployee>();
DataTable tb = new DataTable();
try
{
if (employeeregistration.HasFile)
{
string name = DateTime.Now.ToString("hhmmss_ddmmyy");
name = name + employeeregistration.FileName;
employeeregistration.SaveAs(Server.MapPath("~/ExcelFiles/") + name);
string path = System.IO.Path.GetFullPath(Server.MapPath("~/ExcelFiles/") + name);
string connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=2\"";
if (Path.GetExtension(path) == ".xls")
{
excelconnection = new OleDbConnection(connString);
excelconnection.Open();
}
else if (Path.GetExtension(path) == ".xlsx")
{
excelconnection = new OleDbConnection(connString);
excelconnection.Open();
}
OleDbCommand cmd = new OleDbCommand("SELECT [Name],[ID],[Mobile No],[Phone],[Emirates],[Nationality],[ExpiryDate],[Address] FROM [sheet1$]", excelconnection);
OleDbDataAdapter oleda = new OleDbDataAdapter(cmd);
oleda.Fill(tb);
foreach (DataRow row in tb.Rows)
{
if (!string.IsNullOrEmpty(row[6].ToString()))
{
ClsEmployee obj = new ClsEmployee();
obj.ID = 0;
// obj.Employer_ID=row[0].ToInt32();
obj.EmployeeName = row[0].ToString();
obj.EmployeeUniqueID = row[1].ToString();
obj.MobileNumber = row[2].ToString();
obj.PhoneNumber = row[3].ToString();
obj.Emirates = row[4].ToString();
obj.Nationality = row[5].ToString();
//from excel its dd-mm-yyyy
string[] dsplit = row[6].ToString().Split('-');
obj.ExpiryDate = string.Format("{0}/{1}/{2}", dsplit[1], dsplit[0], dsplit[2]).ToDate();
// obj.ExpiryDate = row[6].ToDate(); //mm-dd-yyyy
obj.Address = row[7].ToString();
list.Add(obj);
}
}
excelconnection.Dispose();
if (File.Exists(path))
{
File.Delete(path);
}
int total = tb.Rows.Count;
if (total>0)
{
GV_Employee.DataSource = null;
GV_Employee.DataSource = list;
GV_Employee.DataBind();
GV_Employee.Visible = true;
ResultLabel.ResultLabelAttributes("Uploaded successfull !!!", ProjectUserControls.Enums.ResultLabel_Color.Yellow);
ResultPanel.Controls.Add(ResultLabel);
}
else
{
ResultLabel.ResultLabelAttributes("No Record In Excel Sheet !!!", ProjectUserControls.Enums.ResultLabel_Color.Red);
ResultPanel.Controls.Add(ResultLabel);
}
//txtSerialQuantity.Text = total.ToString();
////// trbtnCheckAll.Visible = true;
////div_automatic.Visible = true;
////lbl_totalSelected.Text = "Total Selected = " + total.ToString();
}
}
catch (Exception x)
{
x.ToString(); //ResultLabel.ResultLabelAttributes(x.Message, ProjectUserControls.Enums.ResultLabel_Color.Red);
ResultLabel.ResultLabelAttributes(x.Message, ProjectUserControls.Enums.ResultLabel_Color.Red);
ResultPanel.Controls.Add(ResultLabel);
}
return list;
}
protected void Button1_Click(object sender, EventArgs e)
{
ClsEmployee obj1 = new ClsEmployee();
List<ClsEmployee> list = new List<ClsEmployee>();
try
{
foreach (GridViewRow item in GV_Employee.Rows)
{
ClsEmployee obj = new ClsEmployee();
obj.ID = 0;
obj.Employer_ID = cmbEmployer.SelectedValue.ToInt32();// ((Literal)GV_Employee.Rows[1].FindControl("Ltrl_EmployerID")).Text.ToInt32();
obj.EmployeeName = ((Literal)item.FindControl("Ltrl_Name")).Text.ToString();
obj.EmployeeUniqueID = ((Literal)item.FindControl("Ltrl_EmployeeUniqueID")).Text.ToString();
obj.MobileNumber = ((Literal)item.FindControl("Ltrl_Mobile")).Text.ToString();
obj.PhoneNumber = ((Literal)item.FindControl("Ltrl_PhoneNo")).Text.ToString();
obj.Emirates_ID = ((Literal)GV_Employee.Rows[1].FindControl("Ltrl_Emirates")).Text.ToInt32();
obj.Nationality_ID = ((Literal)GV_Employee.Rows[1].FindControl("Ltrl_Nationality")).Text.ToInt32();
obj.ExpiryDate = ((Literal)item.FindControl("Ltrl_Expiry")).Text.ToDate();
obj.Address = ((Literal)item.FindControl("Ltrl_Address")).Text.ToString();
obj.LFMD = "";
obj.RFMD = "";
obj.PinCode = "";
obj.IsFingerAuth = false;
obj.IsActive = true;
list.Add(obj);
}
obj1.SaveEmployeefromExcelFile(list);
ResultLabel.ResultLabelAttributes("Save successfull !!!", ProjectUserControls.Enums.ResultLabel_Color.Yellow);
ResultPanel.Controls.Add(ResultLabel);
GV_Employee.DataSource = null;
GV_Employee.Visible = false;
}
catch (Exception ex)
{
ResultLabel.ResultLabelAttributes(ex.ToString(), ProjectUserControls.Enums.ResultLabel_Color.Red);
ResultPanel.Controls.Add(ResultLabel);
}
}

Try this code.
DateTime dt = DateTime.Parse(row[6].toString());
string date = dt.ToString("dd/MM/yyyy");

I assume row[6] is a DateTime when you get from excel, you just need;
row[6].ToString("MM/dd/yyyy", CultureInfo.InvariantCulture);
Convert a DateTime to string and splitting it a generally bad idea. mm specifier is for minutes, MM is for months by the way.

Try This..
String MyString = "12-30-2014"; // get value from text field
DateTime MyDateTime = new DateTime();
MyDateTime = DateTime.ParseExact(MyString, "MM-dd-yyyy",null);
String MyString_new = MyDateTime.ToString("dd-MM-yyyy");

Related

How to upload multiple Excel files in asp.net

This is the 1st table called excel2 for storing English characters
This is the 2nd table called excel3 for storing numbers
For the Excel file, there's two sheet in total, the first sheet store data of English characters and the second sheet store data of numbers.
User can choose to import multiple Excel files at the same time.
Now, when user select 3 excel file, the foreach loop is looping 3 times, but the data being inserted to the database only contain data from the 1st excel file repeatedly.
Any idea? Many thanks
public partial class multipleexcelimport : System.Web.UI.Page
{
protected void importfile()
{
String MyConString = "SERVER=localhost;" + "DATABASE=mysql_testing;" + "UID=root;" + "PASSWORD=tammy;SslMode=none";
if (this.uploadfile.HasFile)
{
string[] segments = fn.Split('.');
string fileExt = segments[segments.Length - 1];
if (fileExt != "xlsx")
{
showMessage("輸入錯誤", "請上傳正確檔案xlsx");
return;
}
foreach (var file in uploadfile.PostedFiles)
{
var fn = file.FileName;
string newfileName = DateTime.Now.ToString("yyyyMMddHHmmss") + "_" + fn;
string filepath = Server.MapPath(ConfigurationSettings.AppSettings["UPLOAD_FOLDER"]) + newfileName;
this.uploadfile.SaveAs(filepath);
ExcelPackage xlWorkbook = new ExcelPackage(new FileInfo(filepath));
ExcelWorksheet xlRange = xlWorkbook.Workbook.Worksheets[1];
int rowCount = xlRange.Dimension.End.Row;
ExcelWorksheet xlRange2 = xlWorkbook.Workbook.Worksheets[2];
int rowCount2 = xlRange2.Dimension.End.Row;
string sql = "";
string linkid = "";
MySqlConnection conn = null;
MySqlDataAdapter msda = null;
DataSet ds = null;
List<string> FailList = new List<string>();
conn = new MySqlConnection(MyConString);
DateTime dTime = DateTime.Now;
string now_time = dTime.ToString("yyyy-MM-dd HH:mm:ss");
conn.Open();
conn.Close();
using (TransactionScope scope = new TransactionScope())
{
try
{
conn.Open();
//sheet1
for (int i = 2; i <= rowCount; i++)
{
string dates = xlRange.Cells[i, 1].Value.ToString();
sql = "INSERT INTO mysql_testing.excel2 set"
+ " excel = ?dates;"
ds = new DataSet();
msda = new MySqlDataAdapter(sql, conn);
msda.SelectCommand.Parameters.AddWithValue("dates", dates);
}
//sheet2
for (int i = 2; i <= rowCount2; i++)
{
string excel3 = xlRange2.Cells[i, 1].Value.ToString();
sql = "INSERT INTO mysql_testing.excel3 set"
+ " excel3 = ?excel3;" ;
ds = new DataSet();
msda = new MySqlDataAdapter(sql, conn);
msda.SelectCommand.Parameters.AddWithValue("excel3", excel3);
}
showMessage("alert", "success");
scope.Complete();
}
catch (Exception ex)
{
throw ex;
}
finally
{
conn.Close();
}
}
ScriptManager.RegisterStartupScript(this, this.GetType(), "tab", "$('.nav-tabs a[href=\"#massimport\"]').tab('show')", true);
}
}
else
{
showMessage("error", "select file plz");
ScriptManager.RegisterStartupScript(this, this.GetType(), "tab", "$('.nav-tabs a[href=\"#massimport\"]').tab('show')", true);
}
}
public void showMessage(string title, string content)
{
ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('" + content + "');", true);
}
protected void Button1_Click(object sender, EventArgs e)
{
importfile();
}
}

How do I create a dataset in C# with local database

I am a beginner in C# and created a database in a Windows Forms App for a customer data, the function of it is to take the user's phone number and then search the table and then if it is found then populate the data fields with the information; otherwise it needs to add the new customer to the table.
When I run the code I get an error
System.ArgumentException: 'Keyword not supported: 'data source(localdb)\mssqlocaldb;attachdbfilename'.'
This is my code:
DataTable TableCust;
SqlConnection cnCust;
SqlDataAdapter dataCust;
DataGrid dtGridCust;
public bool buttonClicked = false;
private static int CurrentOrder = 1000;
private int i = 0;
Validation v = new Validation();
public frmPizzaPetes()
{
InitializeComponent();
}
string dataSource;
string SqlParms;
private void Form1_Load(object sender, EventArgs e)
{
btnAccept.Enabled = false;
lblOrderNo.Text = CurrentOrder.ToString();
Price();
//
dataSource = #"Data Source(LocalDB)\MSSQLocalDB;AttachDbFilename=|C:\Users\tyada\DATABASE\Pizza.mdf;";
SqlParms = "Integrated Securtiy=True; Connect Timeout==30";
string SqlCust = "select * from Customers";
string strConn = dataSource + SqlParms;
cnCust = new SqlConnection(strConn);
cnCust.Open();
TableCust = new DataTable();
dtGridCust.DataSource = TableCust;
}
public bool ifCustIsFound()
{
bool tester=false;
string SqlCustomer = "SELECT*FROM Customers WHERE CustPhone= '" + mtbPhone.Text + "';";
dataCust = new SqlDataAdapter(SqlCustomer, cnCust);
dataCust.Fill(TableCust);
if (TableCust.Rows.Count > 0)
{
txtName.Text = TableCust.Rows[0]["CustName"].ToString();
txtAddress.Text = TableCust.Rows[0]["CustAddress"].ToString();
txtApt.Text = TableCust.Rows[0]["CustSuite"].ToString();
txtCity.Text = TableCust.Rows[0]["CustCity"].ToString();
mtbZip.Text = TableCust.Rows[0]["CustZip"].ToString();
cboState.Text = TableCust.Rows[0]["CustState"].ToString();
// dtGridCust.DataSource = TableCust;
}
else
{
DialogResult dlg=MessageBox.Show("Add Customer?","Customer not found", MessageBoxButtons.YesNo);
if (dlg == DialogResult.Yes)
{
string strConn = dataSource + SqlParms;
SqlDataAdapter adaptSQL = new SqlDataAdapter(strSQL, strConn);
SqlCommand cmdCust = new SqlCommand();
SqlCommandBuilder cmdBld = new SqlCommandBuilder(adaptSQL);
DataRow newCust;
newCust = TableCust.NewRow();
newCust["CustPhone"] = mtbPhone.Text;
newCust["CustName"] = txtName.Text;
newCust["CustAddress1"] = txtAddress.Text;
newCust["CustAddress2"] = txtApt.Text;
newCust["CustCity"] = txtCity.Text;
newCust["CustState"] = cboState.Text;
newCust["CustZip"] = mtbZip.Text;
try
{
TableCust.Rows.Add(newCust);
cmdBld.GetUpdateCommand();
adaptSQL.Update(TableCust);
MessageBox.Show("Customer Added!");
}
catch (SqlException)
{
MessageBox.Show("Customer Add Failed!");
}
}
txtName.Focus();
}
return tester;
}
it seems "=" is missing in data source. Try this.
private void Form1_Load(object sender, EventArgs e)
{
btnAccept.Enabled = false;
lblOrderNo.Text = CurrentOrder.ToString();
Price();
//
dataSource = #"Data Source =(LocalDB)\MSSQLocalDB;AttachDbFilename=|C:\Users\tyada\DATABASE\Pizza.mdf;";
SqlParms = "Integrated Securtiy=True; Connect Timeout==30";
string SqlCust = "select * from Customers";
string strConn = dataSource + SqlParms;
cnCust = new SqlConnection(strConn);
cnCust.Open();
TableCust = new DataTable();
dtGridCust.DataSource = TableCust;
}

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
//=======================================================

"An INSER INTO query cannot contain a multi-valued Field" OleDBException

I get the following Error when i try to insert Data in one of my tables "An INSERT INTO query cannot contain a multi-valued Field", The other tables are working fine.
I am using an Access 2010 DB, Field Types are Text, Date, Number, Autonumber, Currency.
Do I miss something ?
public void CreateNewSystemWithDefaultValues(String IP)
{
String[] Convert = NetworkInformation.GETDNSFfromIP(IP).Split('.');
DataTable Data = SystemsAccessDB.GETAllDataFromDBWithOption("Systems", "Where 1 = 2");
DataRow DataR;
DataR = Data.NewRow();
DataR["SystemName"] = Convert[0];
DataR["SystemSerialNumber"] = #"n/a";
DataR["SystemCreationDate"] = System.DateTime.Now.Date;
DataR["SystemIPAdress"] = IP;
DataR["SystemDRACAdress"] = #"n/a";
DataR["SystemState"] = "Unknown";
DataR["SystemNIC"] = #"n/a";
DataR["SystemHDDController"] = #"n/a";
DataR["SystemServiceTag"] = #"n/a";
DataR["SystemWikiURL"] = #"https://wikiurl";
DataR["SystemInstallationMedia"] = #"\\Networkpath\";
DataR["SystemMonitoring"] = #"n/a";
DataR["SystemTypeID"] = 6;
DataR["SystemsCPUID"] = 6;
DataR["SystemsMemoryID"] = 6;
DataR["SystemsDowntimeID"] = 9;
DataR["SystemOSID"] = 9;
DataR["SystemLocationID"] = 6;
DataR["SystemContactDataIDHardware"] = 1;
Data.Rows.Add(DataR);
SystemsAccessDB.ADDDataToDB("Systems", Data);
}
public static void ADDDataToDB(String Table, DataTable Data)
{
using (OleDbConnection DBConnection = new OleDbConnection(GetConnectionString()))
{
OleDbDataAdapter DataAdapter = new OleDbDataAdapter();
DataAdapter.SelectCommand = new OleDbCommand("SELECT * FROM "+Table+"", DBConnection);
OleDbCommandBuilder CommandBuilder = new OleDbCommandBuilder(DataAdapter);
CommandBuilder.GetInsertCommand();
try
{
DBConnection.Open();
DataAdapter.Update(Data);
}
catch (OleDbException e)
{
MessageBox.Show(e.Message);
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
}
}

Yahoo stock download Exception thown SQLITE ERROR

I am trying to download quotes from Yahoo finance but it did work in the past few months and since a week I've faced an error that I can't handle:
I first enter the ticker (GOOG for example), then the start date and the end date :
But once everything is properly filled and I try to debug I face an exception :
Here is my code :
private void button2_Click(object sender, EventArgs e)
{
Cursor.Current = Cursors.WaitCursor;
button2.Enabled = false;
symbol = cbSymbol.Text;
startDate = dtpStartDate.Value;
endDate = dtpEndDate.Value;
YahooStocks.Downloader dl = new Downloader();
DataTable dt = dl.UpdateSymbol(symbol, startDate, endDate);
dl.InsertOrUpdateIssue(dt, symbol);
dataGridView1.DataSource = dt;
SetControlProperty(label4, "Text", "GOT : " + symbol + " ");
try
{
this.DoChart(symbol, startDate, endDate);
refreshGraph();
tabControl1.Enabled = true;
}
catch (Exception ex)
{
label4.Text = ex.Message;
}
button2.Enabled = true;
Cursor.Current = Cursors.Default;
}
public DataTable UpdateSymbol(string symbol, DateTime? startDate, DateTime? endDate)
{
if (!endDate.HasValue) endDate = DateTime.Now;
if (!startDate.HasValue) startDate = DateTime.Now.AddYears(-5);
if (symbol == null || symbol.Length < 1)
throw new ArgumentException("Symbol invalid: " + symbol);
// NOTE: Yahoo's scheme uses a month number 1 less than actual e.g. Jan. ="0"
int strtMo = startDate.Value.Month - 1;
string startMonth = strtMo.ToString();
string startDay = startDate.Value.Day.ToString();
string startYear = startDate.Value.Year.ToString();
int endMo = endDate.Value.Month - 1;
string endMonth = endMo.ToString();
string endDay = endDate.Value.Day.ToString();
string endYear = endDate.Value.Year.ToString();
urlTemplate = urlTemplate.Replace("[symbol]", symbol);
urlTemplate = urlTemplate.Replace("[startMonth]", startMonth);
urlTemplate = urlTemplate.Replace("[startDay]", startDay);
urlTemplate = urlTemplate.Replace("[startYear]", startYear);
urlTemplate = urlTemplate.Replace("[endMonth]", endMonth);
urlTemplate = urlTemplate.Replace("[endDay]", endDay);
urlTemplate = urlTemplate.Replace("[endYear]", endYear);
string history = String.Empty;
WebClient wc = new WebClient();
try
{
history = wc.DownloadString(urlTemplate);
}
catch (WebException wex)
{
// throw wex;
}
finally
{
wc.Dispose();
}
DataTable dt = new DataTable();
// trim off unused characters from end of line
history = history.Replace("\r", "");
// split to array on end of line
string[] rows = history.Split('\n');
// split to colums
string[] colNames = rows[0].Split(',');
// add the columns to the DataTable
foreach (string colName in colNames)
dt.Columns.Add(colName);
DataRow row = null;
string[] rowValues;
object[] rowItems;
// split the rows
for (int i = rows.Length - 1; i > 0; i--)
{
rowValues = rows[i].Split(',');
row = dt.NewRow();
rowItems = ConvertStringArrayToObjectArray(rowValues);
if (rowItems[0] != null && (string)rowItems[0] != "")
{
row.ItemArray = rowItems;
dt.Rows.Add(row);
}
}
return dt;
}
public static int ExecuteNonQuery(string connectionString, string commandText, object[] paramList)
{
SQLiteConnection cn = new SQLiteConnection(connectionString);
SQLiteCommand cmd = cn.CreateCommand();
cmd.CommandText = commandText;
cmd = DeriveParameters(cmd, paramList);
if (cn.State == ConnectionState.Closed)
cn.Open();
int result = cmd.ExecuteNonQuery();
cmd.Dispose();
cn.Close();
return result;
}

Categories

Resources