searching an array for specific criteria and displaying - c#

Hi I am completely new to C# programming and I am getting stuck on my code. My program is to ask the user for a city or zip code, the amount of beds/baths they want, and their price range. I need to to search through my array and then display all the houses that meet their criteria (think Zillow, the website). My code currently displays random houses that do not meet any of the criteria I selected for the home. HELP!
for (int a = 0; a < HOUSES; ++a)
{
if (zipChecker == zip[a]) // check zip code
{
found = true;
foundPosition = a;
}
if (BtnBath1.Checked) // check baths
{
if (bath[a] > 0 && bath[a] <= 1)
{
found = true;
foundPosition = a;
}
}
else if (BtnBath2.Checked) // check baths
{
if (bath[a] > 1 && bath[a] <= 2)
{
found = true;
foundPosition = a;
}
}
else if (BtnBath3.Checked) // check baths
{
if (bath[a] > 2 && bath[a] <= 3)
{
found = true;
foundPosition = a;
}
}
else if (BtnBath4.Checked) // check baths
{
if (bath[a] > 3)
{
found = true;
foundPosition = a;
}
}
if (BtnBed1.Checked) // check bed
{
if (bed[a] > 0 && bed[a] <= 1)
{
found = true;
foundPosition = a;
}
}
else if (BtnBed2.Checked) //check bed
{
if (bed[a] > 1 && bed[a] <= 2)
{
found = true;
foundPosition = a;
}
}
else if (BtnBed3.Checked) //check bed
{
if (bed[a] > 2 || bed[a] <= 3)
{
found = true;
foundPosition = a;
}
}
else if (BtnBed4.Checked) //check bed
{
if (bed[a] > 3)
{
found = true;
foundPosition = a;
}
}
if (BoxPrice1.Checked) //check price
{
if (price[a] < 200000 && price[a] > 300000)
{
found = false;
foundPosition = a;
}
}
if (BoxPrice2.Checked) //check price
{
if (price[a] < 300000 && price[a] > 400000)
{
found = false;
foundPosition = a;
}
}
if (BoxPrice3.Checked) //check price
{
if (price[a] < 400000 && price[a] > 500000)
{
found = false;
foundPosition = a;
}
}
if (BoxPrice4.Checked) //check price
{
if (price[a] < 500000)
{
found = false;
foundPosition = a;
}
}
}
if (found)
{
label1.Text +=
string.Format("Bed: {0}, Bath:{1}, Asking Price:{2}, City:{3}, SQFT:{4}, " +
"Zip Code:{5}, Year:{6}", bed[foundPosition], bath[foundPosition],
price[foundPosition].ToString("c2"), city[foundPosition],
sqft[foundPosition].ToString("n0"), zip[foundPosition],
year[foundPosition]);
}
else
{
label1.Text = ("Sorry there were no houses that met your criteria");
}

