i am making a Job reporter application, and till now what i did is, imported C.S.V file to grid view and displaying it by saving it in a data table, now what i want is,update and save the record back in the c.s.v file, i am not using any S.Q.L or any type of database, is it possible to do this?
please help me, i have to deliver project in two hours.
The project is C# Win forms.
Also help me in how i can serialize it to upload into ftp server.
THE CODE IS here...
private void openProjectToolStripMenuItem_Click_1(object sender, EventArgs e)
{
// int size = -1;
OpenFileDialog ofd = new OpenFileDialog()
{
Title = "Choose a File",
InitialDirectory = #"c:\dev\",
Filter = "Text Files (.txt)|*.txt|XML Files|*.xml|Word Documents (.docx)|*.docx",
RestoreDirectory = true,
Multiselect = false
};
if (ofd.ShowDialog() != System.Windows.Forms.DialogResult.OK)
{
MessageBox.Show("No file selected!");
return;
}
using (StreamReader oStreamReader = new StreamReader(ofd.FileName))
{
try
{
Application.DoEvents();
DataSet ds = new DataSet("ApplicationData");
//some updates in the Datatable
DataTable JobHeaderDataTable = new DataTable("JobHeaderDataTable");
DataTable JobDate = new DataTable("JobDate");
DataTable JobDateItems = new DataTable("JobDateItems");
ds.Tables.Add(JobHeaderDataTable);
ds.Tables.Add(JobDate);
ds.Tables.Add(JobDateItems);
int rowCount = 0;
string[] columnNames = null;
string[] oStreamDataValues = null;
while (!oStreamReader.EndOfStream)
{
string oStreamRowData = oStreamReader.ReadLine().Trim();
if (oStreamRowData.Length > 0)
{
oStreamDataValues = oStreamRowData.Split('-');
if (rowCount == 0 && oStreamDataValues[0].ToString() == "HDR")
{
rowCount = 1;
columnNames = oStreamDataValues;
for (int i = 1; i < columnNames.Length; i++)
{
DataColumn oDataColumn = new DataColumn(columnNames[i].ToUpper(), typeof(string));
oDataColumn.DefaultValue = string.Empty;
JobHeaderDataTable.Columns.Add(oDataColumn);
}
//// For Slider
//txtCompany.Text = oStreamDataValues.GetValue(1).ToString();
//txtLocation.Text = oStreamDataValues.GetValue(2).ToString();
//txtRigName.Text = oStreamDataValues.GetValue(3).ToString();
//txtState.Text = oStreamDataValues.GetValue(4).ToString();
//txtCounty.Text = oStreamDataValues.GetValue(5).ToString();
//txtWellName.Text = oStreamDataValues.GetValue(6).ToString();
//txtTownship.Text = oStreamDataValues.GetValue(7).ToString();
//txtDescription.Text = oStreamDataValues.GetValue(8).ToString();
//txtBentHstSub.Text = oStreamDataValues.GetValue(9).ToString();
//txtBilToBend.Text = oStreamDataValues.GetValue(10).ToString();
//txtPadOD.Text = oStreamDataValues.GetValue(11).ToString();
//txtNBStab.Text = oStreamDataValues.GetValue(11).ToString();
//txtJob_ID.Text = oStreamDataValues.GetValue(12).ToString();
//// For Header
//txtCompanyHeader.Text = oStreamDataValues.GetValue(1).ToString();
//txtLocationHeader.Text = oStreamDataValues.GetValue(2).ToString();
//txtRigNameHeader.Text = oStreamDataValues.GetValue(3).ToString();
//txtStateHeader.Text = oStreamDataValues.GetValue(4).ToString();
//txtCountyHeader.Text = oStreamDataValues.GetValue(5).ToString();
//txtWellNameHeader.Text = oStreamDataValues.GetValue(6).ToString();
//txtTownshipHeader.Text = oStreamDataValues.GetValue(7).ToString();
//txtDescriptionHeader.Text = oStreamDataValues.GetValue(8).ToString();
//txtBentHstSubHeader.Text = oStreamDataValues.GetValue(9).ToString();
//txtBillToBendHeader.Text = oStreamDataValues.GetValue(10).ToString();
//txtPadODHeader.Text = oStreamDataValues.GetValue(11).ToString();
//txtNBStabHeader.Text = oStreamDataValues.GetValue(11).ToString();
//txtJob_IDHeader.Text = oStreamDataValues.GetValue(12).ToString();
}
else
{
DataRow oDataRow = JobHeaderDataTable.NewRow();
for (int i = 1; i < columnNames.Length; i++)
{
oDataRow[columnNames[i]] = oStreamDataValues[i] == null ? string.Empty : oStreamDataValues[i].ToString();
}
JobHeaderDataTable.Rows.Add(oDataRow);
}
}
}
oStreamReader.Close();
oStreamReader.Dispose();
foreach (DataRow dr in JobHeaderDataTable.Rows)
{
dataGridView2.DataSource = JobHeaderDataTable;
dataGridView4.DataSource = JobDate;
dataGridView5.DataSource = JobDateItems;
}
}
catch (IOException)
{
}
}
}
Save yourself some headache and check out, ClosedXML, and create the csv using this answer is available Can I save an EXCEL worksheet as CSV via ClosedXML?.
System.IO.File.WriteAllLines(csvFileName,
worksheet.RowsUsed().Select(row =>
string.Join(";", row.Cells(1, row.LastCellUsed(false).Address.ColumnNumber)
.Select(cell => cell.GetValue<string>()))
));
Related
I am working on a inventory updating program in vs2022 which I am using Gembox Spreadsheet for, It is working right now, but the boss man would like me to try to convert my for loop to a for each loop. The loop is what I am using to update my file.
Current For Loop
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];
//foreach (var row in worksheet.Rows.Skip(1))
//{
// foreach (var cell in row.AllocatedCells)
// {
// string updateValue =
// if(cell.Value == int.TryParse((int)outValue, out int updateValue))
// {
// }
// }
//}
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 = selectedItem.Quantity;
}
if (selectedItem.plateDescription == platedescription)
{
worksheet.Rows[i].Cells[1].Value = selectedItem.Quantity;
}
}
workbook.Save(fullPath, new CsvSaveOptions(CsvType.CommaDelimited));
}
I beleive the forEach would look similar to this
private static List<ItemLine> ReadFile(string fileName, string defaultValueDescription)
{
string path = $".\\Backend Files\\{fileName}";
SpreadsheetInfo.SetLicense("FREE -LIMITED-KEY");
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.Skip(1))
{
var cells = row.AllocatedCells;
var il = new ItemLine();
if (cells.Count == 2)
{
il.Description = cells[0].Value?.ToString() ?? "Description Not Found";
il.Quantity = cells[1].IntValue;
}
else if (cells.Count >= 3)
{
il.Plan = cells[0].Value?.ToString() ?? "Plan Not Found";
il.Description = cells[1].Value?.ToString() ?? "Description Not Found";
il.Quantity = cells[2].IntValue;
}
items.Add(il);
}
return items;
}
I am trying to View a report dynamically from code behind. But when the parameters are changed from dynamic textboxes added in the page. in the report refresh() the data is not changed.
I call sqlDS() and reportBuild() in the !IsPostback.
This method is for defining the sqlDatasource:
protected void sqlDS()
{
string conString, prName = "";
int counter = 0;
Reporting rep = new Reporting();
rep = rep.searchReport(repID_HF.Value);
Reporting repFold = new Reporting();
repFold = repFold.searchFolder(foldID_HF.Value);
if (repFold.FolderName.Split('(')[1] == "Web Reports)")
{
conString = dbSql.connectionStringAll;
prName = dbSql.providerName;
}
else
{
conString = db.connectionStringAll;
prName = db.providerName;
}
SqlDataSource1.ConnectionString = conString;
SqlDataSource1.ProviderName = prName;
string sqlString = System.IO.File.ReadAllText(Server.MapPath("~/Reports/SQLs/" + rep.SqlFile));
sqlString.Replace(System.Environment.NewLine, " ");
SqlDataSource1.SelectCommand = sqlString;
SqlDataSource1.CancelSelectOnNullParameter = false;
Reporting repParam = new Reporting();
allPs = repParam.getAllParamRep(rep.RepID);
foreach (Reporting itemParam in allPs)
{
if (itemParam.ParamType == "Date")
{
SqlDataSource1.SelectParameters.Add(":" + itemParam.ParamName, itemParam.ParamDefaultValue);
counter++;
}
else if (itemParam.ParamType == "Text")
{
SqlDataSource1.SelectParameters.Add(":" + itemParam.ParamName, itemParam.ParamDefaultValue);
counter++;
}
else if (itemParam.ParamType == "Menu")
{
counter++;
}
}
}
This method is for declaring the report properties:
protected void reportBuild()
{
Reporting rep2 = new Reporting();
rep2 = rep2.searchReport(repID_HF.Value);
ReportViewer1.LocalReport.ReportPath = "Reports/RDLC/" + rep2.RdlcFile;
this.ReportViewer1.LocalReport.ReportEmbeddedResource = rep2.RdlcFile;
ReportParameter[] paramss = new ReportParameter[SqlDataSource1.SelectParameters.Count];
for (int i = 0; i < SqlDataSource1.SelectParameters.Count; i++)
{
paramss[i] = new ReportParameter(SqlDataSource1.SelectParameters[i].Name.Split(':')[1], SqlDataSource1.SelectParameters[i].DefaultValue);
}
ReportDataSource rds = new ReportDataSource(rep2.DatasetName.Split('.')[0], SqlDataSource1);
ReportViewer1.LocalReport.DataSources.Clear();
ReportViewer1.LocalReport.DataSources.Add(rds);
//paramss[0] = new ReportParameter("TDATE", SqlDataSource1.SelectParameters[0].DefaultValue);
//paramss[1] = new ReportParameter("CUST_NUM", SqlDataSource1.SelectParameters[1].DefaultValue);
ReportViewer1.LocalReport.SetParameters(paramss);
ReportViewer1.LocalReport.Refresh();
}
In the reportViewer refresh method i try to set the new parameters according to the dynamic textboxes added in the page:
protected void ReportViewer1_ReportRefresh(object sender, System.ComponentModel.CancelEventArgs e)
{
foreach (Control txt in Panel1.Controls)
{
if (txt is TextBox)
{
txts.Add(txt);
}
}
foreach (TextBox txtbox in txts)
{
Reporting repP = new Reporting();
repP = repP.searchParam(txtbox.Attributes["pID"].ToString());
if (repP.ParamType == "Date")
{
SqlDataSource1.SelectParameters[":" + repP.ParamName].DefaultValue = txtbox.Text;
}
else if (repP.ParamType == "Text")
{
SqlDataSource1.SelectParameters[":" + repP.ParamName].DefaultValue = txtbox.Text;
}
}
//Reporting r = new Reporting();
//r = r.searchReport(repID_HF.Value);
//Reporting rep = new Reporting();
//rep = rep.searchReport(repID_HF.Value);
//ReportDataSource rds = new ReportDataSource(rep.DatasetName.Split('.')[0], SqlDataSource1);
//this.ReportViewer1.Reset();
//ReportViewer1.LocalReport.DataSources.Clear();
//ReportViewer1.LocalReport.DataSources.Add(rds);
ReportParameterInfoCollection x = ReportViewer1.LocalReport.GetParameters();
//Response.Redirect(Request.RawUrl);
ReportViewer1.LocalReport.Refresh();
}
I tried debugging and found every thing is working correctly the SQL parameters changed, the Report Parameters also is changed.
so why the data in the report is not changed? Plz help me
I got a better and easier way to solve this problem using this link
http://www.igregor.net/post/2007/12/Adding-Controls-to-an-ASPNET-form-Dynamically.aspx
And you can use array of strings to pass attributes.
I have a global DataTable named 'DTImageList' and an XtraGrid named 'uxImageGrid'. Now there is a Method named 'prcFillImagesVideosAndFiles' in which we bring image data from data base page wise i.e. say 500 rows at a time and we create mannual Pages on top of the Grid by using XtraTabControl depending on the total count of data exists according to search. Say if we get 700 Images then will load only 500 at a time and 2 pages will be created as 'Page 1', 'Page 2'.
But in 'prcFillImagesVideosAndFiles' method, we are not fetching the actual images but only its name, id etc. After this I created a new Thread and invoking a method runner which in turn calls a new method called 'FillImages' in which I look through DTImageList and bring actual image one by one from backend and update row with this image due to which XtraGrid starts showing images one by one.
This process works fine for few minutes i.e. loads 20-25 images and after that it gives 'Cross-thread operation not valid' error.
// My prcFillImagesVideosAndFiles method's Code is:
`if (DTImageList != null)
{
DTImageList.Rows.Clear(); DTImageList.Columns.Clear(); DTImageList = null;
}
string sql = #"select " + top + #" IM.Image_ID,IM.extension,IM.Is_Uploaded,cast(0 as varbinary) 'ActualImage',IM.description 'Description',IM.ContentType,IM.DateTime_Uploaded,IM.FolderName, '' as FilePath
from images as IM where IM.GCRecord is null and IM.Is_Uploaded=1 " + MainCriteria + #" " + Ob + #"";
string sql1 = LayoutPaging(sql);
DTImageList = new DataTable();
DTImageList = FillDataTable(sql1);
DataTable DTdeliv2 = new DataTable();
DTdeliv2.Columns.Add("Image");
DTdeliv2.Columns.Add("UniqueNumber");
DTdeliv2.Columns["Image"].DataType = typeof(Image);
DTdeliv2.Columns["UniqueNumber"].DataType = typeof(int);
DTImageList.Merge(DTdeliv2, true, MissingSchemaAction.Add);
uxImageGrid.DataSource = null;
uxImageGrid.DataSource = DTImageList;
RepositoryItemTextEdit riTextEdit = new RepositoryItemTextEdit();
riTextEdit.Appearance.TextOptions.HAlignment = HorzAlignment.Center;
layoutView1.Columns["Description"].AppearanceCell.TextOptions.HAlignment = HorzAlignment.Center;
riTextEdit.Appearance.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(128)))), ((int)(((byte)(128)))));
riTextEdit.Appearance.Options.UseBackColor = true;
riTextEdit.NullText = "";
uxImageGrid.RepositoryItems.Add(riTextEdit);
layoutView1.Columns["Description"].ColumnEdit = riTextEdit;
riTextEdit.Leave += new EventHandler(riTextEdit_Leave);
riTextEdit.KeyPress += new KeyPressEventHandler(riTextEdit_KeyPress);
RepositoryItemPictureEdit riPictureEdit = new RepositoryItemPictureEdit();
riPictureEdit.SizeMode = PictureSizeMode.Zoom;
riPictureEdit.ShowMenu = false;
riPictureEdit.NullText = " Loading Image";
riPictureEdit.Appearance.Image = Pionero.RetailTherapy.Properties.Resources.mag;
uxImageGrid.RepositoryItems.Add(riPictureEdit);
layoutView1.Columns["Image"].ColumnEdit = riPictureEdit;
riPictureEdit.MouseMove += new MouseEventHandler(riPictureEdit_MouseMove);
riPictureEdit.MouseDown += new MouseEventHandler(riPictureEdit_MouseDown);
layoutView1.Columns["Image"].Caption = "";
int k = DTImageList.Rows.Count;
if (k > 0)
{
DevExpress.Data.Filtering.CriteriaOperator expr1 = new DevExpress.Data.Filtering.BinaryOperator("Is_Uploaded", true);
layoutView1.ActiveFilterCriteria = expr1;
if (pthread != null)
{
StopRunningThread();
}
if (pthread == null || pthread.IsAlive==false)
{
pthread = new Thread(new ThreadStart(runner));
pthread.IsBackground = true;
Is_ThreadNeededtoWork = true;
pthread.Start();
}
else
{
Is_ThreadNeededtoWork = true;
pthread.Start();
}
}`
//The runner method is:
void runner()
{
if (Is_ThreadNeededtoWork == false)
{
if (dtImages != null)
{
dtImages.Rows.Clear(); dtImages.Columns.Clear(); dtImages = null;
}
return;
}
if (Is_ThreadNeededtoWork == true)
{
FillImages();
}
}
// FillImages method's code is:
try
{
if (DTImageList.Rows.Count <= 0) return;
StringBuilder sbImagesNotLoaded = new StringBuilder();
sbImagesNotLoaded.Append("Following images not loaded due to connection: ");
ArrayList lstImage_IDs = new ArrayList();
int NoOfAttempts = 0;
//if (dtImages != null)
//{
for (int i = 0; i < DTImageList.Rows.Count; i++)
{
NoOfAttempts = 0;
V:
string Qry = #" Select Image_ID,image from images where Image_ID = " + DTImageList.Rows[i]["Image_ID"].ToString();
dtImages = FillDataTable(Qry);
if (dtImages != null && dtImages.Rows.Count > 0)
{
if (DTImageList.Rows[i]["image"] == DBNull.Value)
{
// Thread.Sleep(100);
byte[] barr = (byte[])dtImages.Rows[0]["image"];
Image img = Global.byteArrayToImage(barr);
DTImageList.Rows[i]["Image"] = img;
DTImageList.AcceptChanges();
uxImageGrid.RefreshDataSource();
}
}
else
{
// Thread.Sleep(100);
if (Convert.ToInt32(DTImageList.Rows[i]["Image_ID"]) > 0)
if (NoOfAttempts < 3)
{
NoOfAttempts = NoOfAttempts + 1;
goto V;
}
else
{
if (lstImage_IDs.Count > 0)
sbImagesNotLoaded.Append("," + Convert.ToString(DTImageList.Rows[i]["Description"]));
else
sbImagesNotLoaded.Append(Convert.ToString(DTImageList.Rows[i]["Description"]));
lstImage_IDs.Add(DTImageList.Rows[i]["Image_ID"]);
}
}
}
//}
if (lstImage_IDs.Count > 0)
{
for (int i = 0; i < lstImage_IDs.Count; i++)
{
DataRow drImage = DTImageList.Select("Image_ID=" + Convert.ToString(lstImage_IDs[i]) + "").FirstOrDefault();
if (drImage != null)
DTImageList.Rows.Remove(drImage);
}
DTImageList.AcceptChanges();
XtraMessageBox.Show(sbImagesNotLoaded.ToString(), Global.Header, MessageBoxButtons.OK, MessageBoxIcon.Information);
}
EnableDisablePanelControls(true);
if (pthread != null)
{
Is_ThreadNeededtoWork = false;
StopRunningThread();
}
}
catch (ThreadAbortException abortException)
{
}
catch (Exception emmp)
{
EnableDisablePanelControls(true);
//pthread.Abort();
}
finally
{
//Global.StopProg();
}
//StopRunningThread() 's code is:
void StopRunningThread()
{
if (dtImages != null)
{
dtImages.Rows.Clear(); dtImages.Columns.Clear(); dtImages = null;
}
Is_ThreadNeededtoWork = false;
}
Thanks
Vicky
You can try inserting images before you pass it as Datasource to uxImageGrid.
Add image column to DTImageLis.
DTImageList.Columns.Add("Image", typeof(System.Drawing.Image));
Add the image to datatable based on Name,Id etc and bind it to uxImageGrid
uxImageGrid.Datasource=DTImageList;
i m developing a Outlook Add ins using C#. hare i extract all the attachment(in doc or docx) which is attach with selected mail. i have create a button on tool bar using add in.when i click on button then all the attachment with selected mail come in to my database.now my question is that when i click on button that time some processing happens during the processing time i want to show a progress bar on my outlook window untill its finish extraction.Can any one help me to out this problem. here i include code also with extract mails attachment and sent to database
private void ThisApplication_NewMail()
{
DataTable dtImportedData = new DataTable();
Outlook.Explorer currExplorer = this.Application.ActiveExplorer();
Outlook.MAPIFolder folder = this.Application.ActiveExplorer().CurrentFolder;
Outlook.Items inBoxItems = folder.Items;
Outlook.MailItem item = null;
const string destinationDirectory = #"C:\TestFileSave";
if (!Directory.Exists(destinationDirectory))
{
Directory.CreateDirectory(destinationDirectory);
}
dtImportedData.Columns.Add("Select", typeof(bool));
dtImportedData.Columns.Add("Name");
dtImportedData.Columns.Add("Experience");
dtImportedData.Columns.Add("Company Name");
dtImportedData.Columns.Add("Email");
dtImportedData.Columns.Add("Mobile");
dtImportedData.Columns.Add("Date Of Birth");
dtImportedData.Columns.Add("Designation");
dtImportedData.Columns.Add("Location");
dtImportedData.Columns.Add("Qualification");
dtImportedData.Columns.Add("Skill Set");
dtImportedData.Columns.Add("Path");
//DataRow dr = null;
DataRow drExtract = null;
try
{
string strFileName = string.Empty;
Outlook.Selection selections = currExplorer.Selection;
for (int i = 1; i <= selections.Count; ++i)
{
object newEmail = (object)selections[i];
if (newEmail != null && (newEmail is Outlook.MailItem))
{
item = (Outlook.MailItem)newEmail;
if (item.Attachments.Count > 0)
{
for (int j = 1; j <= item.Attachments.Count; j++)
{
if (item.Attachments[j].FileName.Contains(".doc") || item.Attachments[j].FileName.Contains(".docx") || item.Attachments[j].FileName.Contains(".rtf"))
{
string filePath = Path.Combine(destinationDirectory, item.Attachments[j].FileName.ToString());
item.Attachments[j].SaveAsFile(filePath);
string m_Content = ClsWordManager.ReadWordFile(filePath);
drExtract = dtImportedData.NewRow();
ClsResumeExtractor objExtractResume = new ClsResumeExtractor();
drExtract["Select"] = true;
drExtract["Name"] = objExtractResume.ExtractName(m_Content);
drExtract["Email"] = objExtractResume.ExtractEmailAddressesFromString(m_Content);
drExtract["Mobile"] = objExtractResume.ExtractMobile(m_Content);
drExtract["Qualification"] = objExtractResume.ExtractQualification(m_Content);
drExtract["Designation"] = objExtractResume.ExtractDesignation(m_Content);
drExtract["Company Name"] = objExtractResume.ExtractCompanyName(m_Content);
drExtract["Location"] = objExtractResume.ExtractCurrentLocation(m_Content);
drExtract["Date Of Birth"] = objExtractResume.ExtractDateOfBirth(m_Content);
drExtract["Experience"] = objExtractResume.ExtractYearOfExperience(m_Content);
drExtract["Skill Set"] = objExtractResume.ExtractSkillSet(m_Content);
drExtract["Path"] = filePath;
dtImportedData.Rows.Add(drExtract);
}
}
}
else
{
System.Windows.Forms.MessageBox.Show("Select Email which have Attchments..!");
}
}
}
if (dtImportedData.Rows.Count > 0)
{
SaveImportedDataOutlook objSaveImportedDataOutlook = new SaveImportedDataOutlook();
objSaveImportedDataOutlook.grdCandidate.DataSource = dtImportedData;
ClsCommons.OpenDialog(objSaveImportedDataOutlook);
}
}
catch (Exception ex)
{
string errorInfo = (string)ex.Message.Substring(0, 11);
}
}
what would be the best way to compare two data table. i populate two data table reading two different xml and now i need to compare and return the difference in terms of datatable.my compare logic was
private DataTable CompareDataTables(DataTable dtFirst, DataTable dtSecond)
{
int result = 0;
bool flag = false;
DataTable dtNoRows = new DataTable();
dtNoRows.Columns.Add("Result");
DataTable dtDiff = new DataTable();
dtDiff.Columns.Add("Field Name");
dtDiff.Columns.Add("Old Value");
dtDiff.Columns.Add("New Value");
DataRow dr = null;
if (dtFirst.Columns.Count == dtSecond.Columns.Count)
{
for (int i = 0; i <= dtFirst.Columns.Count - 1; i++)
{
try
{
DateTime.Parse(dtFirst.Rows[0][dtFirst.Columns[i].ColumnName.ToString()].ToString().Trim());
flag = true;
}
catch (Exception ex)
{
flag = false;
}
if (!flag)
{
if (dtFirst.Rows[0][dtFirst.Columns[i].ColumnName.ToString()].ToString().Trim().ToUpper() != dtSecond.Rows[0][dtSecond.Columns[i].ColumnName.ToString()].ToString().Trim().ToUpper())
{
dr = dtDiff.NewRow();
dr["Field Name"] = dtFirst.Columns[i].ColumnName.ToString();
dr["Old Value"] = dtFirst.Rows[0][dtFirst.Columns[i].ColumnName.ToString()].ToString().Trim();
dr["New Value"] = dtSecond.Rows[0][dtSecond.Columns[i].ColumnName.ToString()].ToString().Trim();
dtDiff.Rows.Add(dr);
}
}
else
{
result = DateTime.Compare(DateTime.Parse(dtFirst.Rows[0][dtFirst.Columns[i].ColumnName.ToString()].ToString()), DateTime.Parse(dtSecond.Rows[0][dtSecond.Columns[i].ColumnName.ToString()].ToString()));
if (result != 0)
{
dr = dtDiff.NewRow();
dr["Field Name"] = dtFirst.Columns[i].ColumnName.ToString();
dr["Old Value"] = DateTime.Parse(dtFirst.Rows[0][dtFirst.Columns[i].ColumnName.ToString()].ToString().Trim()).ToString("MM/dd/yyyy") + " - " + DateTime.Parse(dtFirst.Rows[0][dtFirst.Columns[i].ColumnName.ToString()].ToString().Trim()).ToString("hh:mm:ss");
dr["New Value"] = DateTime.Parse(dtSecond.Rows[0][dtSecond.Columns[i].ColumnName.ToString()].ToString().Trim()).ToString("MM/dd/yyyy") + " - " + DateTime.Parse(dtSecond.Rows[0][dtSecond.Columns[i].ColumnName.ToString()].ToString().Trim()).ToString("hh:mm:ss");
dtDiff.Rows.Add(dr);
}
flag = false;
}
}
}
return dtDiff;
}
my code is working fine but i need to the is there any best way out. please guide me.
you can use LINQ to comparing tables values(two table must have the same structure)
bool flag = false;
if (dtFirst.Columns.Count == dtSecond.Columns.Count)
{
for (int i = 0; i <= dtFirst.Columns.Count - 1; i++)
{
String colName = dtFirst.Columns[i].ColumnName;
var colDataType = dtFirst.Columns[i].DataType.GetType();
var colValue = dtFirst.Columns[i];
flag = dtSecond.AsEnumerable().Any(T => typeof(T).GetProperty(colName).GetValue(T, typeof(colDataType)) == colValue);
}
}
var qry1 = dtDuplicate.AsEnumerable().Select(a => new { SchoolID = a["SchoolMID"].ToString()});
var qry2 = dsValadateSchoolInfo.Tables[1].AsEnumerable().Select(b => new { SchoolID = ["SchoolMID"].ToString() });
var exceptAB = qry1.Except(qry2);
DataTable dtMisMatch = (from a in dtDuplicate.AsEnumerable()
join ab in exceptAB on a["SchoolMID"].ToString() equals ab.SchoolID
select a).CopyToDataTable();