How to convert Linq select new to DataTable - c#

How to convert select new LINQ to DataTable
I need to compare several files using Windows Application form C#.
I have use LINQ and Lambda expression to sum up the duplicates
Please help thanks
I had seen Convert select new to DataTable?. and tried
var firstRecord = records.First();
if (firstRecord == null)
return;
var infos = firstRecord.GetType().GetProperties();
DataTable table = new DataTable();
foreach (var info in infos) {
DataColumn column = new DataColumn(info.Name, info.PropertyType);
table.Columns.Add(column);
}
foreach (var record in records) {
DataRow row = table.NewRow();
for (int i = 0; i < table.Columns.Count; i++)
row[i] = infos[i].GetValue(record);
table.Rows.Add(row);
}
But it had errors for sequence contains no elements.
These are my full codes.
namespace Comparison2._0
{
public partial class ComparisonForm : Form
{
public class FlatFile
{
public string Location { get; set; }
public string Item_Type { get; set; }
public string Type { get; set; }
public double Amount { get; set; }
}
public ComparisonForm()
{
InitializeComponent();
}
private void UploadTransactionReportButton_Click(object sender, EventArgs e)
{
OpenFileDialog dialog = new OpenFileDialog();
dialog.Multiselect = false;
if (dialog.ShowDialog() == DialogResult.OK)
{
String path = dialog.FileName;
//String fileName = path.Substring(path.LastIndexOf("\\") + 1);
TransactionFileNameTextBox.Text = path;
}
}
private void UploadMovementReportButton_Click(object sender, EventArgs e)
{
OpenFileDialog dialog = new OpenFileDialog();
dialog.Multiselect = false;
if (dialog.ShowDialog() == DialogResult.OK)
{
String path = dialog.FileName;
//String fileName = path.Substring(path.LastIndexOf("\\") + 1);
MovementReportTextBox.Text = path;
}
}
private void UploadFlatfileReportButton_Click(object sender, EventArgs e)
{
OpenFileDialog dialog = new OpenFileDialog();
dialog.Multiselect = true;
if (dialog.ShowDialog() == DialogResult.OK)
{
String[] path = dialog.FileNames;
//String fileName = path.Substring(path.LastIndexOf("\\") + 1);
for (int i = 0; i < path.Count(); i++)
FlatfileTextBox.Text += path[i] + "#";
}
}
private void UploadAdjustmentReportButton_Click(object sender, EventArgs e)
{
OpenFileDialog dialog = new OpenFileDialog();
dialog.Multiselect = false;
if (dialog.ShowDialog() == DialogResult.OK)
{
String path = dialog.FileName;
AdjustmentReportTextBox.Text = path;
}
}
private void CompareButton_Click(object sender, EventArgs e)
{
OleDbConnection objConn, objConn1, objConn2;
DataTable dt, dt1, dt2, TableA, TableB, TableC;
string sql, sql1, sql2;
OleDbDataAdapter oleDA;
DataSet ds;
string transactionReport = TransactionFileNameTextBox.Text;
string movementReport = MovementReportTextBox.Text;
string adjustmentReport = AdjustmentReportTextBox.Text;
String sConnectionString1 = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" +
transactionReport + ";" + "Extended Properties=\"Excel 12.0;HDR=YES;IMEX=1\"";
String sConnectionString2 = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source="
+ movementReport + ";" + "Extended Properties =\"Excel 12.0;HDR=YES;IMEX=1\"";
String sConnectionString3 = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source="
+ adjustmentReport + ";" + "Extended Properties =\"Excel 12.0;HDR=YES;IMEX=1\"";
//TRANSACTION FILE
objConn = new OleDbConnection(sConnectionString1);
objConn.Open();
dt = objConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
sql = "SELECT * from [Sheet$]";
oleDA = new OleDbDataAdapter(sql, sConnectionString1);
ds = new DataSet();
oleDA.Fill(ds);
TableA = ds.Tables[0];
objConn.Close();
//dataGridView.DataSource = _DtTable;
//MOVEMENT FILE
objConn1 = new OleDbConnection(sConnectionString2);
objConn1.Open();
dt1 = objConn1.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
sql1 = "SELECT * from [Sheet$]";
oleDA = new OleDbDataAdapter(sql1, sConnectionString2);
ds = new DataSet();
oleDA.Fill(ds);
TableB = ds.Tables[0];
objConn1.Close();
//dataGridView.DataSource = _DtTable1;
//ADJUSTMENT FILE
objConn2 = new OleDbConnection(sConnectionString3);
objConn2.Open();
dt2 = objConn2.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
sql2 = "SELECT * from [Sheet$]";
oleDA = new OleDbDataAdapter(sql2, sConnectionString3);
ds = new DataSet();
oleDA.Fill(ds);
TableC = ds.Tables[0];
objConn2.Close();
//dataGridView1.DataSource = TableC;
//FLATFILES
//List<string> fileLines = System.IO.File.ReadAllLines(FlatfileTextBox.Text).ToList();
DataTable TableD = ConvertToDataTable(FlatfileTextBox.Text, 4);
//dataGridView1.DataSource = tableD;
DataTable FlatFileTable = new DataTable();
FlatFileTable.Columns.Add(new DataColumn("Location"));
FlatFileTable.Columns.Add(new DataColumn("Item Type"));
FlatFileTable.Columns.Add(new DataColumn("Type"));
FlatFileTable.Columns.Add(new DataColumn("PO Total Cost(Qty Received)"));
FlatFileTable.Columns.Add(new DataColumn("Amount", typeof(double)));
FlatFileTable.Columns.Add(new DataColumn("Amount Difference"));
foreach (DataRow rowA in TableA.Rows)
{
foreach (DataRow rowD in TableD.Rows)
{
if (Convert.ToDouble(rowD["Amount"]) > 0)
{
if (rowA["Location"].ToString().Substring(0, 5).Trim() == rowD["Location"].ToString() && rowD["Type"].ToString() == "GRN" && rowA["Item Type"].ToString() == rowD["Item Type"].ToString())
{
var newRow = FlatFileTable.NewRow();
newRow["Location"] = rowD["Location"];
newRow["Item Type"] = rowD["Item Type"];
newRow["Type"] = rowD["Type"];
newRow["PO Total Cost(Qty Received)"] = rowA["PO Total Cost(Qty Received)"];
//sum += Convert.ToDouble(rowD["Amount"]);
newRow["Amount"] = rowD["Amount"];
var newSort = from row in FlatFileTable.AsEnumerable()
group row by new { Location = row.Field<string>("Location"), Item_Type = row.Field<string>("Item Type"), Type = row.Field<string>("Type") } into grp
select new
{
Location = grp.Key.Location,
//Item_Type = grp.Key.Item_Type,
Type = grp.Key.Type,
Amount = grp.Sum(r => r.Field<double>("Amount"))
};
//dataGridView1.DataSource = table;
//newRow["Amount Difference"] = Convert.ToDouble(rowA["PO Total Cost(Qty Received)"]) - Convert.ToDouble(rowD["Amount"]);
FlatFileTable.Rows.Add(newRow);
//FlatFileTable.Rows.Add(newSort.ToList());
//dataGridView1.DataSource = FlatFileTable;
//DataTable TableZ = newSort.Copt
dataGridView.DataSource = Comparison(TableA, TableB, FlatFileTable);
}
}
}
}
//dataGridView1.DataSource = FlatFileTable;
//dataGridView.DataSource = Comparison(TableA, TableB, newSort.);
//I want to pass into this function so I can compare between them
}
public DataTable ConvertToDataTable(string filePath, int numberOfColumns)
{
DataTable tbl = new DataTable();
tbl.Columns.Add(new DataColumn("Type"));
tbl.Columns.Add(new DataColumn("Amount", typeof(double)));
tbl.Columns.Add(new DataColumn("Location"));
tbl.Columns.Add(new DataColumn("Item Type"));
//foreach(var file in filePath)
string[] MultipleFiles = filePath.Split('#');
for (int i = 0; i < MultipleFiles.Count() - 1; i++)
{
string[] lines = System.IO.File.ReadAllLines(MultipleFiles[i]);
foreach (string line in lines)
{
var cols = line.Split('|');
var count = 0;
DataRow dr = tbl.NewRow();
for (int cIndex = 7; cIndex < 11; cIndex++)
{
dr[count] = cols[cIndex];
count++;
}
tbl.Rows.Add(dr);
}
}
return tbl;
}
public DataTable Comparison(DataTable A, DataTable B, DataTable C)
{
var tableC = new DataTable();
tableC.Columns.Add(new DataColumn("Location"));
tableC.Columns.Add(new DataColumn("Item Type"));
tableC.Columns.Add(new DataColumn("PO Total Cost(Qty Received)"));
tableC.Columns.Add(new DataColumn("Qty Received Actual Cost"));
tableC.Columns.Add(new DataColumn("Amount from FlatFile"));
tableC.Columns.Add(new DataColumn("Amount (Transaction - Movement)"));
tableC.Columns.Add(new DataColumn("Amount (Transaction - FlatFile)"));
foreach (DataRow rowA in A.Rows)
{
foreach (DataRow rowB in B.Rows)
{
foreach (DataRow rowC in C.Rows)
{
if (rowA["Location"].ToString() == rowB["Location"].ToString() && rowA["Item Type"].ToString() == rowB["Item Type"].ToString() &&
rowA["Location"].ToString().Substring(0, 5).Trim() == rowC["Location"].ToString() && rowA["Item Type"].ToString() == rowC["Item Type"].ToString())
{
var newRow = tableC.NewRow();
newRow["Location"] = rowA["Location"];
newRow["Item Type"] = rowA["Item Type"];
newRow["PO Total Cost(Qty Received)"] = rowA["PO Total Cost(Qty Received)"];
newRow["Qty Received Actual Cost"] = rowB["Qty Received Actual Cost"];
newRow["Amount from FlatFile"] = rowC["Amount"];
newRow["Amount (Transaction - Movement)"] = Convert.ToDouble(rowA["PO Total Cost(Qty Received)"]) - Convert.ToDouble(rowB["Qty Received Actual Cost"]);
newRow["Amount (Transaction - FlatFile)"] = Convert.ToDouble(rowA["PO Total Cost(Qty Received)"]) - Convert.ToDouble(rowC["Amount"]);
tableC.Rows.Add(newRow);
}
//}
}
}
}
return tableC;
}
private void ComparisonForm_Load(object sender, EventArgs e)
{
}
}
}

