compare two datatable in c# - c#

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();

Related

Change for loop to forEach

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;
}

C# How to handle NULL json values? Getting and InvalidOperationException: Cannot access child value on > Newtonsoft.Json.Linq.JValue

I am having trouble handling nulls in my json file. As you can see in the following photo the null value is under player:
This unfortunately is causing the following InvalidOperationException:
System.InvalidOperationException: Cannot access child value on
Newtonsoft.Json.Linq.JValue.
at Newtonsoft.Json.Linq.JToken.get_Item(Object key)
at WindowsFormsApplication2.Starting_Lineups.StartingLineups() in C:\Users\Administrator\documents\visual studio
2015\Projects\WindowsFormsApplication2\WindowsFormsApplication2\Starting
Lineups.cs:line 97
I tried the following How to ignore a property in class if null, using json.net but have been unsuccessful.
JSON:
{"gamestartinglineup":{"lastUpdatedOn":"2017-10-24 11:41:12 AM","game":{"id":"42120","date":"2017-10-24","time":"7:30PM","awayTeam":{"ID":"83","City":"New York","Name":"Knicks","Abbreviation":"NYK"},"homeTeam":{"ID":"82","City":"Boston","Name":"Celtics","Abbreviation":"BOS"},"location":"TD Garden"},"teamLineup":[{"team":{"ID":"83","City":"New York","Name":"Knicks","Abbreviation":"NYK"},"expected":{"starter":[{"position":"Bench8","player":null},{"position":"Starter1","player":{"ID":"9087","LastName":"Hardaway Jr.","FirstName":"Tim","JerseyNumber":"3","Position":"SG"}},{"position":"Starter2","player":{"ID":"9373","LastName":"Porzingis","FirstName":"Kristaps","JerseyNumber":"6","Position":"PF"}},{"position":"Starter5","player":{"ID":"9518","LastName":"Sessions","FirstName":"Ramon","JerseyNumber":"1","Position":"PG"}},{"position":"Starter3","player":{"ID":"9396","LastName":"Kanter","FirstName":"Enes","JerseyNumber":"0","Position":"C"}},{"position":"Starter4","player":{"ID":"9127","LastName":"Lee","FirstName":"Courtney","JerseyNumber":"1","Position":"SG"}},{"position":"Bench1","player":{"ID":"9148","LastName":"McDermott","FirstName":"Doug","JerseyNumber":"20","Position":"SF"}},{"position":"Bench2","player":{"ID":"9376","LastName":"O'Quinn","FirstName":"Kyle","JerseyNumber":"9","Position":"PF"}},{"position":"Bench3","player":{"ID":"9245","LastName":"Beasley","FirstName":"Michael","JerseyNumber":"9","Position":"F"}},{"position":"Bench4","player":{"ID":"10102","LastName":"Baker","FirstName":"Ron","JerseyNumber":"31","Position":"G"}},{"position":"Bench5","player":null},{"position":"Bench6","player":null},{"position":"Bench7","player":null}]},"actual":null},{"team":{"ID":"82","City":"Boston","Name":"Celtics","Abbreviation":"BOS"},"expected":{"starter":[{"position":"Bench8","player":null},{"position":"Starter1","player":{"ID":"13730","LastName":"Tatum","FirstName":"Jayson","JerseyNumber":"0","Position":"F"}},{"position":"Starter2","player":{"ID":"9082","LastName":"Horford","FirstName":"Al","JerseyNumber":"15","Position":"C"}},{"position":"Starter5","player":{"ID":"9157","LastName":"Irving","FirstName":"Kyrie","JerseyNumber":"11","Position":"PG"}},{"position":"Starter3","player":{"ID":"9211","LastName":"Baynes","FirstName":"Aron","JerseyNumber":"12","Position":"C"}},{"position":"Starter4","player":{"ID":"10090","LastName":"Brown","FirstName":"Jaylen","JerseyNumber":"7","Position":"SF"}},{"position":"Bench1","player":{"ID":"13777","LastName":"Theis","FirstName":"Daniel","JerseyNumber":"27","Position":"PF"}},{"position":"Bench2","player":{"ID":"9105","LastName":"Rozier","FirstName":"Terry","JerseyNumber":"12","Position":"PG"}},{"position":"Bench3","player":{"ID":"13770","LastName":"Nader","FirstName":"Abdel","JerseyNumber":"28","Position":"SF"}},{"position":"Bench4","player":{"ID":"9120","LastName":"Larkin","FirstName":"Shane","JerseyNumber":"8","Position":"PG"}},{"position":"Bench5","player":{"ID":"13778","LastName":"Yabusele","FirstName":"Guerschon","JerseyNumber":"30","Position":"PF"}},{"position":"Bench6","player":{"ID":"13771","LastName":"Bird","FirstName":"Jabari","JerseyNumber":"26","Position":"SG"}},{"position":"Bench7","player":null}]},"actual":null}]}}
Code:
public void StartingLineups()
{
upass.upass up = new upass.upass();
string address3 = "https://api.mysportsfeeds.com/v1.1/pull/nba/2017-2018-regular/game_startinglineup.json?gameid=" + dateTimePicker1.Text + comboBox2.Text;
var w3 = new WebClient();
w3.UseDefaultCredentials = true;
w3.Credentials = new NetworkCredential(up.username, up.password);
var result3 = w3.DownloadString(address3);
var obj3 = JObject.Parse(result3);
StartingLineup.startinglineup sl = new StartingLineup.startinglineup();
try
{
foreach (JToken child in obj3 ["gamestartinglineup"]["teamLineup"])
{
foreach (JToken sub in child["expected"]["starter"])
{
JsonConvert.SerializeObject(sub,
Newtonsoft.Json.Formatting.None,
new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore
});
sl.player = sub["player"]["FirstName"].ToString() + " " + sub["player"]["LastName"].ToString();
sl.team = child["team"]["City"].ToString() + " " + child["team"]["Name"].ToString();
sl.position = sub["position"].ToString();
sl.playerpositon = sub["player"]["Position"].ToString();
DataRow row = dt.NewRow();
row["Team"] = sl.team;
row["Player"] = sl.player;
row["Position"] = sl.playerpositon;
if (sl.position.Contains("Starter"))
{
row["Role"] = sl.position;
}
else
{
row["Role"] = "NOPE";
}
dt.Rows.Add(row);
}
dataGridView1.DataSource = dt;
DataRow[] drr = dt.Select("Role='NOPE'");
for (int i = 0; i < drr.Length; i++)
drr[i].Delete();
dt.AcceptChanges();
}
}
catch (Exception e)
{
MessageBox.Show(e.ToString());
}
}
Consider this, when checking for nullable values (Value<T>(Object key)):
var testObj = new Newtonsoft.Json.Linq.JObject();
if (testObj.TryGetValue("player", out Newtonsoft.Json.Linq.JToken token)) {
string yourString = token.Value<string>("FirstName"); // can be null
int? yourNullableInt = token.Value<int?>("AnyNumber"); // can be null
int yourInt = token.Value<int?>("AnyNumber") ?? 0; // can be 0 if null
int yourInt = token.SelectToken("firstLayer")?.SelectToken("secondLayer")?.Value<int?>("anyNumber") ?? 0; // return value by path
}
SelectToken is also applicable on Newtonsoft.Json.Linq.JObject.

