I have group of conditions like
foreach
{
Condition a
condition b
}
So I am validating the values based on conditions.I am facing the problem: for example I have list of items like {1,2,3,4}. So I have a condition like if item 1 is fail then item 2,3,4 should be fail.
if item 2 is fail then item 3,4 should be fail and so on.
I am trying in below code.
foreach (SagaData item in lstPrm)
{
PriceDetail prevPrice = null;
PriceDetail currentPrice = null;
PriceDetail nextPrice = null;
bool bHasError = false;
int iPriceMasterId = 0;
int iPriceTypeId = 0;
string sMprCurrencyType = null;
string sPublisherCurrencyType = null;
int? iExpirationCalendarId = 0;
string sPRMMessage = string.Empty;
//a) If Change Indicator = C or A and Price = 0.00: Cannot change price value to zero.
if ((item.ChangeIndicator == 'C' || item.ChangeIndicator == 'A') && item.PostingPrice == 0)
{
bHasError = true;
sPRMMessage = "FAILURECannot change price value to zero";
}
//b) If Change Indicator = D and Price > 0.00: Invalid deactivation.
if ((item.ChangeIndicator == 'D') && (item.PostingPrice > 0) && (!bHasError))
{
bHasError = true;
sPRMMessage = "FAILUREInvalid deactivation";
}
so i have if condition a fail for item 1 then how should i keep maintain the error for next iteration.
Thanks for the help. if you want more info plz let me know.
You can go through your Collection with a simple for loop and use an ErrorArray:
bool[] bHasError = new bool[lstPrm.Count];
for (int i = 0; i < lstPrm.Count; i++)
{
...
bHasError[i] = true;
...
}
or you can define bHasError BEFORE the foreach if one error is enough for you to consider.
Related
For some reason, my code doesn't seem to reach the last few lines.
I've added the stop point and the return point in the code.
I don't see anything wrong with the data source I use on that row whenever I check it out in debug.
The code seems to set the value there and jumps back to the top of the foreach loop.
foreach (DataGridViewRow row in dataGridView1.Rows) {
//We check if the user has already filled in some info
return point if (row.Cells[7].Value != null && row.Cells[6].Value != null && !askedTheUser)
{
//trigger for message if you want to replace them
Message m = new Message("There is already info present in the category and or size dropdown. Would you like to overwrite this?", "Overwrite", "YESNO");
if (m.Awnser) {
overwrite = true;
}
askedTheUser = true;
}
DataGridViewComboBoxCell cat = (DataGridViewComboBoxCell)row.Cells[6];
string toMatch = row.Cells[3].Value.ToString();
//Now we will start matching
//First we try to match with the package ( if that is filled in )
if (row.Cells[5].Value != null && (string)row.Cells[5].Value != "") {
toMatch = row.Cells[5].Value.ToString();
matchWithPackage = true;
}
Regex re = new Regex(#"([a-zA-Z]+)(\d+)");
Match result = re.Match(toMatch);
string alphaPart = result.Groups[1].Value;
string numberPart = result.Groups[2].Value;
Datagridview dgv = new Datagridview();
if (numberPart.Length < 4) {
numberPart = numberPart.PadLeft(4, '0');
}
#if DEBUG
Console.WriteLine(numberPart);
#endif
//Matching the category
if (CHIP != null && CHIP.Contains(alphaPart))
{
cat.Value = "CHIP";
}
else if (SOJ != null && SOJ.Contains(alphaPart))
{
cat.Value = "SOJ";
}
else if (PLCC != null && PLCC.Contains(alphaPart))
{
cat.Value = "PLCC";
}
else if (QFP != null && QFP.Contains(alphaPart))
{
cat.Value = "QFP";
}
else if (SOP != null && SOP.Contains(alphaPart))
{
cat.Value = "SOP";
}
else {
if (cat.Value != "") {
cat.Value = "";
}
cat.FlatStyle = FlatStyle.Flat;
cat.Style.BackColor = Color.DarkRed;
continue;
}
//Setting the matched color
cat.FlatStyle = FlatStyle.Flat;
cat.Style.BackColor = Color.SpringGreen;
//Adding the dropdownlist to the size cb
(row.Cells[7] as DataGridViewComboBoxCell).DataSource = dgv.AddSeconderyCombobox(dataGridView1, row.Cells[6].Value.ToString());
if (!matchWithPackage) {
continue;
}
//Matching the size
Stop Point List<string> sizeList = (List<string>)(row.Cells[7] as DataGridViewComboBoxCell).DataSource;
Doesn't reach this and beyond List<string> matchedList = sizeList.FindAll(stringToCheck => stringToCheck.Contains(numberPart));
if (matchedList.Count > 0) {
(row.Cells[7] as DataGridViewComboBoxCell).DataSource = matchedList;
}
}
So i fixt my own problem and i'm going to awnser my own question i case somebody comes across a similar problem.
if (sizeList != null) {
List<string> matchedList = sizeList.FindAll(stringToCheck => stringToCheck.Contains(numberPart));
if (matchedList.Count > 0)
{
(row.Cells[7] as DataGridViewComboBoxCell).DataSource = matchedList;
}
}
After adding the few last lines in an extra check that needed to be done I noticed that the code was being executed, but the matchedlist.count was always 0.
So what was happening is that the code after that was redundant as the matchList was 0 and the debugger just skipped jumping to these lines ( a bit confusing if you ask me ).
The following code works for to show people who have holidays with an icon in my calendar but the problem i have is the first line of code in my for statement where i extract the date times
protected void apertureAppointments_TimeSlotCreated(object sender, TimeSlotCreatedEventArgs e)
int i = 0;
bool isFound = false;
List<tblApertureNetShiftPattern> _list = new List<tblApertureNetShiftPattern>();
_list = _dal.getHolidays();
List<Resource> resources = new List<Resource>(apertureAppointments.Resources.GetResourcesByType("Managers"));
Resource res = resources[5];
foreach (tblApertureNetShiftPattern sp in _list)
{
if (_list.Count >= 1)
i++;
else
i = 0;
DateTime? dt1 = _list[i - 1].startdate;
DateTime? dt2 = _list[i - 1].endDate;
if (e.TimeSlot.Start == dt1 && e.TimeSlot.Resource.Text == sp.manager_name)
{
isFound = true;
if (DoDateRangesOverlap(e.TimeSlot.Start, e.TimeSlot.End, dt1, dt2) && isFound == true)
{
Label temperatureLabel = new Label();
if (sp.appointmentType == Constants.shiftDayoff)
{
e.TimeSlot.CssClass = "DayOfCssStyle";
temperatureLabel.CssClass = "DayOfCssStyle";
}
else if (sp.appointmentType == Constants.shiftHoliday)
{
e.TimeSlot.CssClass = "HolidayCssStyle";
temperatureLabel.CssClass = "HolidayCssStyle";
}
else if (sp.appointmentType == Constants.shiftStat)
{
e.TimeSlot.CssClass = "statCssStyle";
temperatureLabel.CssClass = "statCssStyle";
}
else if (sp.appointmentType == Constants.shiftsickDay)
{
e.TimeSlot.CssClass = "SickDayStyle";
temperatureLabel.CssClass = "SickDayStyle";
}
temperatureLabel.Text = sp.Description;
Image imageControl = new Image();
imageControl.ImageUrl = #"~\images\aperturenet\Calendar\resources\holidays.png";
temperatureLabel.BackColor = System.Drawing.Color.Orange;
dt1 = null;
dt2 = null;
isFound = false;
e.TimeSlot.Control.Controls.AddAt(1, temperatureLabel);
e.TimeSlot.Control.Controls.AddAt(2, imageControl);
}
}
}
My Problem lies in this code here
if (_list.Count >= 1)
i++;
else
i = 0;
DateTime? dt1 = _list[i - 1].startdate;
DateTime? dt2 = _list[i - 1].endDate;
When I do not have the -1 in the [ array int] it bombs out because obv the list shows 0,1 and the loop probally shows 2 items. What is the best way to avoid the object out of range index error.?
Getholidays is just a simple list of when the staf memeber our off so nothing to fancy here.
public List<tblApertureNetShiftPattern> getHolidays()
{
List<tblApertureNetShiftPattern> list = new List<tblApertureNetShiftPattern>();
var q = from _holidays in apertureNetEntities.tblApertureNetShiftPatterns.Where(w => w.isDeleted == false)
select _holidays;
list = q.ToList();
return list;
}
Also is their a neater way of doing I somehow feel that my code is very bloated.
Are you sure, these are the lines causing your problem? Because you can only enter the body of the foreach loop if the _list contains at least one element. Thus, _list.Count >= 1 will always be true, and i will be incremented and never become -1.
I suspect your out of bound exception originating from this line of code
List<Resource> resources = new List<Resource>(apertureAppointments.Resources.GetResourcesByType("Managers"));
Resource res = resources[5];
Are you sure, there are always at least 6 items in this list?
Generally, why do you access your listitems by index, if you iterate them with a foreach loop? YOu could easily do it as follows
foreach (tblApertureNetShiftPattern sp in _list) {
DateTime? dt1 = sp.startDate;
DateTime? dt2 = sp.endDate;
}
just like you do it with the manager_name property.
If you insist on accessing by index, I suggest incrementing the index variable i at the end of the loop. This way you won't always have to decrement the index before accessing the array.
So what my problem is and i have looked on the internet for this but really cannot find out how to do it.
I want to use my combo box which is populated with items from a notepad. i want the combo box to search through the notepad when an items from the combo box is selected and when it gets a match i want it to return the line number(ID).
This is what i thought would work, but it doesn't full work.
int items = File.ReadLines(#"C:\Users\PC\Documents\File\IDs.txt").Count();
string line;
int thisnum;
if (cboItemPick.SelectedIndex != -1)
{
if (cboItemPick.SelectedItem != null)
{
for (int i = 0; i <items;)
{
items = i;
line = File.ReadLines(#"C:\Users\PC\Documents\File\IDs.txt").ElementAt(items);
if (line == cboItemPick.Text)
{
MessageBox.Show("Boom");
break;
}
else
{
i++;
}
}
}
}
First of all, your code will have very bad performances. Please refer to this reviewed example:
if( cboItemPick.SelectedItem != null) {
var filepath = #"C:\Users\PC\Documents\File\IDs.txt";
var lines = File.ReadLines(filepath);
var keyword = cboItemPIck.SelectedItem as String;
for(var i = 0; i < lines.length; i++) {
var line = lines[i];
if( string.Compare(line, keyword) == 0) {
// Good, you have a match!
MessageBox.Show(string.Format("Item found at line: {0}", i));
break;
}
}
}
I hope this can help you.
You can try this:
var lines = File.ReadLines(#"C:\Users\PC\Documents\File\IDs.txt");
var result = lines.Select((i, index) => new { Value = i, Index = index }).ToList();
//Check if cboItemPick.SelectedItem is valid and set it to comboboxValue
var lineNumber = result.First(i => i.Value == comboboxValue).Select(i => i.Index);
I'm curious as to the best route (more looking towards simplicity, not speed or efficiency) to sort a DropDownList in C#/ASP.NET - I've looked at a few recommendations but they aren't clicking well with me. this drop down is giving me list in alphabetical order. But I have to sort out randomly.
Note:I do not have control over how the data comes into the DropDownList - I cannot modify the SQL.
public void populateLocationList()
{
DataTable dt_locations = (DataTable)daa_addresses.GetDataByEventLocations(int_eventid);
if (dt_locations != null && dt_locations.Rows.Count > 0)
{
// Populate locations dropdown menu
// Bind locationsList instead of dt_locations
ddl_locations.DataTextField = "Key";
ddl_locations.DataValueField = "Value";
ddl_locations.DataSource = RemoveDuplicateLocations(dt_locations);
ddl_locations.DataBind();
string location = "";
// Set the selection based upon the query string
if (Request.QueryString["loc"] != null)
{
location = Request.QueryString["loc"];
locationLbl.Text = Request.QueryString["loc"];
locationID.Value = "-1";
}
if (dt_locations.Rows.Count == 1)
{
location = ddl_locations.Items[0].Text;
locationLbl.Text = location;
}
// Set location in drop down list
int int_foundlocation = 0;
bool foundLocation = false;
foreach (ListItem lsi_item in ddl_locations.Items)
{
if (lsi_item.Text.ToLower().Trim() == location.ToLower().Trim())
{
int_foundlocation = ddl_locations.Items.IndexOf(lsi_item);
foundLocation = true;
break;
}
}
ddl_locations.SelectedIndex = int_foundlocation;
if (ddl_locations.Items.Count == 1)
{
// Make location label visible.
locationLbl.Visible = true;
ddl_locations.Visible = false;
}
else
{
locationLbl.Visible = false;
ddl_locations.Visible = true;
}
//* defualt location S for short courses *//
if (!IsPostBack && !foundLocation)
{
ListItem s = ddl_locations.Items.FindByText("S");
int index = 0;
if (s != null)
{
index = ddl_locations.Items.IndexOf(s);
}
ddl_locations.SelectedIndex = index;
ddl_locations.DataBind();
}
}
}
I have to sort out randomly.
You'd have to shuffle rows, probably with something close to this code (borrowed from #configurator's answer):
internal static class Extensions
{
internal static IEnumerable<T> Shuffle<T>(this IEnumerable<T> source, Random rng)
{
T[] elements = source.ToArray();
// Note i > 0 to avoid final pointless iteration
for (int i = elements.Length - 1; i > 0; i--)
{
// Swap element "i" with a random earlier element it (or itself)
int swapIndex = rng.Next(i + 1);
yield return elements[swapIndex];
elements[swapIndex] = elements[i];
// we don't actually perform the swap, we can forget about the
// swapped element because we already returned it.
}
// there is one item remaining that was not returned - we return it now
yield return elements[0];
}
}
Assuming that RemoveDuplicateLocations returns a DataTable the binding part of your code should be changed to:
ddl_locations.DataSource = RemoveDuplicateLocations(dt_locations)
.AsEnumerable()
.Shuffle(new Random())
.CopyToDataTable();
I want to search for a string in DataTable if it starts with "null" delete this string, if this row has no values then erase this row too. Can someone show me how to do it?
ID Name Comment
2 lola hallo
5 miky hi
null0 // delete null0 and remove this row
null1 ko // delete null1 but do not remove this row
1 hub why
3 null2 //delete null2 but do not remove this row
I tried to delete "null" but it doesn't work.
My Code:
int ct1 = 0;
for (int i = 0; i < resE1.Rows.Count; i++ )
{
if(resE1.Rows[i]["SignalName"].ToString() == "null" + ct1)
{
resE1.Rows[i].SetField<String>(2, "");
}
ct1++;
}
I find a solution to replace "null*" with empty spaces, but now I want to erase this row if the cells values of this row are empty, how can i do it?
int ct1 = 0;
for (int i = 0; i < resE1.Rows.Count; i++)
{
string fix = resE1.Rows[i]["SignalName"].ToString();
if(fix.Contains("null"))
{
resE1.Rows[i].SetField<String>(2, "");
}
ct1++;
}
I tried this. Works for me.
List<DataRow> rowsToRemove = new List<DataRow>();
foreach (DataRow dr in resE1.Rows)
{
if (dr["Name"].ToString().IndexOf("null") == 0)
{
dr.SetField("Name", "");
}
bool hasValue = false;
for (int i = 0; i < dr.ItemArray.Count(); i++)
{
if (!dr[i].ToString().Equals(String.Empty))
hasValue = true;
}
if (!hasValue) rowsToRemove.Add(dr);
}
foreach(DataRow dr in rowsToRemove)
{
dr.Delete();
}
Here is your code changed so it works although I don't like how it is written. Check the answer:
int ct1 = 0;
int i = 0;
while(i < dt.Rows.Count)
{
if ( dt.Rows[i]["Name"].ToString() == "null" + ct1)
{
if ((dt.Rows[i][0] == null || dt.Rows[i][0].ToString() == string.Empty) && (dt.Rows[i][2] == null || dt.Rows[i][2].ToString() == string.Empty))
{
dt.Rows.RemoveAt(i);
i--;
}
else
{
dt.Rows[i].SetField<String>(1, "");
}
ct1++;
}
i++;
}
Assuming your DataTable has column "Name" of type string you can achieve it like this:
private DataTable RemoveUnwanted(DataTable source)
{
var rowsEnu = source.Rows.GetEnumerator();
while (rowsEnu.MoveNext())
{
((DataRow)rowsEnu.Current)["Name"] = ((DataRow)rowsEnu.Current)["Name"].ToString().StartsWith("null") ? string.Empty : ((DataRow)rowsEnu.Current)["Name"];
}
return (from i in source.AsEnumerable()
where !(i.ItemArray.All(o => string.IsNullOrEmpty(o.ToString())))
select i).CopyToDataTable();
}
You will also need reference to System.Data.DataSetExtensions.
To answer one of your questions, to delete the entire row do something like this:
if(resE1.Rows[i].Contains("null") && (resE1.Rows[i]["ID"].ToString() == "") && (resE1.Rows[i]["Comment"].ToString() == ""))
{
resE1.Rows[i].Delete();
}
bool emptyFlag = false;
if(resE1.Rows[i].Contains("null"))
{
for(int j = 0; j < resE1.Columns.Count; j++)
{
if(resE1.Rows[i][j].Equals(""))
emptyFlag = true;
else
emptyFlag = false;
}
if(emptyFlag)
resE1.Rows[i].Delete();
}
You need something like this:
String test = "Null01";
if (test.IndexOf("Null") == 0)
{
test = test.Replace("Null", String.Empty);
}
For second part of your question, just check if Comments are null or empty then replace the string too.
Arrange code according to your own requirement.