Create reportviewer from dataset - c#

I am reading a file from which I create a dataset and I need to create a report from that dataset but this code is not working. so maybe someone could tell me what I am doing wrong I would really apreciated it or suggest another approach to this issue.
The BuildataSet function is working properly, creating the report its whats giving me problems.
public DataSet BuildDataSet(string file,string tableName,string delimeter)
{
//create our DataSet
DataSet domains = new DataSet();
//add our table
domains.Tables.Add(tableName);
String c = "VOYAGE|SAILDATE|DELIVERYDATE|AMENITY|QTY|COMPLIMENTS|MESSAGE|CABIN|1STPAXNAME|"
+"1STPAXLAST|2NDPAXNAME|2NDPAXLAST|3RDPAXNAME|3RDPAXLAST|4THPAXNAME|4THPAXLAST|SHIP|TYPE|DELIVERYTYPE|DROOM|SEATING|TABLE|GHOSTCOLUMN";
try
{
//first make sure the file exists
if (File.Exists(file))
{
//create a StreamReader and open our text file
StreamReader reader = new StreamReader(file);
//read the first line in and split it into columns
string [] columns = c.Split('|');
//now add our columns (we will check to make sure the column doesnt exist before adding it)
foreach (string col in columns)
{
//variable to determine if a column has been added
bool added = false;
string next = "";
//our counter
int i = 0;
while (!(added))
{
string columnName = col;
//now check to see if the column already exists in our DataTable
if (!(domains.Tables[tableName].Columns.Contains(columnName)))
{
//since its not in our DataSet we will add it
domains.Tables[tableName].Columns.Add(columnName, typeof(string));
added = true;
}//end if
else
{
//we didnt add the column so increment out counter
i++;
next = "_" + i.ToString();
break;
}//end else
}
}
//now we need to read the rest of the text file
string data = reader.ReadToEnd();
//now we will split the file on the carriage return/line feed
//and toss it into a string array
string [] rows = data.Split("\r".ToCharArray());
//now we will add the rows to our DataTable
foreach (string r in rows)
{
string[] items = r.Split(delimeter.ToCharArray());
//split the row at the delimiter
//for (int i = 0; i <= items.Count() - 1; i++)
//{
domains.Tables[tableName].Rows.Add(items);
//}
}
}
else
{
throw new FileNotFoundException("The file " + file + " could not be found");
}
}
catch (FileNotFoundException ex)
{
_message = ex.Message;
return null;
}
catch (Exception ex)
{
_message = ex.Message;
return null;
}
//now return the DataSet
return domains;
}
//#endregion
protected void Button1_Click(object sender, EventArgs e)
{
DataSet ds = BuildDataSet(#"C:/Documents/GIFTCDS.TXT", "MyNewTable", "|");
GridView1.DataSource = ds;
GridView1.DataBind();
ReportDataSource rds = new ReportDataSource("MyNewTable", ds.Tables[0]);
ReportViewer1.LocalReport.DataSources.Clear();
ReportViewer1.LocalReport.DataSources.Add(rds);
ReportViewer1.DataBind();
ReportViewer1.LocalReport.Refresh();
}

Related

Transfer text file items with degree symbol to datagridview

I am trying to input items in datagridview using text file.
I have below code to transfer the values of a csv file to my datagridview.
private void TransfertoDataGridView()
{
try
{
string SelectedReport = ReportsFilename;
System.IO.StreamReader file = new System.IO.StreamReader(SelectedReport);
string[] columnnames = file.ReadLine().Split(',');
DataTable dt = new DataTable();
foreach (string c in columnnames)
{
dt.Columns.Add(c);
}
dataGridView1.DataSource = null;
string newline;
while ((newline = file.ReadLine()) != null)
{
if (newline != "")
{
DataRow dr = dt.NewRow();
string[] values = newline.Split(',');
for (int i = 0; i < values.Length; i++)
{
try
{
dr[i] = values[i];
}
catch { }
}
dt.Rows.Add(dr);
}
}
file.Close();
dataGridView1.DataSource = dt;
this.dataGridView1.Columns[0].Visible = false;
}
catch
{
dataGridView1.DataSource = null;
}
}
Below is how my csv file looks like,
Column D has items with degree symbol.
And when I run the code, it transfers all the cell values but replaces the degree symbol with question mark "?".
I need expert help on how I can input the degree symbol to the datagridview.
Thank you very much in advanced for the help.
You can use something like this:
string str = "this is my string with a � sign like this.";
str = str.Replace('�', '°');
As a result:
this is my string with a ° sign like this.
If String like � then it will replace a ° sign.
Any symbol I guess you can do it with a replace function.

Import Part of CSV to datagridview

What I have is a CSV that I have imported into a Datagridview.
I am now looking for a way to only import the column with the header # and Delay and not all info in the CSV, so any help on this would be appreciated.
Here is the Code I have thus far:
private void button1_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
DialogResult result = openFileDialog1.ShowDialog();
if (result == DialogResult.OK) // Test result.
{
String Fname = openFileDialog1.FileName;
//String Sname = "export";
string[] raw_text = System.IO.File.ReadAllLines(Fname);
string[] data_col = null;
int x = 0;
foreach (string text_line in raw_text)
{
data_col = text_line.Split(';');
if (x == 0)
{
for (int i = 0; i < data_col.Count(); i++)
{
dt.Columns.Add(data_col[i]);
}
x++;
}
else
{
dt.Rows.Add(data_col);
}
}
dataGridView1.DataSource = dt;
}
}
When I read from CSV files, I create a list of values that I want for each row and use that list as the basis for my INSERT statement to the database.
I know where to find the data I want in the CSV file so I specifically target those items while I'm building my list of parameters for the query.
See the code below:
// Read the file content from the function parameter.
string content = System.Text.Encoding.ASCII.GetString(bytes);
// Split the content into an array where each array item is a line for
// each row of data.
// The Replace simply removes the CarriageReturn LineFeed characters from
// the source text and replaces them with a Pipe character (`|`)
// and then does the split from that character.
// This is just personal preference to do it this way
string[] data = content.Replace("\r\n", "|").Split('|');
// Loop through each row and extract the data you want.
// Note that each value is in a fixed position in the row.
foreach (string row in data)
{
if (!String.IsNullOrEmpty(row))
{
string[] cols = row.Split(';');
List<MySqlParameter> args = new List<MySqlParameter>();
args.Add(new MySqlParameter("#sid", Session["storeid"]));
args.Add(new MySqlParameter("#name", cols[0]));
args.Add(new MySqlParameter("#con", cols[3]));
try
{
// Insert the data to the database.
}
catch (Exception ex)
{
// Report an error.
}
}
}
In the same way, you could build your list/dataset/whatever as a data source for your datagridview. I would build a table.
Here's a mockup (I haven't got time to test it right now but it should get you on the right track).
DataTable table = new DataTable();
table.Columns.Add("#");
table.Columns.Add("Delay");
foreach (var line in raw_text)
{
DataRow row = table.NewRow();
row[0] = line[0]; // The # value you want.
row[1] = line[1]; // The Delay value you want.
table.Rows.Add(row);
}
DataGridView1.DataSource = table;
DataGridView1.DataBind();
Using TextFieldParser can make handling CVS input less brittle:
// add this using statement for TextFieldParser - needs reference to Microsoft.VisualBasic assembly
using Microsoft.VisualBasic.FileIO;
...
// TextFieldParser implements IDisposable so you can let a using block take care of opening and closing
using (TextFieldParser parser = new TextFieldParser(Fname))
{
// configure your parser to your needs
parser.TextFieldType = FieldType.Delimited;
parser.Delimiters = new string[] { ";" };
parser.HasFieldsEnclosedInQuotes = false; // no messy code if your data comes with quotes: ...;"text value";"another";...
// read the first line with your headers
string[] fields = parser.ReadFields();
// add the desired headers with the desired data type
dt.Columns.Add(fields[2], typeof(string));
dt.Columns.Add(fields[4], typeof(string));
// read the rest of the lines from your file
while (!parser.EndOfData)
{
// all fields from one line
string[] line = parser.ReadFields();
// create a new row <-- this is missing in your code
DataRow row = dt.NewRow();
// put data values; cast if needed - this example uses string type columns
row[0] = line[2];
row[1] = line[4];
// add the newly created and filled row
dt.Rows.Add(row);
}
}
// asign to DGV
this.dataGridView1.DataSource = dt;