But it had errors for sequence contains no elements.
You are getting the above error because there is no record in the collection apparently and First fails in that case. You need FirstOrDefault which will return null if there is no items in the collection:
var firstRecord = records.FirstOrDefault();

Related

How to see a number with more than 15 characters in a DataGridView?

I'm trying to import from a CSV file into DataGridView a number that is longer than 15 characters. In the CSV file it looks like 8940012004412026012but after import in the DataGridView is presented as 8.9400120044120259E + 18.
This is my present code:
public static DataTable GetDataTable(string strFileName)
{
ADODB.Connection oConn = new ADODB.Connection();
oConn.Open("Provider=Microsoft.Jet.OleDb.4.0; Data Source = " + System.IO.Path.GetDirectoryName(strFileName) + "; Extended Properties = \"Text;HDR=YES;FMT=Delimited\";", "", "", 0);
string strQuery = "SELECT * FROM [" + System.IO.Path.GetFileName(strFileName) + "]";
ADODB.Recordset rs = new ADODB.Recordset();
System.Data.OleDb.OleDbDataAdapter adapter = new System.Data.OleDb.OleDbDataAdapter();
DataTable dt = new DataTable();
rs.Open(strQuery, "Provider=Microsoft.Jet.OleDb.4.0; Data Source = " + System.IO.Path.GetDirectoryName(strFileName) + "; Extended Properties = \"Text;HDR=YES;FMT=Delimited\";",
ADODB.CursorTypeEnum.adOpenForwardOnly, ADODB.LockTypeEnum.adLockReadOnly, 1);
adapter.Fill(dt, rs);
return dt;
}
private void Import()
{
if (textBox4.Text.Trim() != string.Empty)
{
try
{
DataTable ct = GetDataTable(textBox4.Text);
dataGridView2.AllowUserToAddRows = false;
dataGridView2.DataSource = ct;
dataGridView2.Columns[0].HeaderCell.Value = "1";
dataGridView2.Columns[1].HeaderCell.Value = "2";
dataGridView2.Columns[2].HeaderCell.Value = "3";
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
}
}
dataGridView2.Columns[2].HeaderCell.Value = "3";
needs to be 8940012004412026012
Thanks for the suggestion to use CsvHelper this is the solution i found
private void button60_Click(object sender, EventArgs e)
{
OpenFileDialog fdlg = new OpenFileDialog();
fdlg.Title = "Select file";
fdlg.InitialDirectory = #"c:\";
fdlg.FileName = textBox4.Text;
fdlg.Filter = "Text and CSV Files(*.txt, *.csv)|*.txt;*.csv|Text Files(*.txt)|*.txt|CSV Files(*.csv)|*.csv|All Files(*.*)|*.*";
fdlg.FilterIndex = 1;
fdlg.RestoreDirectory = true;
if (fdlg.ShowDialog() == DialogResult.OK)
{
using (var reader = new StreamReader(fdlg.FileName))
using (var csv = new CsvReader(reader, CultureInfo.InvariantCulture))
{
using (var dr = new CsvDataReader(csv))
{
var dt = new DataTable();
dt.Load(dr);
dataGridView2.DataSource = dt;
}
}
}
}

DataTable automatically re-initializes itself

Why does my DataTable automatically reset to null value inside of my event?
After the for loop ends the DataTable resets to null and doesn't keep the value in the public field. Even though I have another event that does the same thing but it can hold the DataTable.
Public DataTable d = new DataTable();
private void btnCSVgetter_Click(object sender, EventArgs e)
{
emptyDataGrid();
var csv = new OpenFileDialog();
csv.Title = "Select CSV to Upload";
csv.DefaultExt = "*.csv";
csv.Filter = "CSV files| *.csv";
if (csv.ShowDialog() == DialogResult.OK)
{
string safeName = csv.SafeFileName;
string filename = csv.FileName;
string filedirectory = csv.FileName.Substring(0, filename.IndexOf(safeName));
if (IsFileLocked(filename)) { MessageBox.Show("File is in use by another user, close and try again"); return; }
var con = new OleDbConnection(String.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Text;HDR=YES;FMT=Delimited\"", filedirectory));
var cmd = new OleDbCommand(String.Format("select * from [" + safeName + "]"), con);
con.Open();
var csvDA = new OleDbDataAdapter(cmd);
var d = new DataTable();
csvDA.Fill(d);
DGVUpload.DataSource = d;
con.Close();
d.Columns.Remove("Symbol");
foreach (DataColumn col in d.Columns)
{
if (col.ColumnName == "Ric Code")
col.ColumnName = "Symbol";
else if (col.ColumnName == "AveragePrice")
col.ColumnName = "Avg_Price";
else if (col.ColumnName == "Accounts")
col.ColumnName = "ClientAcct";
else if (col.ColumnName == "Executed")
col.ColumnName = "Quantity";
} // After this line datatable d resets to null
// MoreCode...
}
Your code snippet has two declarations of DataTable d:
Public DataTable d = new DataTable(); <---- here
private void btnCSVgetter_Click(object sender, EventArgs e)
{
emptyDataGrid();
OpenFileDialog csv = new OpenFileDialog();
csv.Title = "Select CSV to Upload";
csv.DefaultExt = "*.csv";
csv.Filter = "CSV files| *.csv";
if (csv.ShowDialog() == DialogResult.OK)
{
string safeName = csv.SafeFileName;
string filename = csv.FileName;
string filedirectory = csv.FileName.Substring(0, filename.IndexOf(safeName));
if (IsFileLocked(filename) == true) { MessageBox.Show("File is in use by another user, close and try again"); return; }
OleDbConnection con = new OleDbConnection(String.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Text;HDR=YES;FMT=Delimited\"", filedirectory));
OleDbCommand cmd = new OleDbCommand(String.Format("select * from [" + safeName + "]"), con);
con.Open();
OleDbDataAdapter csvDA = new OleDbDataAdapter(cmd);
DataTable d = new DataTable(); <----- here
csvDA.Fill(d);
When you do this, the inner if statement is operating on the local d variable, not the class variable declared outside the method. Once the local d goes out of scope, the only d available to you is the one at the class level, which is empty.

How to compare 2 excel sheet column values and get the similarties in c# using data table

I want to make compare button which compare 2 selected columns from combobox and get the similarities and export them to another excel sheet using datatable in c# .
#region Properties
public string Directory { get; set; }
public string FirstFile { get; set; }
public string FirstFileSheetName { get; set; }
public string SecondFile { get; set; }
public string SecondFileSheetName { get; set; }
public DataTable ReturnDataSet { get; set; }
public bool Excel2007 { get; set; }
public bool UseHeader { get; set; }
#endregion
#region Constructor
public ExcelHandler() { }
public ExcelHandler(string Dir, string File1, string File1SheetName, string File2, string File2SheetName)
{
this.Directory = Dir;
this.FirstFile = File1;
this.SecondFile = File2;
this.FirstFileSheetName = File1SheetName;
this.SecondFileSheetName = File2SheetName;
}
#endregion
#region Match Files
public DataTable CheckExcelFiles()
{
DataTable dtRet = new DataTable();
//Read the first excel
try
{
//Read the excel
DataTable dt1 = GetDataTableFromExcel(this.Directory, this.FirstFile, this.FirstFileSheetName);
DataTable dt2 = GetDataTableFromExcel(this.Directory, this.SecondFile, this.SecondFileSheetName);
//Compare two
dtRet = getDifferentRecords(dt1, dt2);
}
catch (Exception ex) { }
return dtRet;
}
//Overload method to write to csv
public void CheckExcelFiles(string strFilePath)
{
DataTable dtRet = new DataTable();
//Read the first excel
try
{
//Read the excel
DataTable dt1 = GetDataTableFromExcel(this.Directory, this.FirstFile, this.FirstFileSheetName);
DataTable dt2 = GetDataTableFromExcel(this.Directory, this.SecondFile, this.SecondFileSheetName);
//Compare two
dtRet = getDifferentRecords(dt1, dt2);
ExportDataTableToExcel(dtRet, strFilePath);
}
catch (Exception ex) { }
}
//Get Datatable reading Excel
private DataTable GetDataTableFromExcel(string strDir, string strFileName, string strSheetName)
{
var fileName = string.Format("{0}\\" + strFileName, strDir);
string connectionString;
if (Excel2007)
//read a 2007 file
connectionString = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 8.0;HDR=" + (UseHeader == true ? "YES" : "NO") + ";\"", fileName);
else
//read a 97-2003 file
connectionString = string.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties=\"Excel 8.0;HDR=" + (UseHeader == true ? "YES" : "NO") + ";\"", fileName);
//var connectionString = string.Format("Provider=Microsoft.Jet.OLEDB.4.0; data source={0}; Extended Properties=Excel 8.0;", fileName);
var adapter = new OleDbDataAdapter("SELECT * FROM [" + strSheetName + "$]", connectionString);
var ds = new DataSet();
adapter.Fill(ds, fileName + strSheetName);
return ds.Tables[fileName + strSheetName];
}
//Compare datatables
private DataTable CompareDataTable(DataTable A, DataTable B)
{
A.PrimaryKey = new DataColumn[] { A.Columns["PK"] };
B.PrimaryKey = new DataColumn[] { B.Columns["PK"] };
A.Merge(B, true); // this will add to A any records that are in B but not A
A.AcceptChanges();
return A.GetChanges(DataRowState.Added); // returns records originally only in B
}
//Provided here http://social.msdn.microsoft.com/Forums/en-US/csharpgeneral/thread/23703a85-20c7-4759-806a-fabf4e9f5be6/
//Provided by Guo Surfer
#region Compare two DataTables and return a DataTable with DifferentRecords
/// <summary>
/// Compare two DataTables and return a DataTable with DifferentRecords
/// </summary>
/// <param name="FirstDataTable">FirstDataTable</param>
/// <param name="SecondDataTable">SecondDataTable</param>
/// <returns>DifferentRecords</returns>
public DataTable getDifferentRecords(DataTable FirstDataTable, DataTable SecondDataTable)
{
//Create Empty Table
DataTable ResultDataTable = new DataTable("ResultDataTable");
//use a Dataset to make use of a DataRelation object
using (DataSet ds = new DataSet())
{
//Add tables
ds.Tables.AddRange(new DataTable[] { FirstDataTable.Copy(), SecondDataTable.Copy() });
//Get Columns for DataRelation
DataColumn[] firstColumns = new DataColumn[ds.Tables[0].Columns.Count];
for (int i = 0; i < firstColumns.Length; i++)
{
firstColumns[i] = ds.Tables[0].Columns[i];
}
DataColumn[] secondColumns = new DataColumn[ds.Tables[1].Columns.Count];
for (int i = 0; i < secondColumns.Length; i++)
{
secondColumns[i] = ds.Tables[1].Columns[i];
}
//Create DataRelation
DataRelation r1 = new DataRelation(string.Empty, firstColumns, secondColumns, false);
ds.Relations.Add(r1);
DataRelation r2 = new DataRelation(string.Empty, secondColumns, firstColumns, false);
ds.Relations.Add(r2);
//Create columns for return table
for (int i = 0; i < FirstDataTable.Columns.Count; i++)
{
ResultDataTable.Columns.Add(FirstDataTable.Columns[i].ColumnName, FirstDataTable.Columns[i].DataType);
}
//If FirstDataTable Row not in SecondDataTable, Add to ResultDataTable.
ResultDataTable.BeginLoadData();
foreach (DataRow parentrow in ds.Tables[0].Rows)
{
DataRow[] childrows = parentrow.GetChildRows(r1);
if (childrows == null || childrows.Length == 0)
ResultDataTable.LoadDataRow(parentrow.ItemArray, true);
}
//If SecondDataTable Row not in FirstDataTable, Add to ResultDataTable.
foreach (DataRow parentrow in ds.Tables[1].Rows)
{
DataRow[] childrows = parentrow.GetChildRows(r2);
if (childrows == null || childrows.Length == 0)
ResultDataTable.LoadDataRow(parentrow.ItemArray, true);
}
ResultDataTable.EndLoadData();
}
return ResultDataTable;
}
#endregion
private void ExportDataTableToExcel(DataTable dt, string strFilePath)
{
// Create the CSV file to which grid data will be exported.
StreamWriter sw = new StreamWriter(strFilePath, false);
// First we will write the headers.
//DataTable dt = m_dsProducts.Tables[0];
int iColCount = dt.Columns.Count;
for (int i = 0; i < iColCount; i++)
{
sw.Write(dt.Columns[i]);
if (i < iColCount - 1)
{
sw.Write(",");
}
}
sw.Write(sw.NewLine);
// Now write all the rows.
foreach (DataRow dr in dt.Rows)
{
for (int i = 0; i < iColCount; i++)
{
if (!Convert.IsDBNull(dr[i]))
{
sw.Write(dr[i].ToString());
}
if (i < iColCount - 1)
{
sw.Write(",");
}
}
sw.Write(sw.NewLine);
}
sw.Close();
}
#endregion