int printcount = 0;
for (int a = 0; a < HOUSES; ++a) {
if (zipChecker == zip[a]) // check zip code
{
found = true;
foundPosition = a;
} else break;
if (BtnBath1.Checked) // check baths
{
if (bath[a] > 0 && bath[a] <= 1) {
found = true;
foundPosition = a;
} else break;
}
if (BtnBath2.Checked) // check baths
{
if (bath[a] > 1 && bath[a] <= 2) {
found = true;
foundPosition = a;
} else break;
}
if (BtnBath3.Checked) // check baths
{
if (bath[a] > 2 && bath[a] <= 3) {
found = true;
foundPosition = a;
} else break;
}
if (BtnBath4.Checked) // check baths
{
if (bath[a] > 3) {
found = true;
foundPosition = a;
} else break;
}
if (BtnBed1.Checked) // check bed
{
if (bed[a] > 0 && bed[a] <= 1) {
found = true;
foundPosition = a;
} else break;
}
if (BtnBed2.Checked) //check bed
{
if (bed[a] > 1 && bed[a] <= 2) {
found = true;
foundPosition = a;
} else break;
}
if (BtnBed3.Checked) //check bed
{
if (bed[a] > 2 || bed[a] <= 3) {
found = true;
foundPosition = a;
} else break;
}
if (BtnBed4.Checked) //check bed
{
if (bed[a] > 3) {
found = true;
foundPosition = a;
} else break;
}
if (BoxPrice1.Checked) //check price
{
if (price[a] < 200000 && price[a] > 300000) {
found = false;
foundPosition = a;
} else break;
}
if (BoxPrice2.Checked) //check price
{
if (price[a] < 300000 && price[a] > 400000) {
found = false;
foundPosition = a;
} else break;
}
if (BoxPrice3.Checked) //check price
{
if (price[a] < 400000 && price[a] > 500000) {
found = false;
foundPosition = a;
} else break;
}
if (BoxPrice4.Checked) //check price
{
if (price[a] < 500000) {
found = false;
foundPosition = a;
} else break;
}
if (found) {
printcount++;
label1.Text += string.Format("Bed: {0}, Bath:{1}, Asking Price:{2}, City:{3},SQFT:{4}, Zip Code:{5}, Year:{6}", bed[foundPosition], bath[foundPosition], price[foundPosition].ToString("c2"), city[foundPosition], sqft[foundPosition].ToString("n0"), zip[foundPosition], year[foundPosition]);
}
}
if (printcount == 0) label1.Text = ("Sorry there were no houses that met your criteria");
just changed the code for your requirement but can't test it

Related

How can I simplify code in the foreach loop indexOF?

I've a model with a lot of strings named "hours1, hours2, hours3... " which one is used to assign to the index of the foreach.
How can I simplify this code?
if (colNames.IndexOf(item2) == 0)
{
if (model.Hours == null)
{
item.Hours = 0;
}
else
{
item.Hours = (decimal)model.Hours;
}
}
if (colNames.IndexOf(item2) == 1)
{
if (model.Hours1 == null)
{
item.Hours = 0;
}
else
{
item.Hours = (decimal)model.Hours1;
}
}
if (colNames.IndexOf(item2) == 2)
{
if (model.Hours2 == null)
{
item.Hours = 0;
}
else
{
item.Hours = (decimal)model.Hours2;
}
}
This isn't very pretty, but perhaps:
decimal? hours = null;
switch(colNames.IndexOf(item2))
{
case 0: hours = model.Hours; break;
case 1: hours = model.Hours1; break;
case 2: hours = model.Hours2; break;
}
item.Hours = hours ?? 0M;

How to count the a specific value on a multidimensional array c#(Unity)

