Text file as datasource to display data in gridview - c#

Text file data looks like below:
FacilityID:12787 FacilityName:ACME Medical Center FacilityLocation:XYZ
FacilityID:27875 FacilityName:Medical Center FacilityLocation:kh
private void ReadFile(string fileName)
{
var rows = System.IO.File.ReadAllLines(fileName);
Char[] separator = new Char[] { ':' };
DataTable tbl = new DataTable(fileName);
if (rows.Length != 0)
{
foreach (string headerCol in rows[0].Split(separator[0]))
{
tbl.Columns.Add(new DataColumn(headerCol));
}
if (rows.Length > 1)
{
for (int rowIndex = 1; rowIndex < rows.Length; rowIndex++)
{
var newRow = tbl.NewRow();
var cols = rows[rowIndex].Split(separator);
for (int colIndex = 0; colIndex < cols.Length; colIndex++)
{
newRow[colIndex] = cols[colIndex];
}
tbl.Rows.Add(newRow);
}
}
}
}
To add data in datatable written above code.
but it is not filling properly.
"Datatable Wrongly Filled"
FacilityID:12787
FacilityName:ACME Medical Center
FacilityLocation:XYZ
FacilityID:27875
FacilityName:Medical Center
FacilityLocation:kh
How should i modify the code the datatable should be filled like below
FacilityID FacilityName FacilityLocation
12787 ACME Medical Center XYZ
27875 Medical Center kh

Some stuff which is already available on net may be helpful to you
please go through these links:
http://www.codeproject.com/KB/database/ReadTextFile.aspx
http://aspalliance.com/1107_CodeSnip_Reading_CSV_Files_Using_Dataset.all
http://www.c-sharpcorner.com/UploadFile/mgold/ConnectODBCText11262005070206AM/ConnectODBCText.aspx

private string GetID(string str)
{
if (!string.IsNullOrEmpty(str.Split(':')[1]))
{
return str.Split(':')[1].Replace("FacilityName", string.Empty);
}
return string.Empty;
}
private string GetName(string str)
{
if (!string.IsNullOrEmpty(str.Split(':')[2]))
{
return str.Split(':')[2].Replace("FacilityLocation", string.Empty);
}
return string.Empty;
}
private string GetLocation(string str)
{
if (!string.IsNullOrEmpty(str.Split(':')[3]))
{
return str.Split(':')[3];
}
return string.Empty;
}
private string Button Click()
{
string rows = "FacilityID:12787 FacilityName:ACME Medical Center FacilityLocation:XYZ";
DataTable tbl = new DataTable("test");
if (rows.Length != 0)
{
tbl.Columns.Add("FacilityID");
tbl.Columns.Add("FacilityName");
tbl.Columns.Add("FacilityLocation");
var newRow = tbl.NewRow();
newRow[0] = GetID(rows);
newRow[1] = GetName(rows);
newRow[2] = GetLocation(rows);
tbl.Rows.Add(newRow);
dataGridView1.DataSource = tbl.DefaultView;
}
}

Related

C# Gembox Spreadsheet to populate comboBox

