I have a project and I am trying to sum up rows of the same ID together.
Like for example:
ID Quantity
1 5
1 7
2 10
2 18
1 8
So when I press a button, quantity under ID 1 will give me 20 and for ID 2, I will get 28.
But I faced an error specifying that "Object reference is not set to an instance of an object". Below are my codes:
id = int.Parse(row.Cells[0].Value.ToString());
This is the code that shows the error msg:
int id = 0;
int qty = 0;
List<QuantityPerID> qtyList = new List<QuantityPerID>();
QuantityPerID qtyObj;
foreach (DataGridViewRow row in dataGridView1.Rows)
{
id = int.Parse(row.Cells[0].Value.ToString());
qty = int.Parse(row.Cells[1].Value.ToString());
qtyObj = new QuantityPerID();
bool ifexists = false;
if (qtyList != null && qtyList.Count() > 0)
{
if (qtyList.Where(q => q.ID == id).Count() > 0)
{
ifexists = true;
}
}
if (ifexists)
{
qtyObj = qtyList.Where(q => q.ID == id).First();
qtyObj.Quantity += qty;
}
else
{
qtyObj.ID = id;
qtyObj.Quantity = qty;
qtyList.Add(qtyObj);
}
}
I would like to ask also is there any other easier method to achieve the same results?
Are you sure that Cells[0] and Cells[1] are not empty? You are calling the ToString on it's Values. Check if the Value is null before the call to ToString
if( null != row.Cells[0].Value )
{
id = int.Parse(row.Cells[0].Value.ToString());
}
if(null != row.Cells[1].Value)
{
qty = int.Parse(row.Cells[1].Value.ToString());
}
Do you see an empty line at the end of the rows? Does the DataGridView.AllowUserToAddRows property set to true?
If so, then this is the issue. You are also reading the values of the empty line.
Instead of the foreach, you can do it with a for loop
// notice the Count - 1.
for(var index = 0; index < dataGridView1.Rows.Count - 1; ++index)
{
// your code here
}
Split this definition
id = int.Parse(row.Cells[0].Value.ToString());
into multiple parts to see what is generating your NullReferenceException (and possibly the Qty one too).
Or, at runtime, you could check the Cells' values using IntelliSense (if you hover above "Cells", or "row" it will show you their contents".
Related
Allow users to leave completely empty one or two empty rows. If any of the cells in rows have been filled out, then call out for the users to fill out the rest of the cells and tell them which row/line that cell lives in to fill.
Ideal logic to implement is: If empty row is found, skip it and go the the next row and find if any cell is left to fill,if found empty, skip go the next one.
I have two classes. The class below makes sure if the row is completely empty.
public bool isRowEmpty(DataTable dt, int index)
{
// check if index exists, if not returns false
// it will means that the row is "not empty"
if (index >= dt.Rows.Count || index < 0)
return false;
// Get row
DataRow dr = dt.Rows[index];
// Amount of empty columns
int emptyQt = 0;
// Run thourgh columns to check if any of them are empty
for (int i = 0; i < dr.ItemArray.Length; i++)
{
// If empty, add +1 to the amount of empty columns
if (string.IsNullOrWhiteSpace(dr.ItemArray[i].ToString()))
emptyQt++;
}
// if the amount of empty columns is equals to the amount of
//columns, it means that the whole row is empty
return emptyQt == dr.Table.Columns.Count;
}
Using the class above, I determine which row is empty within the next class, if found empty I will skip and go the next row, if found not empty find any cells that are not filled.
But the code below is not skipping the complete blank rows. Any insights?
public DataValidationModel Validate(DataTable data, IList<FieldModel> fields)
{
var fieldsSorted = fields.Where(f => f.IsInTaxonomy == true).OrderBy(f => f.TaxonomyPosition).ToList();
var model = new DataValidationModel()
{
Errors = new List<RowErrorModel>()
};
int rowCounter = 7;
for (int i =0; i < data.Rows.Count - 1; i++) //Rows.Count - 1,
{
if (!isRowEmpty(data, rowCounter-1) && isRowEmpty(data, rowCounter) && !isRowEmpty(data, rowCounter + 1))
i+=1;
if (data.Rows[rowCounter][0] == DBNull.Value || String.IsNullOrWhiteSpace(data.Rows[i][0].ToString()))
{
model.Errors.Add(new RowErrorModel()
{
Row = rowCounter,
Error = "The name cannot be blank."
});
}
if (data.Rows[rowCounter]["Site"] == DBNull.Value || String.IsNullOrWhiteSpace(data.Rows[i]["Site"].ToString()))
{
model.Errors.Add(new RowErrorModel()
{
Row = rowCounter,
Error = "Site is required."
});
}
if (data.Rows[rowCounter]["start date"] == DBNull.Value)
{
model.Errors.Add(new RowErrorModel()
{
Row = rowCounter,
Error = "start date is required."
});
}
if (data.Rows[rowCounter]["end date"] == DBNull.Value)
{
model.Errors.Add(new RowErrorModel()
{
Row = rowCounter,
Error = "end date is required."
});
}
if (data.Rows[rowCounter]["Placement Type"] == DBNull.Value)
{
model.Errors.Add(new RowErrorModel()
{
Row = rowCounter,
Error = "Placement Type is required."
});
}
if (data.Rows[rowCounter]["Channel"] == DBNull.Value)
{
model.Errors.Add(new RowErrorModel()
{
Row = rowCounter,
Error = "Channel is required."
});
}
if (data.Rows[rowCounter]["Environment"] == DBNull.Value)
{
model.Errors.Add(new RowErrorModel()
{
Row = rowCounter,
Error = "Environment is required."
});
}
if (data.Rows[rowCounter]["rate type"] == DBNull.Value)
{
model.Errors.Add(new RowErrorModel()
{
Row = rowCounter,
Error = "rate is required when a rate type is not blank."
});
}
if (data.Rows[rowCounter]["units"] == DBNull.Value)
{
model.Errors.Add(new RowErrorModel()
{
Row = rowCounter,
Error = "units is required when a rate type is not blank."
});
}
if (data.Rows[rowCounter]["cost"] == DBNull.Value)
{
model.Errors.Add(new RowErrorModel()
{
Row = rowCounter,
Error = "cost is required when a rate type is not blank."
});
}
model.Errors = model.Errors.OrderBy(f => f.Row).ToList();
return model;
}
I show you an example which is not related to your additional logic.
public bool isRowEmpty(DataTable dt, int index)
{
DataRow row = dt.Rows[index];
return dt.Columns.Cast<DataColumn>()
.All(c => row.IsNull(c) || string.IsNullOrWhiteSpace(row[c].ToString()));
}
In the foreach or for-loop you just need to use continue:
for (int i = 0; i < data.Rows.Count; i++)
{
if (isRowEmpty(data, i))
continue;
// ...
}
Why can't you use continue once you found that the row is empty per your comment like
for (int i =0; i < data.Rows.Count - 1; i++) //Rows.Count - 1,
{
if (!isRowEmpty(data, rowCounter-1) && isRowEmpty(data, rowCounter) && !isRowEmpty(data, rowCounter + 1))
continue; // this one here, which will jump to next iteration
How to get start index and last index of all the cells having same value in a DataTable for a specific column?
Such as if my DataTable looks like below:
column1 column2
a 0
a 1
a 2
b 3
b 4
b 5
So that I want the output to be start index as 0 for value a in column1 and last index of 2 for value of a in column1.
Similarly, 3 and 5 for start and last index for value b in column1.
Would something like this work?
class Index // Edit here
{
public string value;
public int first;
public int last;
}
List<Index> indexes = new List<Index>();
foreach (DataGridViewRow row in dataGridView1.Rows)
{
Index ind = indexes.SingleOrDefault(i => i.value == row.Cells[0].Value.ToString()); // Remember to set the correct index of the column
if (ind == null) // Edit here
{
ind = new Index(); // Edit here
ind.value = row.Cells[0].Value.ToString(); // Remember to set the correct index of the column
ind.first = ind.last = row.Index;
indexes.Add(ind);
}
else
{
ind.last = row.Index;
}
}
This should create a list of classes with the variables: value, first and last, which would be the values you're looking for.
I hope this helps.
Edit: I made some changes to the code, where 'Index' is a class and not a struct. Does this work better?
I know this question have been asked multiple times . But I could not find much help from anyone of those.
I don't want to convert the excel into data table but I want it to be converted to a list of objects and sent to server side for processing.
If it has more than 2K rows it should throw an error. Currently what I am doing is something like :
using (var excel = new ExcelPackage(hpf.InputStream))
{
var ws = excel.Workbook.Worksheets["Sheet1"];
for (int rw = 4; rw <= ws.Dimension.End.Row; rw++)
{
if (ws.Cells[rw, 1].Value != null)
{
int headerRow = 2;
GroupMembershipUploadInput gm = new GroupMembershipUploadInput();
for (int col = ws.Dimension.Start.Column; col <= ws.Dimension.End.Column; col++)
{
var s = ws.Cells[rw, col].Value;
if (ws.Cells[headerRow, col].Value.ToString().Equals("Existing Constituent Master Id"))
{
gm.cnst_mstr_id = (ws.Cells[rw, col].Value ?? (Object)"").ToString();
}
else if (ws.Cells[headerRow, col].Value.ToString().Equals("Prefix of the constituent(Mr, Mrs etc)"))
{
gm.cnst_prefix_nm = (ws.Cells[rw, col].Value ?? (Object)"").ToString();
}
else if (ws.Cells[headerRow, col].Value.ToString().Equals("First Name of the constituent(Mike)"))
{
gm.cnst_first_nm = (ws.Cells[rw, col].Value ?? (Object)"").ToString();
}
.....................
.....................
}
}
iUploadedCnt = iUploadedCnt + 1; //Increase the count by 1
}
if (lgl.GroupMembershipUploadInputList.Count < 2003) //Check for the uploaded list count
{
//throw the error
}
But this approach seems slow.
Conversion of the excel to list seems slow to me. For example , when I upload more than 2k records , the list gets converted first to list and then the count is checked if more than 2003 . This process is definitely slower.
How can it be achieved in a faster /better way ?
You do a lot of repeated string processing which is unnecessary. For each row you check the column headers again if they fit some predefined value. (for instance if (ws.Cells[headerRow, col].Value.ToString().Equals("Existing Constituent Master Id")).
You could do this once before you start parsing all rows and create for instance a Dictionary<int, SomeEnum> which maps the column number to a specific enum value. When parsing the rows you then can make a quick lookup in the dictionary, which column maps to which property.
Furthermore, you define a var s = ws.Cells[rw, col].Value; but never use it. Instead, you read this cell value again, when you assign it to a property of your object. You could just make the necessary conversions and checks here, and then use only s;
// define this enum somewhere
enum ColumPropEnum {
cnst_mstr_id, cnst_prefix_nm, ...
}
//define this prop somewhere
Dictionary<int, ColumnPropEnum> colprops = new Dictionary<int, ColumnPropEnum>();
//do this once before processing all rows
for (int col = ws.Dimension.Start.Column; col <= ws.Dimension.End.Column; col++) {
if (ws.Cells[headerRow, col].Value.ToString().Equals("Existing Constituent Master Id"))
colprops.Add(col, ColumnPropEnum.cnst_mstr_id);
else if (ws.Cells[headerRow, col].Value.ToString().Equals(" ..."))
colprops.Add(col, ColumnPropEnum.cnst_prefix_nm);
...
}
//now use this dictionary in each row
for (int rw = 4; rw <= ws.Dimension.End.Row; rw++)
{
....
for (int col = ws.Dimension.Start.Column; col <= ws.Dimension.End.Column; col++) {
//the single ? checks, whether the Value is null, if yes it returns null, otherwise it returns ToString(). Then the double ?? checks whether the result if the operation is null, if yes, it assigns "" to s, otherwise the result of ToString();
var s = ws.Cells[rw, col].Value?.ToString() ?? "";
ColumnPropEnum cp;
if (colpros.TryGetValue(col, out cp)) {
switch (cp) {
case cnst_mstr_id: gm.cnst_mstr_id = s; break;
case cnst_prefix_nm: gm.cnst_prefix_nm = s; break;
...
}
}
}
}
I'm not sure at which position you add this object to a list or upload it to the server, as this is not part of the code. But it could be faster, to first check only the first column of each row if you have the necessary count of non-null values and throw an error if not and do all the other processing only if you didn't throw the error.
int rowcount = 0;
//If you need at minimum 2000 rows, you can stop after you count 2000 valid rows
for (int rw = 4; rw <= ws.Dimension.End.Row && rowcount < 2000; rw++)
{
if (ws.Cells[rw, 1].Value != null) rowcount++
}
if (rowcount < 2000) {
//throw error and return
}
//else do the list building and uploading
I am trying to get the database values and binding to data table by using the following query
sql = #"SELECT member_Id, 30*memberToMship_ChargePerPeriod / DateDiff(memberToMship_EndDate,
memberToMship_StartDate) As monthlyamount,
PERIOD_DIFF(DATE_FORMAT(now(),'%Y%m'),
DATE_FORMAT(memberToMship_StartDate,'%Y%m')) + (DAY(memberToMship_StartDate) < memberToMship_DueDay)+ (DAY(now()) > memberToMship_DueDay)-1 AS ExpPayments,
SUM(memberToMship_InductionFee+memberToMship_JoinFee+
(IF(mshipOption_Period='year',
TIMESTAMPDIFF (YEAR ,memberToMship_StartDate, memberToMship_EndDate),
TIMESTAMPDIFF (MONTH ,memberToMship_StartDate, memberToMship_EndDate)) * memberToMship_ChargePerPeriod)) as value
FROM membertomships
INNER JOIN mshipoptions on membertomships.mshipOption_Id = mshipoptions.mshipoption_Id";
and this is my code for getting the data to datable from database
string memberid;
double value = 0.0;
double expectedpayment=0.0;
double monthlypayamount=0.0;
int dueday = 0;
dt = xxxxxx.GetData(sql, mf);
if (dt != null && dt.Rows.Count > 0)
{
memberid = Convert.ToInt32(dt.Rows[0]["member_Id"]).ToString();
monthlypayamount = Convert.ToDouble(dt.Rows[1]["monthlyamount"]);
expectedpayment = Convert.ToDouble(dt.Rows[2]["ExpPayments"]);
value = Convert.ToDouble(dt.Rows[3]["value"]);
}
but I am getting an error
" index out of range exception"
and error like this
"there is no row at position 1"
Would any one please help on this...
You should use index [0] for Rows on every line of code if you want to get all the data from the first row that was returned. If you use Rows[1] and Rows[2] etc., then you are looking at the second row, and third row, etc., which is invalid if your query only returned one row of data.
You're checking for
dt.Rows.Count > 0
And then accessing rows 0, 1, 2, and 3, without checking if all of these rows exist. I think you've confused row numbers with columns, and should try
memberid = Convert.ToInt32(dt.Rows[0]["member_Id"]).ToString();
monthlypayamount = Convert.ToDouble(dt.Rows[0]["monthlyamount"]);
expectedpayment = Convert.ToDouble(dt.Rows[0]["ExpPayments"]);
value = Convert.ToDouble(dt.Rows[0]["value"]);
if (dt != null && dt.Rows.Count > 0)
{
memberid = Convert.ToInt32(dt.Rows[0]["member_Id"]).ToString();
monthlypayamount = Convert.ToDouble(dt.Rows[1]["monthlyamount"]);
expectedpayment = Convert.ToDouble(dt.Rows[2]["ExpPayments"]);
value = Convert.ToDouble(dt.Rows[3]["value"]);
}
Your if statement is only checking for the existence of 1 or more rows. However, when you set monthlypayamount you are assuming a second row (dt.Rows[1]["monthlyamount"]). I think you need to use a foreach loop to iterate the results
foreach(DataRow row in dt.Rows)
{
memberid = Convert.ToInt32(row["member_Id"]).ToString();
monthlypayamount = Convert.ToDouble(row["monthlyamount"]);
expectedpayment = Convert.ToDouble(row["ExpPayments"]);
value = Convert.ToDouble(row["value"]);
//logic here to use variable values before moving to next row
}
This will make sure you get access to all rows
It seems that you are trying to access row 1 however, row 1 doesn't exist. So, it seems that your query is returning only one row that is row 0. Try
if (dt != null && dt.Rows.Count > 0)
{
memberid = Convert.ToInt32(dt.Rows[0]["member_Id"]).ToString();
monthlypayamount = Convert.ToDouble(dt.Rows[0]["monthlyamount"]);
expectedpayment = Convert.ToDouble(dt.Rows[0]["ExpPayments"]);
value = Convert.ToDouble(dt.Rows[0]["value"]);
}
So I have this datagridview that is linked to a Binding source that is binding to an underlying data table. The problem is I need to manual add rows to the datagridview.
This cannot be done while it is bound, so I have to work with the databinding.
If I add the rows to the underlying datatable, when the datatable is saved, the rows are duplicated, probably because the binding source somehow got a hold of a copy and inserted it also.
Adding it to the binding source is what I've been trying to do but it's not quite working.
Let me explain exactly what my setup is:
I have a database with two tables:
CashReceiptTable and CashReceiptItemsTable
CashReceiptItemsTable contains a FK to CashReceiptTable.
The form allows the users to add, and modify the two tables.
When the user enters a new cashreceipt, the cash receipt's id is -1, and the FK in cashReceiptitemstable is -1. When the database is saved, cashReceipt's id is updated, and I have to manually update cashreceiptitem's FK.
Here are the problems:
When I try to update the CashReceiptID (the FK) in more than one row in cashreceiteitems binding source, the first row is updated, and disappears (because it's filtered), and the other rows are removed, and I can no longer access them.
I have no idea why this is, I haven't updated the filter yet so they should still be there, but trying to access them throws RowNotInTableException.
I've managed a work around that copies the rows in the the binding source to an in memory array, deletes the first row in the binding source (all the other rows just vanish), update the row's FK and reinsert them into the binding source and save the table.
This works okay, but why do the rows disappear?
I also have one more slight problem. When the CashReceiptsTable is empty and I am adding a new row to it, if I add more than one row to the CashReceiptsItemTable it causes problems. When manually adding the items to the binding source, adding a new row pops to previous row off and pushes it onto the datatable. This hides it from my FK updating routine and it is lost, it also removes it from the DataGridView.
It only does that when I'm adding the first row to CashReceiptsTable. Why does it do this, and how can I fix it?
I'm posting my code that autopopulates it here:
private void autopopulate(decimal totalPayment) {
//remove old rows
for (int i = 0; i < tblCashReceiptsApplyToBindingSource.List.Count; i++) {
DataRowView viewRow = tblCashReceiptsApplyToBindingSource.List[i] as DataRowView;
RentalEaseDataSet.tblCashReceiptsApplyToRow row = viewRow.Row as RentalEaseDataSet.tblCashReceiptsApplyToRow;
if (row.CashReceiptsID == this.ReceiptID) {
tblCashReceiptsApplyToBindingSource.List.Remove(viewRow);
i--;
}
}
decimal payment = totalPayment;
//look for an exact amount
foreach (DataGridViewRow dueRow in dataViewDueRO.Rows) {
decimal due = -1 * (Decimal)dueRow.Cells[Due.Index].Value;
if (due == payment) {
String charge = (String)dueRow.Cells[Description.Index].Value;
int chargeID = ManageCheckbooks.findTransactionID(charge);
tblCashReceiptsApplyToBindingSource.AddNew();
RentalEaseDataSet.tblCashReceiptsApplyToRow row = ((DataRowView)tblCashReceiptsApplyToBindingSource.Current).Row as RentalEaseDataSet.tblCashReceiptsApplyToRow;
row.CashReceiptsID = this.ReceiptID;
row.ApplyTo = chargeID;
row.Paid = payment; //convert to positive
payment = 0;
break;
}
}
//if the exact amount was found, payment will = 0, and this will do nothing, otherwise,
//divy out everything left over (which will be everything)
foreach (DataGridViewRow dueRow in dataViewDueRO.Rows) {
String charge = (String)dueRow.Cells[Description.Index].Value;
decimal due = (Decimal)dueRow.Cells[Due.Index].Value;
if (due > 0 || payment <= 0) {
continue;
}
int chargeID = ManageCheckbooks.findTransactionID(charge);
payment += due; //due is negative, so this will subtract how much the user owes
tblCashReceiptsApplyToBindingSource.AddNew();
RentalEaseDataSet.tblCashReceiptsApplyToRow row = ((DataRowView)tblCashReceiptsApplyToBindingSource.Current).Row as RentalEaseDataSet.tblCashReceiptsApplyToRow;
row.CashReceiptsID = this.ReceiptID;
row.ApplyTo = chargeID;
if (payment >= 0) {
//payment is enough to cover this
row.Paid = due * -1; //convert to positive
} else {
//doesn't have enough money to conver this, can only cover partial, or none
row.Paid = (due - payment) * -1; //math:
//money remaining $50, current charge = $60
//payment = 50 + -60 = -10
//row["Paid"] = (-60 - -10) * -1
//row["Paid"] = (-60 + 10) * -1
//row["Paid"] = -50 * -1
//row["Paid"] = 50
}
if (payment <= 0) {
break; //don't conintue, no more money to distribute
}
}
isVirginRow = true;
}
And this is the function that saves it to the database:
protected override void saveToDatabase() {
tblCashReceiptsBindingSource.EndEdit();
isVirginRow = false;
RentalEaseDataSet.tblCashReceiptsRow[] rows = rentalEaseDataSet.tblCashReceipts.Select("ID < 0") as RentalEaseDataSet.tblCashReceiptsRow[];
int newID = -1;
if (rows.Count() > 0) {
tblCashReceiptsTableAdapter.Update(rows[0]);
newID = rows[0].ID;
}
tblCashReceiptsTableAdapter.Update(rentalEaseDataSet.tblCashReceipts);
//update table
/*foreach (RentalEaseDataSet.tblCashReceiptsApplyToRow row in rentalEaseDataSet.tblCashReceiptsApplyTo.Select("CashReceiptsID = -1")) {
row.CashReceiptsID = newID;
}*/
//update binding source
DataRowView[] applicationsOld = new DataRowView[tblCashReceiptsApplyToBindingSource.List.Count];
RentalEaseDataSet.tblCashReceiptsApplyToRow[] applicationsNew = new RentalEaseDataSet.tblCashReceiptsApplyToRow[tblCashReceiptsApplyToBindingSource.List.Count];
tblCashReceiptsApplyToBindingSource.List.CopyTo(applicationsOld, 0);
for (int i = 0; i < applicationsOld.Count(); i++) {
RentalEaseDataSet.tblCashReceiptsApplyToRow row = applicationsOld[i].Row as RentalEaseDataSet.tblCashReceiptsApplyToRow;
if (row.CashReceiptsID < 0) {
applicationsNew[i] = rentalEaseDataSet.tblCashReceiptsApplyTo.NewRow() as RentalEaseDataSet.tblCashReceiptsApplyToRow;
applicationsNew[i]["ID"] = row.ID;
applicationsNew[i]["CashReceiptsID"] = this.ReceiptID;
applicationsNew[i][2] = row[2];
applicationsNew[i][3] = row[3];
applicationsNew[i][4] = row[4];
//row.Delete();
}
}
for (int i = 0; i < applicationsOld.Count(); i++) {
try {
if ((int)applicationsOld[i].Row["ID"] < 0) {
applicationsOld[i].Row.Delete();
}
} catch (RowNotInTableException) {
break;
}
}
this.tblCashReceiptsApplyToBindingSource.Filter = "CashReceiptsID = " + this.ReceiptID;
foreach (DataRow newRow in applicationsNew) {
if (newRow == null) {
break;
}
tblCashReceiptsApplyToBindingSource.AddNew();
((DataRowView)tblCashReceiptsApplyToBindingSource.Current).Row[0] = newRow[0];
((DataRowView)tblCashReceiptsApplyToBindingSource.Current).Row[1] = newRow[1];
((DataRowView)tblCashReceiptsApplyToBindingSource.Current).Row[2] = newRow[2];
((DataRowView)tblCashReceiptsApplyToBindingSource.Current).Row[3] = newRow[3];
((DataRowView)tblCashReceiptsApplyToBindingSource.Current).Row[4] = newRow[4];
}
tblCashReceiptsApplyToBindingSource.EndEdit();
checkForBadRows();
tblCashReceiptsApplyToTableAdapter.Update(rentalEaseDataSet.tblCashReceiptsApplyTo);
tblCashReceiptsApplyToTableAdapter.Fill(rentalEaseDataSet.tblCashReceiptsApplyTo);
}
You might want to try adding rows to the DataGridView. Since you are binding to it, the DataGridView becomes your 'access point'.
I've got several applications that bind to DataGridView and for most circumstances when I add a row I do so through the DataGridView. It already has properties/methods/events that let you add with relative ease.
If you need some more information I can update.