Store values from selected checkBox to a array - c#

I have a foreach that if the checkbox of the row is selected it should do some calculations and after that store the result values in something,i'm trying to store in a array.In the end i need to have, for example 4 rows that were selected with his values inside the array,after that i need to put this values inside a session,and recover in other page(A confirmation page).I'm trying this.But i cant figure out a way to store the select rows in a array.I dont necessary need to be array if someone knows a better way.
string[] valoresSelecionados;
foreach (GridViewRow grdCount in grdSimulacao.Rows)
{
if (((CheckBox)grdCount.FindControl("chkSeleciona")).Checked)
{
if (double.Parse(grdCount.Cells[5].Text) >= 0)
vlNotas += double.Parse(grdCount.Cells[5].Text);
else
vlDebito += double.Parse(grdCount.Cells[5].Text);
if (!string.IsNullOrEmpty(grdCount.Cells[8].Text) && grdCount.Cells[8].Text != " ")
vlEncargos += double.Parse(grdCount.Cells[8].Text);
_simulacao.Notas.Rows.Add(grdCount.Cells[1].Text);
if (Culture== "English (United States)")
{
//DateTime data =DateTime.Parse(grdCount.Cells[2].Text);
//var dataInicial = data.ToString("mm-DD-yyyy");
_simulacao.Notas.Rows[u]["DTEMISSAO"] = grdCount.Cells[2].Text;
_simulacao.Notas.Rows[u]["DTVENCIMENTO"] = grdCount.Cells[3].Text;
}
else
{
_simulacao.Notas.Rows[u]["DTEMISSAO"] = grdCount.Cells[2].Text;
_simulacao.Notas.Rows[u]["DTVENCIMENTO"] = grdCount.Cells[3].Text;
}
_simulacao.Notas.Rows[u]["PRAZOPGTO"] = "5";
_simulacao.Notas.Rows[u]["VALTOTAL"] = grdCount.Cells[5].Text;
_simulacao.Notas.Rows[u]["DOCCOMPRAS"] = grdCount.Cells[6].Text;
if (DateTime.Parse(grdCount.Cells[3].Text) < DateTime.Parse(txtDtCredito.Text))
dtok = true;
DateTime antigaData = DateTime.Parse(grdCount.Cells[3].Text);
DateTime novaData = DateTime.Parse(txtDtCredito.Text);
DateTime dataAtual = DateTime.Today;
int diaAtual = dataAtual.DayOfYear;
int diaNovo = novaData.DayOfYear;
int diaAntigo = antigaData.DayOfYear;
int anoAtual = dataAtual.Year;
int anoNovo = novaData.Year;
if (diaAntigo <= diaNovo)
{
dataErro++;
}
if (diaNovo == diaAtual || diaNovo == diaAtual + 1 || diaNovo == diaAtual + 2 ||
diaNovo == diaAtual + 3 || diaNovo < diaAtual || anoAtual < anoNovo)
{
error++;
}
else
{
TimeSpan ts = antigaData - novaData;
if ((double.Parse(grdCount.Cells[5].Text)) < 0)
{
}
else
{
_simulacao.Notas.Rows[u]["DIASANTEC"] = ts.Days;
}
}
if (grdCount.Cells[7].Text != " ")
_simulacao.Notas.Rows[u]["DIASANTEC"] = "10";
else
_simulacao.Notas.Rows[u]["DIASANTEC"] = "0";
if (!string.IsNullOrEmpty(grdCount.Cells[8].Text) && grdCount.Cells[8].Text != " ")
{
_simulacao.Notas.Rows[u]["VLFINAL"] = double.Parse(grdCount.Cells[5].Text) - double.Parse(grdCount.Cells[8].Text);
_simulacao.Notas.Rows[u]["VLENCARGOS"] = grdCount.Cells[8].Text;
}
else
{
_simulacao.Notas.Rows[u]["VLFINAL"] = double.Parse(grdCount.Cells[5].Text);
_simulacao.Notas.Rows[u]["VLENCARGOS"] = "0,00";
}
valoresSelecionados[] = _simulacao.Notas.Rows.Add[u];
u++;
}
}
The first Picture show the first grid with all values.I selected 4 for example,after the calculations of the method i need to show only the 4 select in a model (second Picture),under the first grid of Picture two i will put the new grid with the selected values from before.