I am working on a program that uses comboboxes that are populated from a csv file, I initially just used streamreader to populate the combobox, but I was instructed to use gembox spreadsheet to populate it instead.
Here is the streamreader code that I used:
private static List<ItemLine> Readfile(string fileName, string defaultValueDescription)
{
string path = $".\\Backend Files\\{fileName}";
var items = new List<ItemLine>();
int row = 0;
//read the file
StreamReader reader = new StreamReader(path);
while (reader.EndOfStream == false)
{
string lines = reader.ReadLine();
row++;
if (row == 1)
{
items.Add(new ItemLine { Description = defaultValueDescription, Quantity = 0 });
continue;
}
string[] itemFields = lines.Split(",");
ItemLine IL = new ItemLine();
if (itemFields.Length == 2)
{
IL.Description = itemFields[0];
IL.Quantity = 0;
if (int.TryParse(itemFields[1], out int qty))
{
IL.Quantity = qty;
}
}
else if (itemFields.Length >= 3)
{
IL.Plan = itemFields[0];
IL.Description = itemFields[1];
IL.Quantity = 0;
if (int.TryParse(itemFields[2], out int qty))
{
IL.Quantity = qty;
}
}
///Add Items to List
items.Add(IL);
}
reader.Close();
return items;
}
Here is an example of what I used gembox spreadsheet for in another part of my program which I use to update the csv files with, I think the code I am trying to figure out would look something like:
public void updateFile(string filename, int range, ItemLine selectedItem, decimal outValue)
{
var fullPath = $".\\Backend Files\\{filename}";
SpreadsheetInfo.SetLicense("FREE -LIMITED-KEY");
var workbook = ExcelFile.Load(fullPath, new CsvLoadOptions(CsvType.CommaDelimited));
var worksheet = workbook.Worksheets[0];
for (int i = 1; i <= range; i++)
{
var plan = worksheet.Rows[i].Cells[0].Value;
var desc = worksheet.Rows[i].Cells[1].Value;
var csvDescription = plan + " - " + desc;
var platedescription = plan + " - ";
if (selectedItem.ComboDescription == csvDescription)
{
worksheet.Rows[i].Cells[2].Value = outValue;
}
if (selectedItem.plateDescription == platedescription)
{
worksheet.Rows[i].Cells[1].Value = outValue;
}
}
workbook.Save(fullPath, new CsvSaveOptions(CsvType.CommaDelimited));
}
Try this:
private static List<ItemLine> ReadFile(string fileName, string defaultValueDescription)
{
string path = $".\\Backend Files\\{filename}";
var workbook = ExcelFile.Load(path, new CsvLoadOptions(CsvType.CommaDelimited));
var worksheet = workbook.Worksheets[0];
var items = new List<ItemLine>();
items.Add(new ItemLine { Description = defaultValueDescription, Quantity = 0 });
foreach (var row in worksheet.Rows)
{
var cells = row.AllocatedCells;
var il = new ItemLine();
items.Add(il);
if (cells.Count == 2)
{
il.Description = cells[0].Value.ToString();
il.Quantity = cells[1].ValueType == CellValueType.Int ? cells[1].IntValue : 0;
}
else if (cells.Count >= 3)
{
il.Plan = cells[0].Value.ToString();
il.Description = cells[1].Value.ToString();
il.Quantity = cells[2].ValueType == CellValueType.Int ? cells[2].IntValue : 0;
}
}
return items;
}
Also, I'm not sure about the logic around the defaultValueDescription, it seems that in your StreamReader approach you just skip the first line in CSV because of it.
If that is the intended behavior, then add the .Skip(1) extension method from System.Linq, like this:
foreach (var row in worksheet.Rows.Skip(1))
{
// ...
}

EPPLUS: Length of a DataValidation list cannot exceed 255 characters

