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");
}
}
}
Related
I load data from SQLite to DataGridView. DataGridView doesn't show correctly. I have tried to use follow methods: Refresh, Paint, Update, Invalidate DataGridView.
If I minimize and maximize my program, then DataGridView shows correctly.
I execute it in the MainForm.
private void thicknessComboBox_TextChanged(object sender, EventArgs e)
{
List<string> tm1Deflection = database.ExecuteSelectQuery(connectionString, tm1ListCommand, parameters);
List<string> tension = database.ExecuteSelectQuery(connectionString, tensionListCommand, parameters);
var rowHeaders = new string[] { "TM-1 READING", "SPOKE TENSION (KGF)" };
var rows = new List<string[]> { tm1Deflection.ToArray(), tension.ToArray() };
formControl.SetDataGridViewValues(conversionTableGridView, tm1Deflection.Count, rowHeaders, rows); // This string filling DataGridView
}
Filling DataGridView locates in another class:
public void SetDataGridViewValues(DataGridView dataGridView, int columnCount, string[] rowHeaders, List<string[]> rows)
{
dataGridView.ColumnCount = columnCount;
dataGridView.RowHeadersWidth = 165;
int columnsWidth = (dataGridView.Width - dataGridView.RowHeadersWidth) / dataGridView.ColumnCount;
for (var i = 0; i < columnCount; i++)
{
dataGridView.Columns[i].Name = "";
dataGridView.Columns[i].Width = columnsWidth;
}
dataGridView.Rows.Clear();
if (rows.Count != rowHeaders.Length)
{
MessageBox.Show("Number of row headers must be equal number of rows!", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
else
{
for (var i = 0; i < rows.Count; i++)
{
dataGridView.Rows.Add(rows[i]);
dataGridView.Rows[i].HeaderCell.Value = rowHeaders[i];
}
}
}
Example with DataTable:
DataTable table = new DataTable();
table.Columns.Add("Column1", typeof(int));
table.Rows.Add(1);
conversionTableGridView.DataSource = table;
Error:
I have clicked on first cell:
I am using EPPlus Library to create an Excel report.
So far I have loaded the DataTable on sheet by using this code:
string FileName = #"DataSource\sampleData.xml";
var excelDocName = #"C:\Excel\OutExcel.xlsx";
var aFile = new FileInfo(excelDocName);
if (File.Exists(excelDocName))
File.Delete(excelDocName);
DataSet ds = new DataSet();
ds.ReadXml(FileName);
DataTable xmlTable = ds.Tables[0];
using (ExcelPackage pck = new ExcelPackage(aFile))
{
ExcelWorksheet ws = pck.Workbook.Worksheets.Add("DataLoad");
ws.Cells["A1"].LoadFromDataTable(xmlTable, true);
ws.Cells.AutoFitColumns();
pck.Save();
}
The result is perfect, but what I need to is
Merge the rows having same values in Column A and based on that I need to merge rows in Column B,C and D.
Sum range of Values in Column E based on Column A and merge rows in column E and show the Sum result.
I am attaching the screenshot of what I am getting and what result is needed and also share the Excel file and XML Data Source to quickly use the code to generate Excel.
XML DataSource
Excel Result Image
As Suggested by 'alhashmiya', I have change the logic and iterate DataTable row by row to insert and during insertion I hold the specific columns in a variable to update the merge range.
Below code is for any one in future who is having same requirement,
string FileName = #"DataSource\sampleData.xml";
var excelDocName = #"c:\temp\OutExcel.xlsx";
var aFile = new FileInfo(excelDocName);
DataSet ds = new DataSet();
ds.ReadXml(FileName);
DataTable table = ds.Tables[0];
using (ExcelPackage pck = new ExcelPackage(aFile))
{
ExcelWorksheet ws = pck.Workbook.Worksheets[1];
const int startRow = 2;
int mergestarttrow = 2;
int rw = startRow;
int RefNo = 0;
int TTLCONS = 0;
string[] mergedColNamed = new string[] { "SNO", "_NAME", "CAUSE_SUBCAUSE", "_AREAS", "CONS", "GRIDNAM" };
Dictionary<string, string> mergeRange = new Dictionary<string, string>() { { "SNO", "A" }, { "_NAME", "B" }, { "CAUSE_SUBCAUSE", "C" }, { "_AREAS", "D" }, { "CONS", "E" }, { "GRIDNAM", "F" } };
if (table.Rows.Count != 0)
{
foreach (DataRow row in table.Rows)
{
bool needMerge = false;
bool checkMerge = false;
//Hold to compare with next iteration and based to condition match Enable Check Merge Flag
int CurrentRefNo = System.Convert.ToInt32(row["SNO"]);
if (RefNo > 0)
{
if (RefNo == CurrentRefNo)
{
checkMerge = true;
mergeRange = mergeRange = mergeRange = new Dictionary<string, string>() { { "SNO", "A" }, { "_NAME", "B" }, { "CAUSE_SUBCAUSE", "C" }, { "_AREAS", "D" }, { "CONS", "E" }, { "GRIDNAM", "F" } };
}
else
{
mergestarttrow = rw;
needMerge = true;
}
}
int col = 1;
if (rw > startRow)
ws.InsertRow(rw, 1);
if (needMerge)
{
for (int i = 0; i < mergedColNamed.Length; i++)
{
string MergeRangeValue = mergeRange.FirstOrDefault(x => x.Key == mergedColNamed[i]).Value;
using (ExcelRange Rng = ws.Cells[MergeRangeValue])
{
Rng.Merge = true;
ws.Cells[MergeRangeValue].Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
ws.Cells[MergeRangeValue].Style.VerticalAlignment = ExcelVerticalAlignment.Center;
Rng.Style.Border.Top.Style = ExcelBorderStyle.Thin;
Rng.Style.Border.Left.Style = ExcelBorderStyle.Thin;
Rng.Style.Border.Right.Style = ExcelBorderStyle.Thin;
Rng.Style.Border.Bottom.Style = ExcelBorderStyle.Thin;
if (mergedColNamed[i] == "CONS")
{
Rng.Value = TTLCONS;
TTLCONS = 0;
Rng.Style.Numberformat.Format = "0";
}
if (mergedColNamed[i] == "SNO")
{
Rng.Style.Numberformat.Format = "0";
}
}
}
mergeRange = new Dictionary<string, string>() { { "SNO", "A" }, { "_NAME", "B" }, { "CAUSE_SUBCAUSE", "C" }, { "_AREAS", "D" }, { "CONS", "E" }, { "GRIDNAM", "F" } };
}
foreach (DataColumn dc in table.Columns)
{
if (mergedColNamed.Contains(dc.ColumnName.ToUpper()))
{
if (dc.ColumnName.ToUpper() == "CONS")
TTLCONS = TTLCONS + System.Convert.ToInt32(row[dc]);
if (!checkMerge)//First Row
{
if (dc.ColumnName.ToUpper() == "SNO")
RefNo = System.Convert.ToInt32(row[dc]);
ws.Cells[rw, col].Value = row[dc].ToString();
ws.Cells[rw, col].Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
ws.Cells[rw, col].Style.VerticalAlignment = ExcelVerticalAlignment.Center;
ws.Cells[rw, col].Style.Border.Top.Style = ExcelBorderStyle.Thin;
ws.Cells[rw, col].Style.Border.Left.Style = ExcelBorderStyle.Thin;
ws.Cells[rw, col].Style.Border.Right.Style = ExcelBorderStyle.Thin;
ws.Cells[rw, col].Style.Border.Bottom.Style = ExcelBorderStyle.Thin;
if (dc.ColumnName.ToUpper() == "CONS")
{
ws.Cells[rw, col].Style.Numberformat.Format = "0";
}
}
else //No Need to set Cell Values as ultimately we will merge only updating the merge range
{
string MergeRangeKey = mergeRange.FirstOrDefault(x => x.Value == mergeRange[dc.ColumnName.ToUpper()]).Key;
string MergeRangeValue = mergeRange[dc.ColumnName.ToUpper()];
mergeRange[MergeRangeKey] = string.Format(mergeRange[dc.ColumnName.ToUpper()] + "{0}:" + mergeRange[dc.ColumnName.ToUpper()] + "{1}", mergestarttrow, rw);
}
}
else
{
ws.Cells[rw, col].Value = row[dc].ToString();
ws.Cells[rw, col].Style.Border.Top.Style = ExcelBorderStyle.Thin;
ws.Cells[rw, col].Style.Border.Left.Style = ExcelBorderStyle.Thin;
ws.Cells[rw, col].Style.Border.Right.Style = ExcelBorderStyle.Thin;
ws.Cells[rw, col].Style.Border.Bottom.Style = ExcelBorderStyle.Thin;
}
col++;
}
rw++;
}
}
ws.Cells.AutoFitColumns();
pck.Save();
System.Diagnostics.Process.Start(excelDocName);
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();
}
}
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;
}
}
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?