I'm using the following code to load my CSV file into a DataTable object. The problem is that the first line from the CSV file is loaded into the DataTable as the header row and not as a data row. How can I make all lines from the CSV file load as data rows and make datatable header row empty or any thing. This is my code
private DataTable ConvertCSVtoDataTable()
{
DataTable dataTable = new DataTable();
using (StreamReader sr = new StreamReader(csvfilename))
{
string[] headers = sr.ReadLine().Split(',');
foreach (string header in headers)
{
dataTable.Columns.Add(header);
}
while (!sr.EndOfStream)
{
string[] rows = sr.ReadLine().Split(',');
DataRow dr = dataTable.NewRow();
for (int i = 0; i < headers.Length; i++)
{
dr[i] = rows[i];
}
dataTable.Rows.Add(dr);
}
}
return dataTable;
}
The problem is that you use the first ReadLine statement to add the Header objects. You only use the second ReadLine to populate rows in the DataTable. Try this:
private DataTable ConvertCSVtoDataTable()
{
bool firstRow = true;
DataTable dataTable = new DataTable();
using (StreamReader sr = new StreamReader(csvfilename))
{
while (!sr.EndOfStream)
{
string[] values = sr.ReadLine().Split(',');
if (firstRow)
{
firstRow = false;
for (int i = 0;i < values.Length; i++)
{
dataTable.Columns.Add("Column" + i);
}
}
DataRow dr = dataTable.NewRow();
for (int i = 0; i < values.Length; i++)
{
dr[i] = values[i];
}
dataTable.Rows.Add(dr);
}
}
return dataTable;
}
EDITED:
Sorry about that I forgot to add the column headers... This should "workish". Unfortunately I dont have a C# debugger in front of me to get the syntax exact, but I believe you can figure out what I am trying to do.
You are explicitly reading the "Header". If I am understanding you correctly you simply need to remove the header management. This will leave you with columns with no header though or a null header.
private DataTable ConvertCSVtoDataTable()
{
DataTable dataTable = new DataTable();
using (StreamReader sr = new StreamReader(csvfilename))
{
while (!sr.EndOfStream)
{
string[] rows = sr.ReadLine().Split(',');
DataRow dr = dataTable.NewRow();
for (int i = 0; i < rows.Length; i++)
{
dr[i] = rows[i];
}
//IF the dataTable column count is less than the row column count add some columns.
if (dataTable.Columns.size() < dr.Columns.size()){
for(int i = 0; i < dr.Columns.size(); i++){
dataTable.Columns.add("");
}
}
dataTable.Rows.Add(dr);
}
}
return dataTable;
}
Related
i am trying to read an xml file and a txt file using one button click i currently have this code in my button, i don't know what it is that i'm doing wrong any help or advice of sort would be great.
try
{
XmlReader file;
file = XmlReader.Create("c:/CSAIO4D/BK01/CH01/ReadFiles/ReadFiles/XMLFile1.xml", new XmlReaderSettings());
DataSet ds = new DataSet();
ds.ReadXml(file);
dataGridView1.DataSource = ds.Tables[0];
StreamReader files = new StreamReader("c:/CSAIO4D/BK01/CH01/ReadFiles/ReadFiles/People.txt");
string[] columnnames = files.ReadLine().Split(',');
DataTable dt = new DataTable();
foreach (string c in columnnames)
{
dt.Columns.Add(c);
}
string newline;
while ((newline = files.ReadLine()) != null)
{
DataRow dr = dt.NewRow();
string[] values = newline.Split(',');
for (int i = 0; i < values.Length; i++)
{
dr[i] = values[i];
}
dt.Rows.Add(dr);
}
file.Close();
dataGridView1.DataSource = dt;
dataGridView1.Visible = true;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
can someone please help me out, i am new to web forms, the issue that i am having is that it only reads the text file and return it to the DataGridView and does not read the xml
Here is How to read XML File
XmlDocument doc = new XmlDocument();
doc.Load("c:\\temp.xml");
Here is how to read XML in the dataset
// Here your xml file
string xmlFile = "Data.xml";
DataSet dataSet = new DataSet();
dataSet.ReadXml(xmlFile, XmlReadMode.InferSchema);
// Then display informations to test
foreach (DataTable table in dataSet.Tables)
{
Console.WriteLine(table);
for (int i = 0; i < table.Columns.Count; ++i)
Console.Write("\t" + table.Columns[i].ColumnName.Substring(0, Math.Min(6, table.Columns[i].ColumnName.Length)));
Console.WriteLine();
foreach (var row in table.AsEnumerable())
{
for (int i = 0; i < table.Columns.Count; ++i)
{
Console.Write("\t" + row[i]);
}
Console.WriteLine();
}
}
And here is
how you can read a text file
string[] lines = System.IO.File.ReadAllLines(#"C:\Users\Public\TestFolder\WriteLines2.txt");
// Display the file contents by using a foreach loop.
System.Console.WriteLine("Contents of WriteLines2.txt = ");
I am trying to import text file into sql server database and the import is working fine but the problem is that all the columns in the text file is being inserted into one column.
I need the columns from the text file to map the columns in the sql table.
here is my code
Console.WriteLine(s);
string fileName = s.ToString();
string fullPath = path + fileName.ToString();
DataTable dt = new DataTable();
dt.Columns.AddRange(new DataColumn[3] { new DataColumn("Environment", typeof(string)),
new DataColumn("Job_Name", typeof(string)),
new DataColumn("Occurs",typeof(string)) });
string csvData = File.ReadAllText(fullPath);
foreach (string row in csvData.Split('\n'))
{
if (!string.IsNullOrEmpty(row))
{
dt.Rows.Add();
int i = 0;
foreach (string cell in row.Split(','))
{
dt.Rows[dt.Rows.Count - 1][i] = cell;
i++;
}
}
}
string consString = ConfigurationManager.ConnectionStrings["myConn"].ConnectionString;
using (SqlConnection con = new SqlConnection(consString))
{
using (SqlBulkCopy sqlBulkCopy = new SqlBulkCopy(con))
{
//Set the database table name
sqlBulkCopy.DestinationTableName = "[dbo].[test2]";
con.Open();
sqlBulkCopy.WriteToServer(dt);
con.Close();
}
}
You are splitting your rows on comma when your data is tab separated. Instead do this:
row.Split('\t')
Also, don't split your entire file on \n, use File.ReadAllLines, for example:
foreach (string row in File.ReadAllLines(fullPath))
{
if (!string.IsNullOrEmpty(row))
{
dt.Rows.Add();
int i = 0;
foreach (string cell in row.Split('\t'))
{
dt.Rows[dt.Rows.Count - 1][i] = cell;
i++;
}
}
}
Below c# function import comma delimited file into C# dataTable. After getting data into dataTable you can apply your desired methods(Bulk Insert / Row by row) to take in DB :
public static DataTable ImportDataFromCSVFile(string filePath)
{
DataTable dataTable = new DataTable();
try
{
using (StreamReader readFile = new StreamReader(filePath))
{
string line;
StringBuilder sb = new StringBuilder();
string[] row;
int counter = 0;
int length = 0;
while ((line = readFile.ReadLine()) != null)
{
row = line.Split(',');
if (counter == 0)
{
length = row.Length;
DataRow dr1 = dataTable.NewRow();
for (int i = 0; i < length; i++)
{
try
{
//dataTable.Columns.Add("Col_" + i.ToString());
dataTable.Columns.Add(Convert.ToString(row[i]));
}
catch (Exception ex)
{
}
}
// dataTable.Rows.Add(dr1);
}
else
{
if (row.Length == dataTable.Columns.Count)
{
DataRow dr = dataTable.NewRow();
for (int i = 0; i < length; i++)
{
if (row[i].ToString().Contains('"'))
{
row[i] = row[i].Replace('"', ' ');
}
dr[i] = Convert.ToString(row[i]);
}
dataTable.Rows.Add(dr);
}
else
{
}
}
counter++;
}
}
}
catch (Exception ex)
{
}
return dataTable;
}
I am trying to create some XML files so that in a disconnected architecture the data can be viewed directly from the XML files.
Currently, I have some data pulled in datagridview.
However, when I attempt to save this data in an XML file, the resulting file contains "" only. Nothing else, all blank.
Please suggest how can I proceed with it.
private void btnSXAAMclientinfo_Click(object sender, EventArgs e)
{
string varGUID;
varGUID = txtClientGUID.Text;
clsBusinessLogic objBL = new clsBusinessLogic();
DataSet datasetAM = objBL.LoadSXAAMClientInfo(varGUID);
dgvPatientData.DataSource = datasetAM.Tables[0].DefaultView;
DataTable dt = new DataTable();
for (int i = 1; i < dgvPatientData.Columns.Count + 1; i++)
{
DataColumn column = new DataColumn(dgvPatientData.Columns[i - 1].HeaderText);
dt.Columns.Add(column);
}
int ColumnCount = dgvPatientData.Columns.Count;
foreach (DataGridViewRow dr in dgvPatientData.Rows)
{
DataRow dataRow = dt.NewRow();
for (int i = 0; i < ColumnCount; i++)
{
dataRow[i] = dr.Cells[i];
}
}
DataSet ds = new DataSet();
ds.Tables.Add(dt);
XmlTextWriter newXml = new XmlTextWriter(#"c:/FK.xml"); ` System.Text.Encoding.UTF8);
ds.WriteXml(newXml);
}
I think you forgot to add the newly created row to the table:
foreach (DataGridViewRow dr in dgvPatientData.Rows)
{
DataRow dataRow = dt.NewRow();
for (int i = 0; i < ColumnCount; i++)
{
dataRow[i] = dr.Cells[i];
}
dt.Rows.Add(dataRow); //<--
}
Read this link for further details.
Am trying to write from the datagridview with a goal of saving the input to the xml file, but am not getting it correctly. My code:
XDocument doc = XDocument.Load(outputFilePath);
doc.Save(outputFilePath);
oDataSet = new DataSet();
foreach (DataGridViewRow _rows in Gridview_Output.Rows)
{
DataRow oDatarow = oDataTable.NewRow();
for (int i = 0; i < Gridview_Output.ColumnCount; i++)
{
oDataTable.Rows.Add(oDatarow.ItemArray);
}
}
oDataSet.Tables.Add(oDataTable);
oDataSet.WriteXml(outputFilePath);
doc.Save(outputFilePath);
I want to write to this empty tags:
<data name="Exit_Button" xml:space="preserve">
<value></value>
<comment>[Font][/Font][DateStamp][/DateStamp][Comment][/Comment]</comment>
</data>
Hmm try this to create a datatable from gridview:
private DataTable GetDataTableFromDGV(DataGridView dgv) {
var dt = new DataTable();
foreach (DataGridViewColumn column in dgv.Columns) {
if (column.Visible) {
// You could potentially name the column based on the DGV column name (beware of dupes)
// or assign a type based on the data type of the data bound to this DGV column.
dt.Columns.Add();
}
}
object[] cellValues = new object[dgv.Columns.Count];
foreach (DataGridViewRow row in dgv.Rows) {
for (int i = 0; i < row.Cells.Count; i++) {
cellValues[i] = row.Cells[i].Value;
}
dt.Rows.Add(cellValues);
}
return dt;
}
Then you can do:
DataTable dT = GetDataTableFromDGV(DataGridView1);
DataSet dS = new DataSet();
dS.Tables.Add(dT);
dS.WriteXml(File.OpenWrite("xml.xml"));
Scenario: App contains DataGridViews, I am populating the DataGridViews from a Database.
All the data in the Database is encrypted so after I fill my DataTable I need to cycle
through every entry in the DataTable through the decryption methods and place back
in the same spot in the DataTable. How would I do such a task?
Or is there a way I can decrypt the data as it is entering the dataTable?
SQLiteDataAdapter dataAdapter = new SQLiteDataAdapter(query, conn);
SQLiteCommandBuilder commandBuilder = new SQLiteCommandBuilder(dataAdapter);
DataTable dataTable = new DataTable();
dataTable.Locale = System.Globalization.CultureInfo.Invaria…
dataAdapter.Fill(dataTable);
//Decrypt cells
int i;
foreach (DataRow row in dataTable.Rows)
{
i = 0;
foreach (var item in row.ItemArray)
{
//This doesn't work
row.ItemArray[i] = Crypto.Decrypt(item.ToString());
i++;
}
}
return dataTable;
for (int i = 0; i < dataTable.Rows.Count; i++)
{
for (int j = 0; j < dataTable.Columns.Count; j++)
{
dataTable.Rows[i][j] = Crypto.Decrypt(dataTable.Rows[i][j].ToString());
}
}