This question is answered on a basic level on another post: here However for my case I am not able to hard code the validation values into the sheet I am pulling them from a database based on the content of the cell and will need to do a separate validation for 4 columns on every row. Is there a way this can be achieved? Thank you in advance.
// Data Validations //
// Product Validation //
for (int i = 2; i < rowCount; i++)
{
var val = ws.DataValidations.AddListValidation(ws.Cells[i, 5].Address);
val.ShowErrorMessage = true;
val.ErrorTitle = "Entry was invalid.";
val.Error = "Please choose options from the drop down only.";
var ticketEntity = ticketQueryable.Where(o => o.TTSTicketNumber == ws.Cells[i, 3].Value.ToString()).Single<CustCurrentTicketEntity>();
var prodIds = prodExtQueryable.Where(p => p.ZoneId == ticketEntity.ZoneId && p.TicketTypeId == ticketEntity.TicketTypeId);
if (ticketEntity != null)
{
var prodIdsList = new List<int>();
foreach (var prodId in prodIds)
{
prodIdsList.Add(prodId.ProductId);
}
var ProductList = ProductCache.Instance.AllProducts.Where(p => prodIdsList.Contains(p.ProductId)).Select(p => new SelectListItem() { Value = p.ProductId.ToString(), Text = p.Name });
foreach (var Result in ProductList)
{
var product = Result.Text;
val.Formula.Values.Add(product);
}
}
}
So yes as Ernie said What I did was add a second sheet "ProductValidations" and set it to Hidden (unhide it to check that it is working). I then Load my data from the DataTable and then add some basic EPPLUS formatting. I then iterate over the Rows and Insert values into the "ProductValidations" sheet for each cell. Next I convert my column number to the correct Excel Column letter name (A, AC, BCE etc) I then create a string to pass back as an Excel formula targeting the correct range of cells in the "ProductValidations" sheet. Also to anyone having an issue downloading the Excel file from the server this guid method works just fine for me.
public ActionResult DownloadExcel(EntityReportModel erModel, string filename)
{
var dataResponse = iEntityViewService.LoadEntityView(new EntityViewInput
{
SecurityContext = SessionCache.Instance.SecurityContext,
EntityViewName = "Ticket",
Parameters = new Dictionary<string, object> {
{"MinTicketDateTime", "04/26/16"}
}
});
var table = dataResponse.DataSet.Tables[0];
filename = "TICKETS-" + DateTime.Now.ToString("yyyy-MM-dd--hh-mm-ss") + ".xlsx";
using (ExcelPackage pack = new ExcelPackage())
{
ExcelWorksheet ws = pack.Workbook.Worksheets.Add(filename);
//Add second sheet to put Validations into
ExcelWorksheet productVal = pack.Workbook.Worksheets.Add("ProductValidations");
// Hide Validation Sheet
productVal.Hidden = OfficeOpenXml.eWorkSheetHidden.Hidden;
// Load the data from the datatable
ws.Cells["A1"].LoadFromDataTable(table, true);
ws.Cells[ws.Dimension.Address].AutoFitColumns();
int columnCount = table.Columns.Count;
int rowCount = table.Rows.Count;
// Format Worksheet//
ws.Row(1).Style.Font.Bold = true;
List<string> deleteColumns = new List<string>() {
"CurrentTicketId",
};
List<string> dateColumns = new List<string>() {
"TicketDateTime",
"Updated",
"InvoiceDate"
};
ExcelRange r;
// Format Dates
for (int i = 1; i <= columnCount; i++)
{
// if cell header value matches a date column
if (dateColumns.Contains(ws.Cells[1, i].Value.ToString()))
{
r = ws.Cells[2, i, rowCount + 1, i];
r.AutoFitColumns();
r.Style.Numberformat.Format = #"mm/dd/yyyy hh:mm";
}
}
// Delete Columns
for (int i = 1; i <= columnCount; i++)
{
// if cell header value matches a delete column
if ((ws.Cells[1, i].Value != null) && deleteColumns.Contains(ws.Cells[1, i].Value.ToString()))
{
ws.DeleteColumn(i);
}
}
int col = 0;
int Prow = 0;
int valRow = 1;
// Data Validations //
// Iterate over the Rows and insert Validations
for (int i = 2; i-2 < rowCount; i++)
{
Prow = 0;
col++;
valRow++;
// Add Validations At this row in column 7 //
var ProdVal = ws.DataValidations.AddListValidation(ws.Cells[valRow, 7].Address);
ProdVal.ShowErrorMessage = true;
ProdVal.ErrorTitle = "Entry was invalid.";
ProdVal.Error = "Please choose options from the drop down only.";
var ticketEntity = ticketQueryable.Where(o => o.TTSTicketNumber == ws.Cells[i, 3].Value.ToString()).Single<CustCurrentTicketEntity>();
// Product Validation //
var prodIds = prodExtQueryable.Where(p => p.ZoneId == ticketEntity.ZoneId && p.TicketTypeId == ticketEntity.TicketTypeId);
if (ticketEntity != null)
{
var prodIdsList = new List<int>();
foreach (var prodId in prodIds)
{
prodIdsList.Add(prodId.ProductId);
}
var ProductList = ProductCache.Instance.AllProducts.Where(p => prodIdsList.Contains(p.ProductId)).Select(p => new SelectListItem() { Value = p.ProductId.ToString(), Text = p.Name });
//For Each Item in the list move the row forward and add that value to the Validation Sheet
foreach (var Result in ProductList)
{
Prow++;
var product = Result.Text;
productVal.Cells[Prow, col].Value = product;
}
// convert column name from a number to the Excel Letters i.e A, AC, BCE//
int dividend = col;
string columnName = String.Empty;
int modulo;
while (dividend > 0)
{
modulo = (dividend - 1) % 26;
columnName = Convert.ToChar(65 + modulo).ToString() + columnName;
dividend = (int)((dividend - modulo) / 26);
}
// Pass back to sheeet as an Excel Formula to get around the 255 Char limit for Validations//
string productValidationExcelFormula = "ProductValidations!" + columnName + "1:" + columnName + Prow;
ProdVal.Formula.ExcelFormula = productValidationExcelFormula;
}
}
// Save File //
var fileStream = new MemoryStream(pack.GetAsByteArray());
string handle = Guid.NewGuid().ToString();
fileStream.Position = 0;
TempData[handle] = fileStream.ToArray();
// Note we are returning a filename as well as the handle
return new JsonResult()
{
Data = new { FileGuid = handle, FileName = filename }
};
}
}
[HttpGet]
public virtual ActionResult Download(string fileGuid, string fileName)
{
if (TempData[fileGuid] != null)
{
byte[] data = TempData[fileGuid] as byte[];
return File(data, "application/vnd.ms-excel", fileName);
}
else
{
//Log err
return new EmptyResult();
}
}