I'm having trouble on counting the number of my TIE value in my list
here is my code :
string[,] table = new string[104, 15];
int xIndex = 0;
int yIndex = 0;
for (int i = 0; i < list.Count; i++)
{
newString[0] += list[i].r;
newString[0] += ",";
}
string[] newChars = newString[0].Split(',');
string result = ""; // variable for the substring
string previousValue_ = ""; // store here the newprevious value without the T
int counterForTie = 0;
int counterForRow = 1;
int justMoveToY = 1;
foreach (string previousValue in newChars)
{
//check the length so that it wont throw an error
if (previousValue.Length > 1)
{
//get only the first letter of value P,B,T
result = previousValue.Substring(0, 1);
}
else
{
result = "";
}
if (table.GetLength(0) < xIndex)
{
break;
}
if (result.Equals(newPreviousValue) || result.Equals("T") && yIndex < table.GetLength(1))
{
if (counterForRow == 1)
{
yIndex = 0;
table[xIndex, yIndex] = result;
counterForRow++;
if (firstDragonTail)
{
counterForTieSecondTime++;
}
else if (secondDragonTail)
{
counterForTieThirdTime++;
}
else
{
counterForTie++;
}
}
else
{
yIndex += 1;
table[xIndex, yIndex] = result;
if (firstDragonTail)
{
counterForTieSecondTime++;
}
else if (secondDragonTail)
{
counterForTieThirdTime++;
}
else
{
counterForTie++;
}
}
}
else if (result.Equals(newPreviousValue) && previousValue.Equals("T") && yIndex < table.GetLength(1))
{
yIndex += 1;
table[xIndex, yIndex] = result;
if (firstDragonTail)
{
counterForTieSecondTime++;
}
else if (secondDragonTail)
{
counterForTieThirdTime++;
}
else
{
counterForTie++;
}
}
else
{
if (justMoveToY == 1 && counterForRow == 1)
{
xIndex = 0;
yIndex = 0;
table[xIndex, yIndex] = result;
justMoveToY++;
counterForRow++;
}
else if (justMoveToY == 1)
{
xIndex = 0;
yIndex += 1;
table[xIndex, yIndex] = result;
justMoveToY++;
}
else {
if (firstDragonTail)
{
xIndex += 1;
yIndex = 0;
table[xIndex, yIndex] = result;
counterForTieSecondTime = 0;
if (counterForTieSecondTime == 0)
{
secondDragonTail = true;
firstDragonTail = false;
}
else
{
secondDragonTail = false;
}
}
else if (secondDragonTail)
{
xIndex += 1;
yIndex = 0;
table[xIndex, yIndex] = result;
counterForTieThirdTime = 0;
if (counterForTieThirdTime == 0)
{
thirdDragonTail = true;
secondDragonTail = false;
}
else
{
thirdDragonTail = false;
}
}
else
{
xIndex += 1;
yIndex = 0;
table[xIndex, yIndex] = result;
counterForTie = 0;
}
}
}
previousValue_ = result;
if (!result.Equals("T"))
{
newPreviousValue = previousValue_;
}
}
My problem here is that i couldn't count separately all the TIE value . All i want just to count the TIE value on every column .
For example like this image
As you can see on the image above i want to know if the TIE value is on the PLAYER value(blue) / BANKER value(red) and count the TIE value if how many is it on the Player column and vice versa.
I tried this
//count tie in a row
if (result.Equals("T") && result.Equals("P"))
{
tieCounterPlayer++;
Debug.Log("TIE FOR PLAYER :" + tieCounterPlayer);
}
else if(result.Equals("T") && result.Equals("B"))
{
tieCounterBanker++;
Debug.Log("TIE FOR BANKER :" + tieCounterBanker);
}
But unfortunately it didn't work.
Sorry for asking
This is what i did.
if (newPreviousValue.Contains("B"))
{
if (result.Equals("T"))
{
tieCounterBanker++;
Debug.Log("TIE FOR BANKER : " + tieCounterBanker);
}
else
{
tieCounterBanker = 0;
}
}
else if(newPreviousValue.Contains("P"))
{
if (result.Equals("T"))
{
tieCounterPlayer++;
Debug.Log("TIE FOR PLAYER : " + tieCounterPlayer);
}
else
{
tieCounterPlayer = 0;
}
}

Labeling checkTypes for biometric attendance