Clear Datatable

I am trying to refresh the datatablewith new content after click the button but it again shows the previous values also. I tried clear() but it doesn't work for me
protected void btnListItems_Click(object sender, EventArgs e)
{
lblMessage.Visible = false;
//lblEnddatse.Visible = true;
Boolean status = true;
Util objUtil = new Util();
String Message = "";
DateTime SDate = new DateTime();
DateTime EDate = new DateTime();
string str = "";
DataTable tbl = new DataTable();
DataTable dt = new DataTable();
DataRow dr;
String[] s1;
dt.Clear();
//DirectoryInfo d = new DirectoryInfo();
s1 = Directory.GetFiles(#"C:/TextFiles");
for (int i = 0; i <= s1.Length - 1; i++)
{
if (i == 0)
{
//Add Data Grid Columns with name
dt.Columns.Add("FileName");
dt.Columns.Add("GeneratedTime");
}
//Get each file information
FileInfo f = new FileInfo(s1[i]);
FileSystemInfo f1 = new FileInfo(s1[i]);
dr = dt.NewRow();
//Get File name of each file name
dr["FileName"] = f1.Name;
dr["GeneratedTime"] = f1.CreationTime.Date.ToString("dd/MM/yyyy");
string a = f1.CreationTime.Date.ToString("dd/MM/yyyy");
//Insert collected file details in Datatable
string fromdate = txtFromDate.Text.ToString();
string todate = txtToDate.Text.ToString();
if ((DateTime.ParseExact(a.ToString(),"dd/MM/yyyy",System.Globalization.CultureInfo.InvariantCulture)) >= DateTime.ParseExact(fromdate.ToString(),"dd/MM/yyyy",System.Globalization.CultureInfo.InvariantCulture))
{
if ((DateTime.ParseExact(a.ToString(), "dd/MM/yyyy", System.Globalization.CultureInfo.InvariantCulture)) <= DateTime.ParseExact(todate.ToString(), "dd/MM/yyyy", System.Globalization.CultureInfo.InvariantCulture))
{
dt.Rows.Add(dr);
}
}
if ((f.Length / 1024) > 5000)
{
lblMessage.Text = "" + f1.Name + " had reach its size limit.";
}
else
{ }
}
if (dt.Rows.Count > 0)
{
gvFileGenStatus.DataSource = dt;
gvFileGenStatus.DataBind();
}
}
How can I refresh the datagridview displayed data every time I click button after I switch the date.
Thanks For the help in advance..
Try:
gvFileGenStatus.Rows.Clear();
dt.Dispose();
or in
DataTable dt_null = new DataTable();
if (dt.Rows.Count > 0)
{
gvFileGenStatus.DataSource = dt_null;
gvFileGenStatus.DataBind();
}

How do i clear session?

I'm working with entity framework and right now I'm saving two assignments and want to show them to my gridview.
Here I'm saving them to my database table and show them in the gridview:
The code here:
protected void ButtonAddAssignmentClick(object sender, EventArgs e)
{
Session.Remove("DataTable");
//Add to DB and show in gridview
using (var db = new KnowItCvdbEntities())
{
SPWeb theSite = SPControl.GetContextWeb(Context);
SPUser theUser = theSite.CurrentUser;
string strUserName = theUser.LoginName;
var theEmplAssignment = (
from p
in db.EMPLOYEES
where p.username == strUserName
select p).FirstOrDefault();
_emp = theEmplAssignment;
if (_emp != null)
{
//Create assignment
var myAssignment = new EMPLOYEES_ASSIGNMENT
{
assignment_id = new Random().Next(),
employee_id = _emp.employee_id,
reference_name = TextBoxReference.Text,
company_name = TextBoxCompanyName.Text,
sector = TextBoxSector.Text,
area = TextBoxArea.Text,
from_date = TextBoxFromDate.Text,
to_date = TextBoxToDate.Text,
description = TextBoxDesc.Text,
};
//Create assignment tools
for (int i = 0; i < ListBoxAssignmentTools.Items.Count; i++)
{
var myTool = new ASSIGNMENT_TOOLS
{
assignment_tools_id = new Random().Next(),
assignment_id = myAssignment.assignment_id,
employee_id = myAssignment.employee_id,
tool_name = ListBoxAssignmentTools.Items[i].ToString()
};
myAssignment.ASSIGNMENT_TOOLS.Add(myTool);
}
//Create assignment technology
for (int i = 0; i < ListBoxAssignmentTechnology.Items.Count; i++)
{
var myTech = new ASSIGNMENT_TECHNOLOGY
{
assignment_technology_id = new Random().Next(),
assignment_id = myAssignment.assignment_id,
employee_id = myAssignment.employee_id,
technology_name = ListBoxAssignmentTechnology.Items[i].ToString()
};
myAssignment.ASSIGNMENT_TECHNOLOGY.Add(myTech);
}
//Add assignment to db
_emp.EMPLOYEES_ASSIGNMENT.Add(myAssignment);
db.SaveChanges();
//Populate gridview
var dt = new DataTable();
if (Session["DataTable"] != null)
{
dt = (DataTable)Session["DataTable"];
}
else
{
dt.Columns.Add("Company name");
dt.Columns.Add("Sector");
dt.Columns.Add("Area");
dt.Columns.Add("From");
dt.Columns.Add("To");
dt.Columns.Add("Tools");
dt.Columns.Add("Technology");
dt.Columns.Add("Description");
dt.Columns.Add("Reference");
dt.Rows.Clear();
}
DataRow dr = dt.NewRow();
dr["Company name"] = TextBoxCompanyName.Text;
dr["Sector"] = TextBoxSector.Text;
dr["Area"] = TextBoxArea.Text;
dr["From"] = TextBoxFromDate.Text;
dr["To"] = TextBoxToDate.Text;
dr["Description"] = TextBoxDesc.Text;
dr["Reference"] = TextBoxReference.Text;
string sToolsValue = string.Empty;
for (int i = 0; i < ListBoxAssignmentTools.Items.Count; i++)
{
sToolsValue += ListBoxAssignmentTools.Items[i] + " ";
}
dr["Tools"] = sToolsValue;
string sTechValue = string.Empty;
for (int i = 0; i < ListBoxAssignmentTechnology.Items.Count; i++)
{
sTechValue += ListBoxAssignmentTechnology.Items[i] + " ";
}
dr["Technology"] = sTechValue;
dt.Rows.Add(dr);
Session["DataTable"] = dt;
//Add to gridview
GridViewShowAssignments.DataSource = dt;
GridViewShowAssignments.DataBind();
TextBoxCompanyName.Text = string.Empty;
TextBoxArea.Text = string.Empty;
TextBoxSector.Text = string.Empty;
TextBoxFromDate.Text = string.Empty;
TextBoxToDate.Text = string.Empty;
TextBoxDesc.Text = string.Empty;
TextBoxReference.Text = string.Empty;
ListBoxAssignmentTools.Items.Clear();
ListBoxAssignmentTechnology.Items.Clear();
}
}
}
And I'm using a method on page load that retrieves all assignments on the current logged in user and showing it on the gridview.
But the gridview is populating duplicates! I suspect that I must clear my session on page load but I don't really know how to do it.
The method code:
//Get assignment from db and populate gridview
private void GetEmployeeAssignment(EMPLOYEE theEmpl)
{
Session.Remove("DataTable");
using (var db = new KnowItCvdbEntities())
{
if (_emp != null)
{
var assignmentList = from p in db.EMPLOYEES_ASSIGNMENT.AsEnumerable()
join at in db.ASSIGNMENT_TOOLS.AsEnumerable() on p.assignment_id equals at.assignment_id
join ate in db.ASSIGNMENT_TECHNOLOGY.AsEnumerable() on p.assignment_id equals ate.assignment_id
where p.employee_id == theEmpl.employee_id
select new EmployeeAssignmentInfo
{
CompanyName = p.company_name,
AssignmentId = p.assignment_id,
Area = p.area,
From = p.from_date,
To = p.to_date,
Description = p.description,
Sector = p.sector,
Reference = p.reference_name,
ToolName = at.tool_name,
AssignmentToolsId = at.assignment_tools_id,
TechnologyName = ate.technology_name,
AssignmentTechnologyId = ate.assignment_technology_id
};
foreach (var vAssignment in assignmentList)
{
//Populate gridview
var dt = new DataTable();
if (Session["DataTable"] != null)
{
dt = (DataTable)Session["DataTable"];
}
else
{
dt.Columns.Add("Company name");
dt.Columns.Add("Sector");
dt.Columns.Add("Area");
dt.Columns.Add("From");
dt.Columns.Add("To");
dt.Columns.Add("Tools");
dt.Columns.Add("Technology");
dt.Columns.Add("Description");
dt.Columns.Add("Reference");
dt.Rows.Clear();
}
DataRow dr = dt.NewRow();
dr["Company name"] = vAssignment.CompanyName;
dr["Sector"] = vAssignment.Sector;
dr["Area"] = vAssignment.Area;
dr["From"] = vAssignment.From;
dr["To"] = vAssignment.To;
dr["Description"] = vAssignment.Description;
dr["Reference"] = vAssignment.Reference;
dr["Tools"] = vAssignment.ToolName + " ";
dr["Technology"] = vAssignment.TechnologyName + " ";
dt.Rows.Add(dr);
Session["DataTable"] = dt;
GridViewShowAssignments.DataSource = dt;
GridViewShowAssignments.DataBind();
}
}
else
{
LabelPleaseRegister.Visible = true;
LabelPleaseRegister.Text = "Please register your personal information";
PanelRegisterCv.Visible = false;
PanelRegisterPersonalInfo.Visible = false;
}
}
}
Page load:
protected void Page_Load(object sender, EventArgs e)
{
SPWeb theSite = SPControl.GetContextWeb(Context);
SPUser theUser = theSite.CurrentUser;
string strUserName = theUser.LoginName;
LabelUsername.Text = strUserName;
if (!IsPostBack)
{
_emp = GetEmployee(strUserName);
GetEmployeeAssignment(_emp);
}
}
Just do
Session["DataTable"] = null;
or
Session.Remove("DataTable")
Update your code like:
//Get assignment from db and populate gridview
private void GetEmployeeAssignment(EMPLOYEE theEmpl)
{
Session["DataTable"]=null;
using (var db = new KnowItCvdbEntities())
{
if (_emp != null)
{
var assignmentList = from p in db.EMPLOYEES_ASSIGNMENT.AsEnumerable()
join at in db.ASSIGNMENT_TOOLS.AsEnumerable() on p.assignment_id equals at.assignment_id
join ate in db.ASSIGNMENT_TECHNOLOGY.AsEnumerable() on p.assignment_id equals ate.assignment_id
where p.employee_id == theEmpl.employee_id
select new EmployeeAssignmentInfo
{
CompanyName = p.company_name,
AssignmentId = p.assignment_id,
Area = p.area,
From = p.from_date,
To = p.to_date,
Description = p.description,
Sector = p.sector,
Reference = p.reference_name,
ToolName = at.tool_name,
AssignmentToolsId = at.assignment_tools_id,
TechnologyName = ate.technology_name,
AssignmentTechnologyId = ate.assignment_technology_id
};
var dt = new DataTable();
foreach (var vAssignment in assignmentList)
{
//Populate gridview
if (Session["DataTable"] != null)
{
dt = (DataTable)Session["DataTable"];
}
else
{
dt.Columns.Add("Company name");
dt.Columns.Add("Sector");
dt.Columns.Add("Area");
dt.Columns.Add("From");
dt.Columns.Add("To");
dt.Columns.Add("Tools");
dt.Columns.Add("Technology");
dt.Columns.Add("Description");
dt.Columns.Add("Reference");
dt.Rows.Clear();
}
DataRow dr = dt.NewRow();
dr["Company name"] = vAssignment.CompanyName;
dr["Sector"] = vAssignment.Sector;
dr["Area"] = vAssignment.Area;
dr["From"] = vAssignment.From;
dr["To"] = vAssignment.To;
dr["Description"] = vAssignment.Description;
dr["Reference"] = vAssignment.Reference;
dr["Tools"] = vAssignment.ToolName + " ";
dr["Technology"] = vAssignment.TechnologyName + " ";
dt.Rows.Add(dr);
}
Session["DataTable"] = dt;
GridViewShowAssignments.DataSource = dt;
GridViewShowAssignments.DataBind();
}
else
{
LabelPleaseRegister.Visible = true;
LabelPleaseRegister.Text = "Please register your personal information";
PanelRegisterCv.Visible = false;
PanelRegisterPersonalInfo.Visible = false;
}
}
}
Best Regards

Categories