datatable turns empty when i pass it to method

So i have a very simple function which goes through a table and find those rows that has the age columns between 2 numbers and then return a new table with the new rows. here is my function :
private DataTable AgeFinder(int MiniAge, int MaxiAge, DataTable x)
{
//AFWT : Analyze From Which Table
int count;
DataTable dtAge = new DataTable();
dtAge = x.Clone();
int ageMin = MiniAge;
int ageMax = MaxiAge;
if (ageMin > ageMax)
{
int temp = ageMax;
ageMax = ageMin;
ageMin = temp;
}
int ageDr;
count = 0;
ageDr = 0;
dataGridView1.DataSource = x;
foreach (DataRow dr in x.Rows)
{
ageDr = Convert.ToInt16(x.Rows[count]["age "]);
if (ageDr >= ageMin && ageDr < ageMax)
{
dtAge.Rows.Add(dr.ItemArray);
}
count++;
}
lblCountThisQuery.Text = dtAge.Rows.Count.ToString();
return dtAge;
}
and here is how i call it:
dtAge = AgeFinder(Convert.ToInt16(tbxMinAge.Text), Convert.ToInt16(tbxMaxAge.Text), AT);
dataGridView1.DataSource = dtAge;
now i can see that the AT is not empty but when i check the x (the table inside the method), its empty! why does this happen?

Making my SQLite printing method dynamic