I have a table named Attendancelogs where I am saving the records that I fetch from a biometric device, the table structure is;
LogType defines the type of log i.e. Biometric/Manual
CheckType defines the type of entry i.e. I or O
VerifyMode defines the type of punch i.e. Fingerprint/Password
isIgnore is used to exclude an entry from the logs.
Now, what I am trying to do is to write a function called sortFunc(); that will process on the already stored records in the Attendancelogs table. what this is suppose to do is;
Mark the checkType of each employee as I for the first entry, then O for their second entry of the date and so on.
If an employee has a last I at the end of the day, meaning no check out, then the next day's first punch of that employee (with in 12 AM - 7 AM) is considered check out for the previous day (marking as a nighter case for that employee) the rest entries are considered as sequential I and O.
any multiple entries within 10 seconds (or defined time) is ignored and marked CheckType as "Auto Ignored for x seconds"
If an employee is not allowed to use Card/Password then his CheckTypes are marked as Card not allowed or Password not allowed
Here is the function that I wrote;
public static bool inn = true;
public void sortLogs(int machineNum)
{
DateTime prevDate = DateTime.MinValue;
DateTime currentDate = DateTime.MinValue;
DateTime prevDateTime = DateTime.MinValue;
DateTime currentDateTime = DateTime.MinValue;
TimeSpan lowerBound = TimeSpan.Zero;
TimeSpan upperBound = TimeSpan.Zero;
var time = DateTime.ParseExact("00:00:00", "HH:mm:ss", null).ToString("hh:mm:ss tt", CultureInfo.GetCultureInfo("en-US"));
lowerBound = Convert.ToDateTime(time).TimeOfDay;
var time2 = DateTime.ParseExact("07:00:00", "HH:mm:ss", null).ToString("hh:mm:ss tt", CultureInfo.GetCultureInfo("en-US"));
upperBound = Convert.ToDateTime(time2).TimeOfDay;
upperBound = new TimeSpan(7, 0, 0);
var CheckType = "N/S";
bool isNighter = false;
List<AttendanceLog> firstDates = new List<AttendanceLog>();
AttendanceLog lastEmp = new AttendanceLog();
var empList = db.AttendanceLogs.OrderBy(x => x.EmpID).ThenBy(x => x.DateTime).ToList();
var countEmps = empList.DistinctBy(p => p.EmpID).Count();
string[,] array = new string[countEmps, 2];
var checkDevice = db.DeviceInformations.Where(xy => xy.DeviceID == machineNum && xy.IsActive == 1.ToString()).ToList();
AttendanceLog firstObj = new AttendanceLog();
int counter = 0;
int tempEmp = -1;
foreach (var emp in empList)
{
if (emp.EmpID == 0)
continue;
var cardAcceptance = db.Roles.Where(x => x.EmpID == emp.EmpID && x.Card_Acceptance == true).ToList();
var passwordAcceptance = db.Roles.Where(x => x.EmpID == emp.EmpID && x.Password_Acceptance == true).ToList();
currentDate = emp.Date;
currentDateTime = emp.DateTime;
if (emp.EmpID != tempEmp)
{
inn = true;
}
if (prevDateTime != DateTime.MinValue)
{
var seconds = (emp.DateTime - prevDateTime).TotalSeconds;
var settings = db.settings.Where(xy => xy.Constant_Name == "Entry Delay").FirstOrDefault();
if (settings.Constant_Value <= 0)
settings.Constant_Value = 10;
else
if (seconds > 0 && seconds < settings.Constant_Value)
{
//store prevDateTime in deleted table
emp.CheckType = "Auto Ignored: " + seconds + " seconds interval.";
// prevDateTime = emp.DateTime;
continue;
}
}
if (passwordAcceptance.Count <= 0)
{
if (emp.VerifyMode == "3")
{
try
{
emp.CheckType = "Password not allowed";
//db.SaveChanges();
continue;
}
catch (DbEntityValidationException e)
{
foreach (var eve in e.EntityValidationErrors)
{
foreach (var ve in eve.ValidationErrors)
{
}
}
throw;
}
}
}
if (cardAcceptance.Count <= 0)
{
if (emp.VerifyMode == "4")
{
try
{
emp.CheckType = "Card not allowed";
// db.SaveChanges();
continue;
}
catch (DbEntityValidationException e)
{
foreach (var eve in e.EntityValidationErrors)
{
foreach (var ve in eve.ValidationErrors)
{
}
}
throw;
}
}
}
if (counter != countEmps)
{
if (emp.EmpID != firstObj.EmpID)
{
array[counter, 0] = emp.EmpID.ToString();
firstObj.EmpID = emp.EmpID;
firstObj.Date = emp.Date;
counter++;
}
}
if (currentDate == firstObj.Date)
{
//check for entry delay
//get emp datetime here
//comapre with the slots
//if the datetime exsits in between
//otherwise store it with boolean flag for the first entry only, the rest should not be flagged
if (emp.DateTime.TimeOfDay > lowerBound && emp.DateTime.TimeOfDay < upperBound)
{
//consider the first check as nighter and then ignore the rest
}
else {
//checks after the upperBound means, no nighter
}
if (inn)
{
inn = false;
emp.CheckType = "I";
}
else
{
inn = true;
emp.CheckType = "O";
}
for (int i = 0; i < array.Length / 2; i++)
{
if (array[i, 0] == emp.EmpID.ToString())
{
array[i, 1] = emp.CheckType;
break;
}
}
//CheckType = emp.CheckType;
prevDate = currentDate;
prevDateTime = currentDateTime;
}
else
{
if (prevDate != currentDate)
{
if (emp.DateTime.TimeOfDay > lowerBound && emp.DateTime.TimeOfDay < upperBound)
{
//consider the first check as nighter and then ignore the rest
if (inn)
{
inn = false;
emp.CheckType = "I";
}
else
{
inn = true;
emp.CheckType = "O";
}
for (int i = 0; i < array.Length / 2; i++)
{
if (array[i, 0] == emp.EmpID.ToString())
{
array[i, 1] = emp.CheckType;
break;
}
}
//CheckType = emp.CheckType;
prevDate = currentDate;
prevDateTime = currentDateTime;
}
else
{
//checks after the upperBound means, no nighter
}
for (int i = 0; i < array.Length / 2; i++)
{
if (array[i, 0] == emp.EmpID.ToString())
{
if (array[i, 1] == "I")
{
emp.CheckType = "O";
inn = true;
}
else
{
emp.CheckType = "I";
inn = false;
}
}
}
}
else
{
if (inn)
{
inn = false;
emp.CheckType = "I";
}
else
{
inn = true;
emp.CheckType = "O";
}
for (int i = 0; i < array.Length / 2; i++)
{
if (array[i, 0] == emp.EmpID.ToString())
{
array[i, 1] = emp.CheckType;
}
}
}
prevDate = currentDate;
}
tempEmp = emp.EmpID.Value;
}
db.SaveChanges();
}
This did run but it messes up the "12 AM to 7 AM" checks and the password checks, i.e. not the accurate results.
As one of the example seen ^ consecutive O should not be there. I have been going crazy over this!