Related

How to call function randomly in c# according to checkbox list selection value?

Checkbox List has n items, then combination of selection of items has various logic.
e.g. 4 items in list, then user can select 1, 2 ,3 or 4 items.
when 1 items selected possible case is 4
->if items[0] selected then (random_function[0])
->if items1 selected then (random_function1)
.
.so on
when 2 items selected possible case is 6
->if items[0] & items1 then select (random_function[0] or random_function1)
->if items[0] & items[2] then select (random_function[0] or random_function[2])
.
.so on
when 3 items selected possible case is 3
->if items[0] & items1 & items[2] then select (random_function[0] or random_function1 or random_function[2])
->if items[0] & items1 & items[3] then select (random_function[0] or random_function1 or random_function[3])
.
.so on
when 4 items selected possible case is 1
->if items[0] & items1 & items[2] & items[4] then select (random_function[0] or random_function1 or random_function[2] or random_function[3])
Note.: random_function[i] call randomly
so, each items has each if cases,
it is possible for small number of n, what if value of n is greater than 10 or 20.
I tried for n=4 (checklistbox items) but i have to try for n=15.
How to call these function according items selected combinations.
And following code in button click event:
`
string s = null;
int c = 0;
for (int i = 0; i < checkedListBox1.Items.Count; i++)
{
if (checkedListBox1.GetItemChecked(i))
{
c = c + 1;
}
}
if (c == 1)
{
if (checkedListBox1.GetItemChecked(0))
{ s = " Item one"; }
else if (checkedListBox1.GetItemChecked(1))
{ s = " Item two "; }
else if (checkedListBox1.GetItemChecked(2))
{ s = " Item three "; }
else if (checkedListBox1.GetItemChecked(3))
{ s = " Item four "; }
}
else if (c == 2)
{
Random r = new Random();
int var = r.Next(1, 3);
if (checkedListBox1.GetItemChecked(0) && checkedListBox1.GetItemChecked(1))
{
if (var == 1) { s = " Item one "; }
else { s = " Item two "; }
}
else if (checkedListBox1.GetItemChecked(0) && checkedListBox1.GetItemChecked(2))
{
if (var == 1) { s = " Item one "; }
else { s = " Item three "; }
}
else if (checkedListBox1.GetItemChecked(0) && checkedListBox1.GetItemChecked(3))
{
if (var == 1) { s = " Item one "; }
else { s = " Item four "; }
}
else if (checkedListBox1.GetItemChecked(1) && checkedListBox1.GetItemChecked(2))
{
if (var == 1) { s = " Item two "; }
else { s = " Item three "; }
}
else if (checkedListBox1.GetItemChecked(1) && checkedListBox1.GetItemChecked(3))
{
if (var == 1) { s = " Item two "; }
else { s = " Item four "; }
}
else if (checkedListBox1.GetItemChecked(2) && checkedListBox1.GetItemChecked(3))
{
if (var == 1) { s = " Item three "; }
else { s = " Item four "; }
}
}
else if (c == 3)
{
Random r = new Random();
int var = r.Next(1, 4);
if (checkedListBox1.GetItemChecked(0) && checkedListBox1.GetItemChecked(1) && checkedListBox1.GetItemChecked(2))
{
if (var == 1) { s = " Item one "; }
else if (var == 2) { s = " Item two "; }
else { s = " Item three "; }
}
else if (checkedListBox1.GetItemChecked(0) && checkedListBox1.GetItemChecked(1) && checkedListBox1.GetItemChecked(3))
{
if (var == 1) { s = " Item one "; }
else if (var == 2) { s = " Item two "; }
else { s = " Item three "; }
}
else if (checkedListBox1.GetItemChecked(1) && checkedListBox1.GetItemChecked(2) && checkedListBox1.GetItemChecked(3))
{
if (var == 1) { s = " Item one "; }
else if (var == 2) { s = " Item two "; }
else { s = " Item three "; }
}
}
else if (c == 4)
{
Random r = new Random();
int var = r.Next(1, 4);
if (checkedListBox1.GetItemChecked(0) && checkedListBox1.GetItemChecked(1) && checkedListBox1.GetItemChecked(2) && checkedListBox1.GetItemChecked(3))
{
if (var == 1) { s = " Item one "; }
else if (var == 2) { s = " Item two "; }
else if (var == 3) { s = " Item three "; }
else { s = " Item four "; }
}
}
label1.Text = s; //output
`

