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);
}
}
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;
}
Need help adding "packages" to Item Fulfillment records to allow CSRs to see which items were shipped out under which tracking numbers. I can instantiate an ItemFulfillment record and an ItemFulfillmentPackageList object but the ItemFulfillmentPackageList object is always null - can't figure out how to add ItemFulfillmentPackage objects to the collection. I've tried various methods to assign to the ItemFulfillmentPackageList object without luck. Creating an array of ItemFulfillmentPakage objects is the latest attempt. Here's the code I have.
foreach (DataRow dr in dt.Rows)
{
try
{
ItemFulfillment ifRecord = new ItemFulfillment();
ifRecord.packageList = new ItemFulfillmentPackageList();
ifRecord.internalId = dr["Item Fulfillment Internal ID"].ToString();
ItemFulfillmentPackage ifp = new ItemFulfillmentPackage();
ifp.packageDescr = dr["Package Description"].ToString();
ifp.packageTrackingNumber = dr["detail_tracking_information"].ToString();
ItemFulfillmentPackageList ifpl = new ItemFulfillmentPackageList();
Object[] objPackages = new Object[1];
objPackages[1] = ifp;
ifpl = (ItemFulfillmentPackageList)objPackages;
ifRecord.packageList = ifpl;
ifpl.replaceAll = false;
WriteResponse res = _service.update(ifRecord);
if (res.status.isSuccess)
{
;
}
else if (res.status.isSuccessSpecified)
{
;
}
else
displayError(res.status.statusDetail);
}
catch (Exception ex)
{
_logger.error(String.Format("Error in updateItemFulfillment DR method. {0}", ex.Message));
throw new Exception(String.Format("Error in updateItemFulfillment DR method. {0}", ex.Message));
}
}
Make sure that you configure your search preferences so that bodyFieldsOnly is true; by default its set to false and it won't load sublist items.
I had the same issue. What I ended up doing is to create the Item Fulfillment transaction, with all related line level information and add this to NetSuite.
After this, I search for the Item Fulfillment that I just added and add the tracking information to the record. I do this by checking which package field is not equal to null and adding the information to that package list.
In my case, only one tracking number is used per order and all packages will contain this. You can modify this to add tracking references as needed.
The variable called "msg" is a shipment notification which contains all shipping information.
My code:
TransactionSearch xactionSearch = new TransactionSearch();
TransactionSearchBasic xactionBasic = new TransactionSearchBasic();
xactionBasic.createdFrom = new SearchMultiSelectField();
xactionBasic.createdFrom.#operator = SearchMultiSelectFieldOperator.anyOf;
xactionBasic.createdFrom.operatorSpecified = true;
xactionBasic.createdFrom.searchValue = new RecordRef[1];
xactionBasic.createdFrom.searchValue[0] = new RecordRef { internalId = "SO Internal ID"};
xactionSearch.basic = xactionBasic;
if (useTba = "true".Equals(_custSettings["login.useTba"]))
login();
SearchResult res = _service.search(xactionSearch);
ReadResponse res2 = new ReadResponse();
for (int i = 0; i < res.recordList.Length; i++)
{
if (res.recordList[i] is ItemFulfillment)
{
if (useTba = "true".Equals(_custSettings["login.useTba"]))
login();
res2 = _service.get(new RecordRef { internalId = ((ItemFulfillment)res.recordList[i]).internalId, type = RecordType.itemFulfillment, typeSpecified = true });
}
}
ItemFulfillment item = (ItemFulfillment)res2.record;
ItemFulfillment NewItem = new ItemFulfillment { internalId = item.internalId };
//Fedex
if (item.packageFedExList != null)
{
if (item.packageFedExList.packageFedEx != null)
{
for (int i = 0; i < item.packageFedExList.packageFedEx.Length; i++)
{
item.packageFedExList.packageFedEx[i].packageTrackingNumberFedEx = msg.trackingRef;
}
}
NewItem.packageFedExList = item.packageFedExList;
}
if (item.packageList != null)
{
if (item.packageList.package != null)
{
for (int i = 0; i < item.packageList.package.Length; i++)
{
item.packageList.package[i].packageTrackingNumber = msg.trackingRef;
}
}
NewItem.packageList = item.packageList;
}
//UPS
if (item.packageUpsList != null)
{
if (item.packageUpsList.packageUps != null)
{
for (int i = 0; i < item.packageUpsList.packageUps.Length; i++)
{
item.packageUpsList.packageUps[i].packageTrackingNumberUps = msg.trackingRef;
}
}
NewItem.packageUpsList = item.packageUpsList;
}
//Usps
if (item.packageUspsList != null)
{
if (item.packageUspsList.packageUsps != null)
{
for (int i = 0; i < item.packageUspsList.packageUsps.Length; i++)
{
item.packageUspsList.packageUsps[i].packageTrackingNumberUsps = msg.trackingRef;
}
}
NewItem.packageUspsList = item.packageUspsList;
}
if (useTba = "true".Equals(_custSettings["login.useTba"]))
login();
_service.update(NewItem);
I have 2 form. MainPage form contains datagridview and fetchTradeReport method to populate/refresh datagrid, while ColumnSettings form use to configure which datagridviewcolumn that user want to be visible or not. I have "Apply Changes" button in ColumnSettings form, and I include fetchTradeReport method in the click event. But, the datagrid still the same and don't change after I clicked it.
This is my fetchTradeReport method
public void fetchTradeReport()
{
try
{
TTransport transport = new TSocket(address, port);
TProtocol protocol = new TBinaryProtocol(transport);
CacheService.Client client = new CacheService.Client(protocol);
transport.Open();
List<string> transactTime = new List<string>();
SearchCriteria criteria = new SearchCriteria();
criteria.Filters = new List<Filter>();
DateTime dt = new DateTime(1970, 1, 1, 0, 0, 0, 0, System.DateTimeKind.Utc);
if (Convert.ToString(tradeStatusCB.Text) != "")
setTradeStatusFilter(criteria, (TradeReportStatus)Enum.Parse(typeof(TradeReportStatus), Convert.ToString(tradeStatusCB.Text)));
if (platformTB.Text != "")
setPlatformFilter(criteria, platformTB.Text);
if (exchangeTB.Text != "")
criteria.Exchange = exchangeTB.Text;
if (productTB.Text != "")
criteria.Product = productTB.Text;
if (accountTB.Text != "")
criteria.Account = accountTB.Text;
if (orderidTB.Text != "")
setOrderIDFilter(criteria, orderidTB.Text);
if (tradereportidTB.Text != "")
setReportIDFilter(criteria, tradereportidTB.Text);
if (tradedateDTP.Text.Length != 1)
criteria.TradeDate = Convert.ToInt32(tradedateDTP.Value.ToString("yyyyMMdd"));
var tradeList = client.getTradeReports(criteria);
tradeGridView.DataSource = tradeList;
foreach (DataGridViewRow row in tradeGridView.Rows)
{
double time = Convert.ToDouble(row.Cells["TransactTime"].Value);
string dtm = dt.AddSeconds(time).ToLocalTime().ToString();
transactTime.Add(dtm);
}
tradeGridView.Columns.Remove("TransactTime");
if(tradeGridView.Columns.Contains("TransactionTime"))
tradeGridView.Columns.Remove("TransactionTime");
tradeGridView.Columns.Add("TransactionTime", "TransactionTime");
tradeGridView.Columns["TransactionTime"].ValueType = typeof(String);
int i = 0;
foreach (DataGridViewRow row in tradeGridView.Rows)
{
row.Cells["TransactionTime"].Value = transactTime[i];
i++;
}
int counter = 0;
string line;
if (File.Exists(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + #"\\ColumnSettings.config"))
{
StreamReader readFile = new StreamReader(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + #"\\ColumnSettings.config");
while ((line = readFile.ReadLine()) != null)
{
string columnName = line.Substring(0, line.Length - 2);
tradeGridView.Columns[columnName].DisplayIndex = counter;
if (line.Split('-').Last() == "1")
tradeGridView.Columns[columnName].Visible = true;
else
tradeGridView.Columns[columnName].Visible = false;
counter++;
}
readFile.Close();
}
else
collectColumnName();
transport.Close();
}
catch (Exception e)
{
MessageBox.Show(e.StackTrace);
}
}
And this is how I call it in "Apply Changes" button click event in ColumnSettings form
new MainPage(GetConnectionString.address, GetConnectionString.port).fetchTradeReport();
Sorry if my English bad. Any help appreciated. Thanks.
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>()))
));
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;