Score isnt goint up by 2 when i answer right

Hi i need to make a exercise where i have to make sums. But when i answer the sum right the int score isnt going up by 2. Im pretty new to ASP/C# so sorry if im not that smart.
Here is the code i have:
int score = 0;
if (Int32.Parse(txt2.Text) == Int32.Parse(lbl1.Text) * Int32.Parse(lbl2.Text))
{
lbl11.Visible = true;
lbl11.Text = "Goed!";
score = +2;
}
else
{
lbl11.Visible = true;
lbl11.Text = "Fout!";
score = +0;
}
if (Int32.Parse(txt3.Text) == Int32.Parse(lbl3.Text) * Int32.Parse(lbl4.Text))
{
lbl12.Visible = true;
lbl12.Text = "Goed!";
score = +2;
}
else
{
lbl12.Visible = true;
lbl12.Text = "Fout!";
score = +0;
}
if (Int32.Parse(txt4.Text) == Int32.Parse(lbl5.Text) * Int32.Parse(lbl6.Text))
{
lbl13.Visible = true;
lbl13.Text = "Goed!";
score = +2;
}
else
{
lbl13.Visible = true;
lbl13.Text = "Fout!";
score = +0;
}
if (Int32.Parse(txt5.Text) == Int32.Parse(lbl7.Text) * Int32.Parse(lbl8.Text))
{
lbl14.Visible = true;
lbl14.Text = "Goed!";
score = +2;
}
else
{
lbl14.Visible = true;
lbl14.Text = "Fout!";
score = +0;
}
if (Int32.Parse(txt6.Text) == Int32.Parse(lbl9.Text) * Int32.Parse(lbl10.Text))
{
lbl15.Visible = true;
lbl15.Text = "Goed!";
score = +2;
}
else
{
lbl15.Visible = true;
lbl15.Text = "Fout!";
score = +0;
}
if(score >= 0)
{
lblScore.Text = score.ToString();
}
else if(score <= 0)
{
lblScore.Text = "0";
}
Thanks for the answers!
You need to be using
score += 2;
instead of
score = +2;

C# program with COM port going NOT RESPONDING