Excel takes only that no of rows which has data in c#...my code works for some excel sheet not for all

Excel sheets made by different different clients...that code works when i make but not when user make..is anything problem with excel sheet so , i can tell user make like that way..or i can do anything with my code.
private void MeterUpdateByExcelSheet(HttpPostedFileBase file)
{
List<string> errorMessages = new List<string>();
int siteId = Helpers.SiteHelpers.Functions.GetSiteIdOfLoginUser().Value;
var stream = file.InputStream;
using (var package = new ExcelPackage(stream))
{
//getting number of sheets
var sheets = package.Workbook.Worksheets;
int totalProcessedMeters = 0;
if (sheets.Count > 0)
{
var sheet = sheets.FirstOrDefault();
//getting number of rows
var rows = sheet.Dimension.End.Row;
for (int row = 2; row <= rows; row++)
{
//get data for a row from excel
var meterNo = Convert.ToString(sheet.Cells[row, 1].Value);
int? sanctionLoadMains = (int)Convert.ToDecimal(sheet.Cells[row, 2].Value);
int? sanctionLoadDG = (int)Convert.ToDecimal(sheet.Cells[row, 3].Value);
int? unitArea = (int)Convert.ToDecimal(sheet.Cells[row, 4].Value);
int? creditLimit = (int)Convert.ToDecimal(sheet.Cells[row, 5].Value);
int? sMSWarning = (int)Convert.ToDecimal(sheet.Cells[row, 6].Value);
int? sMSWarning1 = (int)Convert.ToDecimal(sheet.Cells[row, 7].Value);
string date = sheet.Cells[row, 8].Value.ToString();
DateTime billingDate;
if (string.IsNullOrEmpty(date))
{
errorMessages.Add("Date is not given for MeterNo " + meterNo + " at row " + row);
continue;
}
if (!DateTime.TryParseExact(date, "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None, out billingDate))
{
errorMessages.Add("Date format is not correct for MeterNo. " + meterNo + " at row " + row);
continue;
}
if (!string.IsNullOrEmpty(meterNo))
{
meterNo = meterNo.PadLeft(9, '0');
var oldMeter = _meterRepository.GetBySiteIdAndMeterNo(siteId, meterNo);
var newMeter = _meterRepository.GetBySiteIdAndMeterNo(siteId, meterNo);
int wattUnit = 1000;//loads should be multiple of 1000(watt)
int smsWarningUnit = 100;//sms warnings should be multiple of 100
if (newMeter == null)
{
errorMessages.Add("MeterNo. " + meterNo + " does not exist.");
continue;
}
if (sanctionLoadMains.HasValue && sanctionLoadMains >= 500)
{
newMeter.LoadSenctionMain = sanctionLoadMains.Value;
}
if (sanctionLoadDG.HasValue && sanctionLoadDG >= 500)
{
newMeter.LoadSenctionDG = sanctionLoadDG.Value;
}
if (unitArea.HasValue)
{
newMeter.UnitArea = unitArea.Value;
}
if (creditLimit.HasValue)
{
newMeter.CreditLimit = creditLimit.Value;
}
if (sMSWarning.HasValue && sMSWarning >= 100)
{
newMeter.SMSWarningAmount = sMSWarning.Value;
}
if (sMSWarning1.HasValue && sMSWarning1 >= 100)
{
newMeter.SMSWarning1Amount = sMSWarning1.Value;
}
if (billingDate != null)
{
newMeter.BillingDate = billingDate.ToIndiaDateTime();
}
_meterRepository.AddOrUpdate(newMeter);
var meterNotes = Helpers.MeterHelpers.Functions.GetMeterNote(oldMeter, newMeter);
Helpers.MeterHelpers.Functions.AddMeterNotes(meterNo, meterNotes);
totalProcessedMeters++;
}
}
TempData["SuccessMessage"] = totalProcessedMeters + " Meter(s) have been updated successfully";
}

how to check error conditions c#

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.

How to add values of 2 textboxes and check whether its equal to the third?

I have a form where I've multiple textboxes and a dropdown menu with it.
I want to calculate and check whether the sum of these textboxes is equal to third with each textbox has a dropdown menu along with it and the values of that dropdown menu are +1 or -1. For example, I have controls as following:
txt1 with ddl1; txt2 with ddl2; txt3 with ddl3; txt4 with ddl4;
I want to check whether:
txt1 * ddl1 = ((txt2 * ddl2) + (txt3 * ddl3) + (txt4 * ddl4))
Also, I am using a custom validator and want to check this condition in it.
Hope you need to change you textbox and ddl value to integer first.
int txt1 = Convert.ToInt32(TextBox1.Text);
int dd1 = Convert.ToInt32(DropDownList1.SelectedValue);
int txt2 = Convert.ToInt32(TextBox2.Text);
int dd2 = Convert.ToInt32(DropDownList2.SelectedValue);
int txt3 = Convert.ToInt32(TextBox3.Text);
int dd3 = Convert.ToInt32(DropDownList3.SelectedValue);
if (txt1 * dd1 == (txt2 * dd2) + (txt3 * dd3))
{
//YOur code here
}
function Total() {
var sumofall;
var FirstText = document.getElementById('txt1').value;
var SecondText = document.getElementById('txt2').value;
var ThirdText = document.getElementById('txt3').value;
var FouthText = document.getElementById('txt4').value;
var dropdown = document.getElementById("ddl1");
var dropdown2 = document.getElementById("ddl2");
var dropdown3 = document.getElementById("ddl3");
var dropdown4 = document.getElementById("ddl4");
var value = dropdown.options[dropdown.selectedIndex].value;
var value2 = dropdown2.options[dropdown2.selectedIndex].value;
var value3 = dropdown3.options[dropdown3.selectedIndex].value;
var value4 = dropdown4.options[dropdown4.selectedIndex].value;
var text = dropdown.options[dropdown.selectedIndex].text;
var text2 = dropdown2.options[dropdown2.selectedIndex].text;
var text3 = dropdown3.options[dropdown3.selectedIndex].text;
var text4 = dropdown4.options[dropdown4.selectedIndex].text;
if (FirstText == "")
FirstText = 0;
if (dropdown == "")
dropdown = 0;
var result = parseInt(FirstText) * parseInt(text);
if (!isNaN(result)) {
}
if (SecondText == "")
SecondText = 0;
if (dropdown2 == "")
dropdown2 = 0;
if (ThirdText == "")
ThirdText = 0;
if (dropdown3 == "")
dropdown3 = 0;
if (FouthText == "")
FouthText = 0;
if (dropdown4 == "")
dropdown4 = 0;
var result2 = parseInt(SecondText) * parseInt(text2);
var result3 = parseInt(ThirdText) * parseInt(text3);
var result4 = parseInt(FouthText) * parseInt(text4);
if (!isNaN(result2) && !isNaN(result3) && !isNaN(result4)) {
sumofall = result2 + result3 + result4;
}
if (result == sumofall)
alert('Something');
else
alert('Error..Not Matched');
return false;
}
In the server function of the custom validator you can write:
int firstValue = 0;
if(int32.TryParse(txt1.Text), out firstValue)
{
int secondValue = 0;
if(int32.TryParse(txt2.Text), out secondValue)
{
// ...
// check other value, then
arg.IsValid = firstValue * Convert.ToInt32(ddl1.SelectedValue) ==
(secondValue * Convert.ToInt32(ddl2.SelectedValue)) +
(thirdValue * Convert.ToInt32(ddl3.SelectedValue)) +
(fourthValue * Convert.ToInt32(ddl4.SelectedValue));
}
else
lblEsito = "Il valore nel secondo TextBox non è un intero";
}
else
lblEsito = "Il valore nel primo TextBox non è un intero";
I have supposed values of dropdownlists are integer and any "Select" with value "0" or "" is present in the dropdownlist controls.
Next time you have to post some code.

Delete and remove the row matching string?

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.

Categories