I am using SQLite to store the data for my application.
The application has a UI that loads the data from the SQLite database to display it table by table to the user. Basically the user can click left or right and view the other tables one by one.
The user can also click a button that will show a print preview of the data and let them print it. I have this working, but I am having some issues devising a dynamic way to display ANY table on the print preview screen perfectly. My concerns are if some column titles are too long etc, basically how to calculate the size of each column etc. Should I loop through and find the max character size of any text in the entire column and then set the column width to just wider than that or is there an easier way to do this?
I also write the data-table to a comma separated csv file so it might be a better alternative to use an existing solution to print from a csv file if any of you know such a solution then please suggest it!
Anyway here is the currently existing code:
// ------------------------ code that gets called when the print button is clicked ----------------------------
// holds the row data
List<string[]> myList = new List<string[]>();
if(ReportPage == 1)
{
int rowCount = MyTestTable.RowCount;
for(int i = 0; i <rowCount; i++)
{
MyTestTable.SelectedRowIndex = i;
var row1 = MyTestTable.GetSelectedRow();
var cols1 = row1.ItemArray;
string Col1 = cols1[row1.FindIndexOfColumn("Col1")].ToString();
string Col2 = cols1[row1.FindIndexOfColumn("Col2")].ToString();
string Col3 = cols1[row1.FindIndexOfColumn("Col3")].ToString();
string Col4 = cols1[row1.FindIndexOfColumn("Col4")].ToString();
string Col5 = cols1[row1.FindIndexOfColumn("Col5")].ToString();
string Col6 = cols1[row1.FindIndexOfColumn("Col6")].ToString();
string Col7 = cols1[row1.FindIndexOfColumn("Col7")].ToString();
myList.Add(new string[] { Col1, Col2, Col3, Col4, Col5, Col6, Col7 });
}
string[] cols = new string[7];
cols[0] = "Col1";
cols[1] = "Col2";
cols[2] = "Col3";
cols[3] = "Col4";
cols[4] = "Col5";
cols[5] = "Col6";
cols[6] = "Col7";
PrintUtility.SetUpDocument("TEST", cols, myList);
}
PrintUtility.TestNewReport();
// ---------------------- plugin code that gets called from the application
namespace PrintUtility
{
public class PrintUtility : UserComponentBase
{
public PrintDocument document;
public DataGridView dataGridView;
public PrintUtility()
{
document = new PrintDocument();
dataGridView = new DataGridView();
}
public void SetUpDocument(string title, string[] cols, List<string[]> rows)
{
document = new PrintDocument();
dataGridView = new DataGridView();
document.DocumentName = title;
document.DefaultPageSettings.Landscape = true;
document.PrintPage += PrintPage;
DataGridView dataGrid = new DataGridView();
dataGrid.ColumnCount = cols.Length;
for (int i = 0; i < cols.Length; i++ )
{
dataGrid.Columns[i].Name = cols[i];
}
foreach(string[] row in rows)
{
dataGrid.Rows.Add(row);
}
this.dataGridView = dataGrid;
document.DocumentName = title;
document.PrintPage += PrintPage;
}
public PrintDocument GetDocument()
{
return this.document;
}
private DataTable ConvertListToDataTable(List<string[]> list)
{
// New table.
DataTable table = new DataTable();
// Get max columns.
int columns = 0;
foreach (var array in list)
{
if (array.Length > columns)
{
columns = array.Length;
}
}
// Add columns.
for (int i = 0; i < columns; i++)
{
table.Columns.Add();
}
// Add rows.
foreach (var array in list)
{
table.Rows.Add(array);
}
return table;
}
public void TestNewReport()
{
Report report = new Report(new PdfFormatter());
FontDef fd = new FontDef(report, "Helvetica");
FontProp fp = new FontPropMM(fd, 4);
FontProp fp_Title = new FontPropMM(fd, 6);
FontProp fp_Word = new FontPropMM(fd, 3);
fp_Title.bBold = true;
List<string> columns = new List<string>();
foreach (DataGridViewColumn column in dataGridView.Columns)
{
columns.Add(column.Name.ToString());
}
List<List<string>> rows = new List<List<string>>();
foreach (DataGridViewRow row in dataGridView.Rows)
{
List<string> rowSingle = new List<string>();
foreach (DataGridViewCell cell in row.Cells)
{
try
{
rowSingle.Add(cell.Value.ToString());
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
rows.Add(rowSingle);
}
// AUDIT TABLE ( This way of doing things is not dynamic )
Page page = new Page(report);
page.SetLandscape();
int x = 10;
int y = 40;
int pastLength = 0;
foreach(string col in columns)
{
x += ((pastLength * 14) + 31);
page.Add(x, y, new RepString(fp_Title, col));
pastLength = col.Length;
}
page.Add(0, 52, new RepString(fp_Title, "_________________________________________________________________"));
/* Dynamic way starting
int rowX = 10;
int rowY = 105;
foreach (List<string> row in rows)
{
int pastLength2 = 0;
foreach (string rowItem in row)
{
page.Add(rowX, rowY, new RepString(fp_Word, rowItem));
rowX += ((pastLength * 14) + 31);
pastLength2 = rowItem.Length;
}
rowY += 30;
}
*/
fp_Title.rSizeMM = 8;
int amountRowsPerPageSoFar = 0;
int rowY = 80;
foreach (List<string> row in rows)
{
try
{
string iDItem = row[0];
page.Add(40, rowY, new RepString(fp_Word, iDItem));
string typeItem = row[1];
page.Add(120, rowY, new RepString(fp_Word, typeItem));
string descriptionItem = row[2];
page.Add(190, rowY, new RepString(fp_Word, descriptionItem));
string timestampItem = row[3];
page.Add(375, rowY, new RepString(fp_Word, timestampItem));
string userItem = row[4];
page.Add(555, rowY, new RepString(fp_Word, userItem));
string stationItem = row[5];
page.Add(655, rowY, new RepString(fp_Word, stationItem));
string activeItem = row[6];
page.Add(775, rowY, new RepString(fp_Word, activeItem));
amountRowsPerPageSoFar++;
rowY += 30;
if (amountRowsPerPageSoFar >= 17)
{
page = new Page(report);
page.SetLandscape();
amountRowsPerPageSoFar = 0;
rowY = 40;
}
}
catch (Exception ex)
{
}
}
RT.ViewPDF(report, "TestReport.pdf");
}
}
}

How to read from a GridView

Solution, for at least a specific cell: GridView1.Rows[i].Cells[j].Text;
I've build a simple CSV-Fileupload. After the user uploaded the file he should be able to evaluate the data. When the fileupload was successful the data gets loaded into the GridView1, with this code: (Problem below the code)
string[] readCSV = File.ReadAllLines(lblFilePath.Text);
DataTable dt = new DataTable();
bool bSplitMe = false;
foreach (var rLine in readCSV)
{
if (bSplitMe)
{
string[] aSplittedLine = rLine.Split(";".ToCharArray());
try
{
dt.Rows.Add(aSplittedLine);
}
catch(System.Exception)
{
txtBoxFileOut.Text = rLine;
break;
}
}
else
{
if (rLine.ToLower().StartsWith("definedtestid;"))
{
bSplitMe = true;
string[] aSplittedLine = rLine.Split(";".ToCharArray());
foreach (var rCol in aSplittedLine)
{
dt.Columns.Add(rCol);
}
}
else
{
txtBoxFileOut.Text += rLine.ToString() + "\n";
}
}
}
dt.Columns.Remove("Column1");
for (int i = 0; i < dt.Rows.Count; i++)
{
for (int j = 0; j < dt.Columns.Count; j++)
{
if (string.IsNullOrEmpty(dt.Rows[i][j].ToString()))
{
dt.Rows[i][j] = "0";
}
}
}
GridView1.DataSource = dt;
GridView1.DataBind();
After this the user should be able to select a row and display the data from that row in a chart.
Problem: I'm not able to read data from the cells I want, or to read from a "hardcoded" cell.
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e) {
GridViewRow row = GridView1.SelectedRow;
txtOutputfield.Text = row.Cells[2].Text;
}
Please check your cell index. Is it correct? For example: the third column will have index "2" not "3"
And, if you use a control to store the data, you need to find that control:
txtOutputfield.Text =
row.Cells[2].FindControl('placeyourcontrolnamehere').Text;
For a specific Cell this worked fine
txtOutputfield.Text = GridView1.Rows[i].Cells[j].Text;

Categories