I have C#/.NET program which uses a COM port and SQL CE Database with a WCF service. Sometimes the program becomes unresponsive (the window freezes) and even in debug mode I cannot the reason.
I can restart the program after restarting my PC or the COM port. The problem isn't with my COM port problem because I have tried it on many PCs and all have the same problem.
How could I resolve this?
private void timer_Tick(object sender, EventArgs e)
{
try
{
labeltimer.Text = DateTime.Now.ToString();
if (timerstarted == true)
{
return;
}
timerstarted = true;
_CARDCODE = 0;
string error = "";
bool hasbassed = false;
if (this._Close == true)
{
this.Close();
}
if (serialPort1.IsOpen)
{
if (i < 8)
{
i++;
}
else
{
i = 0;
}
to[0] = (byte)(128 + i);
try
{
serialPort1.Write(to, 0, 1);
}
catch (System.Exception ex)
{
ListViewItem Lvi = new ListViewItem((++rowcount).ToString());
Lvi.SubItems.Add("");
Lvi.SubItems.Add("");
Lvi.SubItems.Add("Disconnected");
Lvi.SubItems.Add("");
listView.Items.Add(Lvi);
StartPort();
}
if (progressBar.Value >= 1500)
progressBar.Value = 0;
else
progressBar.Value += 10;
if (serialPort1.BytesToRead != 0)
{
byte[] data = new byte[serialPort1.BytesToRead];
from = new byte[3];
try
{
serialPort1.Read(data, 0, data.Length);
}
catch (System.Exception ex)
{
ListViewItem LVi = new ListViewItem((++rowcount).ToString());
LVi.SubItems.Add("");
LVi.SubItems.Add("");
LVi.SubItems.Add("Disconnected");
LVi.SubItems.Add("");
listView.Items.Add(LVi);
StartPort();
}
// data.Length == 4 by Button or HassPassed
if (data.Length == 4)
{
if (data[1] > 2)
DBS.AddButtonPass(data[0], data[1] / 4);
else
{
DBS.EditPass((int)data[0]);
timerstarted = false;
return;
}
}
else if ((data[data.Length - 1] != 255) || (data.Length < 4))
{
from[0] = data[0];
from[1] = 0;
from[2] = 0;
serialPort1.Write(from, 0, 3);
timerstarted = false;
return;
}
//RegistoringSubscriber_ID Add Subscriber Card
else if ((RegistoringSubscriber_ID > 0) && (RegisterCheckpoint != 0) && (data[0] == RegisterCheckpoint))
{
Registoring = false;
if (RegistorNewCard(Convert.ToInt32(data[2].ToString() + data[3].ToString() + data[4].ToString())) > 0)
FormBringPC.AnswerType = 1;
else
FormBringPC.AnswerType = 2;
RegistoringSubscriber_ID = 0;
error = "register card";
}
// RegistoringSubscriber_ID < 0 Add Bonus Card
else if ((RegistoringSubscriber_ID < 0) && (RegisterCheckpoint != 0) && (data[0] == RegisterCheckpoint))
{
Registoring = false;
if (RegistorBonusCard(Convert.ToInt32(data[2].ToString() + data[3].ToString() + data[4].ToString())) > 0)
FormBringPC.AnswerType = 1;
else
FormBringPC.AnswerType = 2;
RegistoringSubscriber_ID = 0;
error = "register Bonus card";
}
else if ((List_Checkpoint_ID.Contains(data[0]) && ((data[1] == 130) || (data[1] == 129))))
{
// DBS.EditPass((int)data[0]);
}
else if ((List_Checkpoint_ID.Contains(data[0]) && (data.Length == 7)))
{
_CARDCODE = Convert.ToInt32(data[2].ToString() + data[3].ToString() + data[4].ToString());
GlobalTypes.InvalidPass pass = DBS.CheckPassStatus(_CARDCODE, (int)data[0], (int)data[1]);
if (pass == GlobalTypes.InvalidPass.Valid)
{
from[0] = data[0];
from[1] = 1;
from[2] = 1;
serialPort1.Write(from, 0, 3);
LBTitle.Text = DateTime.Now.ToLongTimeString();
hasbassed = true;
}
else
{
from[0] = data[0];
from[1] = 0;
from[2] = 0;
serialPort1.Write(from, 0, 3);
switch (pass)
{
case GlobalTypes.InvalidPass.InvalidCard:
{
error = "Չգրանցված քարտ";
break;
}
case GlobalTypes.InvalidPass.InvalidCount:
{
error = "Այց. քանակ";
break;
}
case GlobalTypes.InvalidPass.InvalidGraphic:
{
error = "Ժամանակ hh:mm:ss";
break;
}
case GlobalTypes.InvalidPass.InvalidPeriod:
{
error = "Ժամանակահատված xxxx.dd.yyy";
break;
}
case GlobalTypes.InvalidPass.InvalidStatus:
{
error = "Հառացված աբոնենտ";
break;
}
case GlobalTypes.InvalidPass.InvalidSuscribe:
{
error = "Անհայտ բաժանորդ";
break;
}
default:
{
error = "esim inch";
break;
}
}
}
}
else if ((List_Checkpoint_ID.Contains(data[0]) && (data.Length > 0)))
{
try
{
byte[] ticket = new byte[data.Length - 6];
for (int ii = 0; ii < data.Length - 6; ii++)
{
ticket[ii] = data[ii + 2];
}
_CARDCODE = Convert.ToInt32(Encoding.ASCII.GetString(ticket.ToArray()));
GlobalTypes.HasPass pass = DBS.CheckTicketPassStatus(_CARDCODE, (int)data[0], (int)data[1]);
if (pass == GlobalTypes.HasPass.TruePass)
{
from[0] = data[0];
from[1] = 1;
from[2] = 1;
serialPort1.Write(from, 0, 3);
LBTitle.Text = DateTime.Now.ToLongTimeString();
hasbassed = true;
}
else
{
from[0] = data[0];
from[1] = 0;
from[2] = 0;
serialPort1.Write(from, 0, 3);
switch (pass)
{
case GlobalTypes.HasPass.CardNotFound:
{
error = "Not registored ticket";
break;
}
case GlobalTypes.HasPass.CardRepeat:
{
error = "ReEntring";
break;
}
case GlobalTypes.HasPass.ValidationPeriodError:
{
error = "Ժամանակ hh:mm:ss";
break;
}
case GlobalTypes.HasPass.SeasonError:
{
error = "Ժամանակահատված xxxx.dd.yyy";
break;
}
case GlobalTypes.HasPass.WeekOfDayError:
{
error = "Day of Weak";
break;
}
default:
{
error = "esim inch";
break;
}
}
}
}
catch { timerstarted = false; return; }
}
if (rowcount >= 10)
{
rowcount = 0;
listView.Items.Clear();
}
ListViewItem lvi = new ListViewItem((++rowcount).ToString());
lvi.SubItems.Add(data[0].ToString());
if (data.Length == 4)
hasbassed = true;
if (((data[1] == 2) || (data[1] == 8)) && ((data.Length == 4) || (Dictionary_Chekpoint[data[0]].CheckPointType == 2)))
{
lvi.SubItems.Add("Ելք");
}
else
{
lvi.SubItems.Add("Մուտք");
}
if (data.Length != 4)
lvi.SubItems.Add(_CARDCODE.ToString());
else
lvi.SubItems.Add("Հերթապահ");
lvi.SubItems.Add(error);
if (hasbassed == true)
{
lvi.BackColor = Color.LightGreen;
}
else
{
lvi.BackColor = Color.LightPink;
}
listView.Items.Add(lvi);
}
}
else MessageBox.Show("Serial port is closed!", "RS232 tester", MessageBoxButtons.OK, MessageBoxIcon.Error);
timerstarted = false;
}
catch
{
timerstarted = false;
return;
}
}
C# programs show as NOT RESPONDING whenever there is processing happening in the main UI thread that is preventing UI processing. The general answer here is to push that work into a different thread, so that UI events can continue to process (see references below for more information). In the case of serial ports, the easiest thing to do is hook the SerialPort.DataReceived event instead of polling it: https://msdn.microsoft.com/en-us/library/system.io.ports.serialport.datareceived%28v=vs.110%29.aspx
Ref:
GUI not responding while fetching data
http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx
https://msdn.microsoft.com/en-us/library/windows/desktop/dd744765%28v=vs.85%29.aspx
http://www.dreamincode.net/forums/topic/246911-c%23-multi-threading-in-a-gui-environment/

Categories