How to copy 1 column from a CSV file to a SQL database?

I got a CSV file but in the files in using there are not comma seperaters in the file.
How can I copy this data into my database? So the CSV file and thus the database should have 1 column.
This is what I tried so far:
System.Data.DataTable csvData = new System.Data.DataTable();
try
{
using (TextFieldParser csvReader = new TextFieldParser(csv_file_path, Encoding.GetEncoding("windows-1250"))) //windows 1250 is de correcte character encoding voor europese characters
{
csvReader.SetDelimiters(new string[] { "," }); //change this maybe to something???
csvReader.HasFieldsEnclosedInQuotes = true;
string[] colFields = csvReader.ReadFields();
foreach (string column in colFields)
{
DataColumn datecolumn = new DataColumn(column);
datecolumn.AllowDBNull = true;
csvData.Columns.Add(datecolumn);
}
while (!csvReader.EndOfData)
{
string[] fieldData = csvReader.ReadFields();
//Making empty value as null
for (int i = 0; i < fieldData.Length; i++)
{
if (fieldData[i] == "")
{
fieldData[i] = null;
}
}
csvData.Rows.Add(fieldData); // it return an error here saying that: `System.ArgumentException: Input array is longer than the number of columns in this table`
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
InsertDataIntoSQLServerUsingSQLBulkCopy(csvData, tablenaam);
return csvData;
So an example for the CSV would be:
test123
test45,6
test789
And in my database would be the exact same values.
EDIT: read the comment about actual delimeters so I've updated the code below, is not pretty but should give you a starting point
Why not read the file as a simple text file. One line at a time and parse the expected syntax.
Doing something like this (not tested, may not compile)
string line;
System.Data.DataTable csvData = new System.Data.DataTable();
csvData.Columns.Add("OnlyColumn", typeof(String));
System.IO.StreamReader file = new System.IO.StreamReader("c:\\test.txt");
while((line = file.ReadLine()) != null)
{
if(line.StartsWith("-"))
continue;
DataRow newRow = csvData.NewRow();
newRow["OnlyColumn"] = line.Split('|')[1].Trim();
csvData.Rows.Add(newRow);
}
file.Close();
InsertDataIntoSQLServerUsingSQLBulkCopy(csvData, tablenaam);
Maybe you need to use new line as delimiter not comma. I think you can have new values in new lines?
I think you can just use StreamReader.ReadLine() for this
You should check out this link for an explanation from Microsoft.
https://msdn.microsoft.com/en-us/library/system.io.streamreader.readline(v=vs.110).aspx
So something like this should do it:
using (StreamReader sr = new StreamReader(csv_file_path))
{
while (sr.Peek() >= 0)
{
csvData.Rows.Add(new string[] {sr.ReadLine()});
}
}

using paging in DataTable for showing in GridView

I want 30 data in GridView. I want to read all the files in my folder and show in GridView. I am using the following code.
string folderPath = #"C:\Folder\Folder-2.0\New folder";
DataTable dt = new DataTable();
//Creating DataTable
foreach (string fileName in Directory.EnumerateFiles(folderPath, "*.txt"))
{
string contents = File.ReadAllText(fileName);
string str = string.Empty;
string s;
if (File.Exists(fileName))
{
StreamReader sr = new StreamReader(fileName);
String line;
int k = 0;
while ((line = sr.ReadLine()) != null)
{
string[] text;
if (line.Trim() != string.Empty)
{
//text = line.Split(new char[] { '^' }, StringSplitOptions.RemoveEmptyEntries);
text = line.Split('^');
if (text[0].Contains("START FOOTER"))
{
break;
}
else
{
DataRow dr;
dr = dt.NewRow();
for (int i = 0; i <= text.Length - 1; i++)
{
dr[i] = text[i];
}
dt.Rows.Add(dr);
k = k + 1;
}
}
}
Response.Write(k);
// Response.End;
GridView1.DataSource = dt;
GridView1.DataBind();
}
else
{
s = "File does not exists";
}
}
But the above Code throws error System.OutOfMemoryException. Error is pointing at code GridView1.DataBind(); There are about 2000 files in the folder each file is of size between 1 to 2 MB. Thats why I want to use paging using DataTable. Through DataTable I want to show 30 records.
Thanks,
Please define PageSize as 30 and implement PageIndexChanging event
protected void GridView1_PageIndexChanging(object sender, GridView1PageEventArgs e)
{
// here you need create one method of your above code and call here
GridView1.PageIndex = e.NewPageIndex;
GridView1.DataBind();
}

Populating a dataset from a CSV file

I would like to read the contents of a CSV file and create a dataset.
I am trying like this:
var lines = File.ReadAllLines("test.csv").Select(a => a.Split(';'));
DataSet ds = new DataSet();
ds.load(lines);
but apparently this is not correct.
You need to add the reference Microsoft.VisualBasic.dll to use TextFieldParser Class.
private static DataTable GetDataTabletFromCSVFile(string csv_file_path)
{
DataTable csvData = new DataTable();
try
{
using(TextFieldParser csvReader = new TextFieldParser(csv_file_path))
{
csvReader.SetDelimiters(new string[] { "," });
csvReader.HasFieldsEnclosedInQuotes = true;
string[] colFields = csvReader.ReadFields();
foreach (string column in colFields)
{
DataColumn datecolumn = new DataColumn(column);
datecolumn.AllowDBNull = true;
csvData.Columns.Add(datecolumn);
}
while (!csvReader.EndOfData)
{
string[] fieldData = csvReader.ReadFields();
//Making empty value as null
for (int i = 0; i < fieldData.Length; i++)
{
if (fieldData[i] == "")
{
fieldData[i] = null;
}
}
csvData.Rows.Add(fieldData);
}
}
}
catch (Exception ex)
{
}
return csvData;
}
}
See this article for more info : http://www.morgantechspace.com/2013/08/how-to-read-data-from-csv-file-in-c.html
You need to run a SELECT statement against the CSV file to fill the dataset:
Edit: here's some sample code from http://carllbrown.blogspot.co.uk/2007/09/populate-dataset-from-csv-delimited_18.html
string FileName = ...
OleDbConnection conn = new OleDbConnection
("Provider=Microsoft.Jet.OleDb.4.0; Data Source = " +
Path.GetDirectoryName(FileName) +
"; Extended Properties = \"Text;HDR=YES;FMT=Delimited\"");
conn.Open();
OleDbDataAdapter adapter = new OleDbDataAdapter
("SELECT * FROM " + Path.GetFileName(FileName), conn);
DataSet ds = new DataSet("Temp");
adapter.Fill(ds);
conn.Close();
You can use Library like Fast CSV Reader then
using System.IO;
using LumenWorks.Framework.IO.Csv;
void ReadCsv()
{
// open the file "data.csv" which is a CSV file with headers
using (CsvReader csv = new CsvReader(
new StreamReader("data.csv"), true))
{
myDataRepeater.DataSource = csv;
myDataRepeater.DataBind();
}
}
Comma (,) Problem Solved in This Code
Works Even If you add Commas(,) in between a cell
Reading CSV file CODE:
public MainWindow()
{
InitializeComponent();
DataTable dtDataSource = new DataTable();
string[] fileContent = File.ReadAllLines(#"..\\Book1.csv");
if (fileContent.Count() > 0)
{
//Create data table columns dynamically
string[] columns = fileContent[0].Split(',');
for (int i = 0; i < columns.Count(); i++)
{
dtDataSource.Columns.Add(columns[i]);
}
//Add row data dynamically
for (int i = 1; i < fileContent.Count(); i++)
{
string[] rowData = fileContent[i].Split(',');
string[] realRowData = new string[columns.Count()];
StringBuilder collaboration = new StringBuilder();
int v = 0;
//this region solves the problem of a cell containing ",".
#region CommaSepProblem
for (int j = 0, K = 0; j < rowData.Count(); j++, K++)
{
if ((rowData[j].Count(x => x == '"') % 2 == 0))//checks if the string contains even number of DoubleQuotes
{
realRowData[K] = quotesLogic((rowData[j]));
}
else if ((rowData[j].Count(x => x == '"') % 2 != 0))//If Number of DoubleQuotes are ODD
{
int c = rowData[j].Count(x => x == '"');
v = j;
while (c % 2 != 0)//Go through all the next array cell till it makes EVEN Number of DoubleQuotes.
{
collaboration.Append(rowData[j] + ",");
j++;
c += rowData[j].Count(x => x == '"');
}
collaboration.Append(rowData[j]);
realRowData[K] = quotesLogic(collaboration.ToString());
}
else { continue; }
}
#endregion
dtDataSource.Rows.Add(realRowData);
}
if (dtDataSource != null)
{
//dataGridView1 = new DataGridView();
dataGrid1.ItemsSource = dtDataSource.DefaultView;
}
}
}
Method Need to be added:
string quotesLogic(string collaboration)
{
StringBuilder after = new StringBuilder(collaboration);
if (after.ToString().StartsWith("\"") && after.ToString().EndsWith("\""))//removes 1st and last quotes as those are system generated
{
after.Remove(0, 1);
after.Remove(after.Length - 1, 1);
int count = after.Length - 1;
//FACT: if you try to add DoubleQuote in a cell in excel. It'll save that quote as 2 times DoubleQuote(Like "") which means first DoubleQuote is to give instruction to CPU that the next DoubleQuote is not system generated.
while (count > 0)//This loop find twice insertion of 2 DoubleQuotes and neutralise them to One DoubleQuote.
{
if (after[count] == '"' && after[count - 1] == '"')
{
after.Remove(count, 1);
}
count--;
}
}
return after.ToString();
}
If you just want to quickly create a DataTable filled with sample data from a CSV file (or pasted directly from Excel) to play around or prototype, then you can use my fork of Shan Carter's Mr. Data Converter -- I recently added the ability to output comma- and tab-delimited data to a C# DataTable.
http://thdoan.github.io/mr-data-converter/
I have written five methods below that will turn a Csv file into a DataTable.
They have been designed to take into account optional quote marks (e.g. " symbols) and to be as versatile as possible without using other libraries:
public static DataTable GetDataTabletFromCSVFile(string filePath, bool isHeadings)
{
DataTable MethodResult = null;
try
{
using (TextFieldParser TextFieldParser = new TextFieldParser(filePath))
{
if (isHeadings)
{
MethodResult = GetDataTableFromTextFieldParser(TextFieldParser);
}
else
{
MethodResult = GetDataTableFromTextFieldParserNoHeadings(TextFieldParser);
}
}
}
catch (Exception ex)
{
ex.HandleException();
}
return MethodResult;
}
public static DataTable GetDataTableFromCsvString(string csvBody, bool isHeadings)
{
DataTable MethodResult = null;
try
{
MemoryStream MemoryStream = new MemoryStream();
StreamWriter StreamWriter = new StreamWriter(MemoryStream);
StreamWriter.Write(csvBody);
StreamWriter.Flush();
MemoryStream.Position = 0;
using (TextFieldParser TextFieldParser = new TextFieldParser(MemoryStream))
{
if (isHeadings)
{
MethodResult = GetDataTableFromTextFieldParser(TextFieldParser);
}
else
{
MethodResult = GetDataTableFromTextFieldParserNoHeadings(TextFieldParser);
}
}
}
catch (Exception ex)
{
ex.HandleException();
}
return MethodResult;
}
public static DataTable GetDataTableFromRemoteCsv(string url, bool isHeadings)
{
DataTable MethodResult = null;
try
{
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
StreamReader StreamReader = new StreamReader(httpWebResponse.GetResponseStream());
using (TextFieldParser TextFieldParser = new TextFieldParser(StreamReader))
{
if (isHeadings)
{
MethodResult = GetDataTableFromTextFieldParser(TextFieldParser);
}
else
{
MethodResult = GetDataTableFromTextFieldParserNoHeadings(TextFieldParser);
}
}
}
catch (Exception ex)
{
ex.HandleException();
}
return MethodResult;
}
private static DataTable GetDataTableFromTextFieldParser(TextFieldParser textFieldParser)
{
DataTable MethodResult = null;
try
{
textFieldParser.SetDelimiters(new string[] { "," });
textFieldParser.HasFieldsEnclosedInQuotes = true;
string[] ColumnFields = textFieldParser.ReadFields();
DataTable dt = new DataTable();
foreach (string ColumnField in ColumnFields)
{
DataColumn DataColumn = new DataColumn(ColumnField);
DataColumn.AllowDBNull = true;
dt.Columns.Add(DataColumn);
}
while (!textFieldParser.EndOfData)
{
string[] Fields = textFieldParser.ReadFields();
for (int i = 0; i < Fields.Length; i++)
{
if (Fields[i] == "")
{
Fields[i] = null;
}
}
dt.Rows.Add(Fields);
}
MethodResult = dt;
}
catch (Exception ex)
{
ex.HandleException();
}
return MethodResult;
}
private static DataTable GetDataTableFromTextFieldParserNoHeadings(TextFieldParser textFieldParser)
{
DataTable MethodResult = null;
try
{
textFieldParser.SetDelimiters(new string[] { "," });
textFieldParser.HasFieldsEnclosedInQuotes = true;
bool FirstPass = true;
DataTable dt = new DataTable();
while (!textFieldParser.EndOfData)
{
string[] Fields = textFieldParser.ReadFields();
if(FirstPass)
{
for (int i = 0; i < Fields.Length; i++)
{
DataColumn DataColumn = new DataColumn("Column " + i);
DataColumn.AllowDBNull = true;
dt.Columns.Add(DataColumn);
}
FirstPass = false;
}
for (int i = 0; i < Fields.Length; i++)
{
if (Fields[i] == "")
{
Fields[i] = null;
}
}
dt.Rows.Add(Fields);
}
MethodResult = dt;
}
catch (Exception ex)
{
ex.HandleException();
}
return MethodResult;
}
If, like me, you're saving from reporting services then you should use it like this:
Warning[] warnings;
string[] streamids;
string mimeType;
string encoding;
string filenameExtension;
byte[] bytes = rvMain.ServerReport.Render("csv", null, out mimeType, out encoding, out filenameExtension, out streamids, out warnings);
string CsvBody = System.Text.Encoding.UTF8.GetString(bytes);
DataTable dt = GetDataTableFromCsvString(CsvBody,true);
Otherwise, all you need do is:
bool IsHeadings = true; //Does the data include a heading row?
DataTable dt = GetDataTableFromCsvString(CsvBody, IsHeadings);
Or to use directly from a csv file
bool IsHeadings = true; //Does the data include a heading row?
DataTable dt = GetDataTabletFromCsvFile(FilePath, IsHeadings)
Or to use a csv file that is stored remotely
bool IsHeadings = true; //Does the data include a heading row?
DataTable dt = GetDataTabletFromRemoteCsv(Url, IsHeadings)
A Dataset is a collection of DataTables, so create one like so:
DataSet ds = new DataSet();
ds.Tables.Add(dt);

Categories

Resources