CSV to GridView than CRUD operations

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>()))
));

insert only new data instead duplicate the existing data

I have this code running calling the data from the core system,
public int MuatTurunMTS(hopesWcfRef.Manifest2 entParam, string destination, int capacity)
{
try
{
EL.iSeriesWcf.IiSeriesClient iClient = new iSeriesWcf.IiSeriesClient();
EL.iSeriesWcf.Manifest2 manifest2 = new iSeriesWcf.Manifest2();
manifest2 = iClient.GetManifest2(entParam.NOKT, destination, capacity);
DataTable dt = new DataTable();
dt = manifest2.Manifest2Table;
List<hopesWcfRef.Manifest2> LstManifest2 = new List<hopesWcfRef.Manifest2>();
for (int i = 0; i < dt.Rows.Count; i++)
{
hopesWcfRef.Manifest2 newDataRow = new hopesWcfRef.Manifest2();
newDataRow.NOPASPOT = dt.Rows[i][1].ToString();
newDataRow.NOKT = dt.Rows[i][0].ToString();
newDataRow.KOD_PGKT = dt.Rows[i][2].ToString();
newDataRow.KOD_KLGA = dt.Rows[i][3].ToString();
newDataRow.NAMA = dt.Rows[i][4].ToString();
newDataRow.TKHLAHIR = (dt.Rows[i][5].ToString() == "1/1/0001 12:00:00 AM" ? DateTime.Now : Convert.ToDateTime(dt.Rows[i][5])); //Convert.ToDateTime(dt.Rows[i][5]);
newDataRow.JANTINA = dt.Rows[i][6].ToString();
newDataRow.WARGANEGARA = dt.Rows[i][7].ToString();
newDataRow.JNS_JEMAAH = dt.Rows[i][8].ToString();
newDataRow.NO_SIRI = dt.Rows[i][9].ToString();
newDataRow.NO_MS = Convert.ToInt16(dt.Rows[i][10]);
newDataRow.BARKOD = dt.Rows[i][13].ToString();
newDataRow.NO_DAFTAR = dt.Rows[i][14].ToString();
//bydefault make cell empty
newDataRow.STS_JEMAAH = "";
newDataRow.SEAT_NO = "";
newDataRow.SEAT_ZONE = "";
newDataRow.BERAT = 0;
newDataRow.JUM_BEG = 0;
LstManifest2.Add(newDataRow);
}
int cntr = 0;
if (LstManifest2.Count != 0)
{
foreach (hopesWcfRef.Manifest2 manifest in LstManifest2)
{
cntr++;
SaveManifestTS(manifest);
}
}
return LstManifest2.Count;
}
catch (Exception ex)
{
throw ex;
}
}
And goes to :
public void SaveManifestTS(hopesWcfRef.Manifest2 manifest)
{
try
{
ent.BeginSaveChanges(SaveChangesOptions.Batch, null, null);
ent.AddObject("Manifest2", manifest);
ent.SaveChanges(SaveChangesOptions.Batch);
}
catch (Exception ex)
{
//Uri u = new Uri(ent.BaseUri + "GetErrorMsg"
// , UriKind.RelativeOrAbsolute);
//string datas = (ent.Execute<string>(u)).FirstOrDefault();
//Exception ex = new Exception(datas);
throw ex;
}
}
When SaveChanges run, if the data exist it will duplicate the entire row,
How to avoid the data being duplicate when insert (savechanges)??????
Many Thanks
What about: Do not insert.
In these cases I am using a MERGE statement that updates existing data (based on primary key) and inserts new data.
Oh, and all the code example you loved to post is totally irrelevant to the question, which is a pure SQL side question. You literally quote your car manual then asking which direction to turn.

How to update a DataTable created on Main Thread by a new thread in C#?

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;

Categories