compare value property - c#

how can I compare value property of item to datatable column called Value? Please help me with the syntax
if ((String)item.Value.IndexOf((string)results("value") Stringcomparison.CurrentCultureIgnoreCase) > -1)
{
returnItems.Add(item);
}

Your question and comment seem to be asking different things, but in both cases the answer is probably to unpick the big long line of code into explanatory variables:
string valueFromTable = currentRow["Value"].ToString();
bool itemValueContainsValueFromTable = item.Value.IndexOf(valueFromTable, StringComparison.CurrentCultureIgnoreCase) >= 0;
bool itemValueEqualsValueFromTable = item.Value.Equals(valueFromTable, StringComparison.CurrrentCultureIgnoreCase);
if (/* whichever of these you are interested in */)
{
returnItems.Add(item);
}
(ignoring error cases here, specifically if item.Value is null)
Note that to get a value from the DataTable you will need to pick a row. If you want to see if the item matches any row, then iterate over the rows (foreach (var row in table.Rows)).

Related

DataRow.SetField() gives a null ref exception when adding data to a column I previously deleted then added back

UPDATE
I think I have found what is causing the issue here https://stackoverflow.com/a/5665600/19393524
I believe my issue lies with my use of .DefaultView. The post thinks when you do a sort on it it is technically a write operation to the DataTable object and might not propagate changes made properly or entirely. It is an interesting read and seems to answer my question of why passing valid data to a DataRow is throwing this exception AFTER I make changes to the datatable
UPDATE:
Let me be crystal clear. I have already solved my problem. I would just like to know why it is throwing an error. In my view the code should work and it does.. the first run through.
AFTER I have already deleted the column then added it back (run this code once)
When I debug my code line by line in Visiual studio and stop at the line:
data.Rows[i].SetField(sortColumnNames[k], value);
the row exists
the column exisits
value is not null
sortColumnNames[k] is not null and contains the correct column name
i is 0
Yet it still throws an exception. I would like to know why. What am I missing?
Sorry for the long explanation but this one needs some context unfortunately.
So my problem is this, I have code that sorts data in a DataTable object by column. The user picks the column they want to sort by and then my code sorts it.
I ran into an issue where I needed numbers to sort as numbers not strings (all data in the table is strings). eg (string sorting would result in 1000 coming before 500)
So my solution was to create a temporary column that uses the correct datatype so that numbers get sorted properly and the original string data of the number remains unchanged but is now sorted properly. This worked perfectly. I could sort string numeric data as numeric data without changing the formatting of the number or data type.
I delete the column I used to sort afterwards because I use defaultview to sort and copy data to another DataTable object.
That part all works fine the first time.
The issue is when the user needs to do a different sort on the same column. My code adds back the column. (same name) then tries to add values to the column but then I get a null reference exception "Object not set to an instance of an object"
Here is what I've tried:
I've tried using AcceptChanges() after deleting a column but this did nothing.
I've tried using column index, name, and column object returned by DataTable.Columns.Add() in the first parameter of SetField() in case it was somehow referencing the "old" column object I deleted (this is what I think the problem is more than likely)
I've tried changing the value of the .ItemArray[] directly but this does not work even the first time
Here is the code:
This is the how the column names are passed:
private void SortByColumn()
{
if (cbAscDesc.SelectedIndex != -1)//if the user has selected ASC or DESC order
{
//clears the datatable object that stores the sorted defaultview
sortedData.Clear();
//grabs column names the user has selected to sort by and copies them to a string[]
string[] lbItems = new string[lbColumnsToSortBy.Items.Count];
lbColumnsToSortBy.Items.CopyTo(lbItems, 0);
//adds temp columns to data to sort numerical strings properly
string[] itemsToSort = AddSortColumns(lbItems);
//creates parameters for defaultview sort
string columnsToSortBy = String.Join(",", itemsToSort);
string sortDirection = cbAscDesc.SelectedItem.ToString();
data.DefaultView.Sort = columnsToSortBy + " " + sortDirection;
//copies the defaultview to the sorted table object
sortedData = data.DefaultView.ToTable();
RemoveSortColumns(itemsToSort);//removes temp sorting columns
}
}
This is where the temp columns are added:
private string[] AddSortColumns(string[] items)//adds columns to data that will be used to sort
//(ensures numbers are sorted as numbers and strings are sorted as strings)
{
string[] sortColumnNames = new string[items.Length];
for (int k = 0; k < items.Length; k++)
{
int indexOfOrginialColumn = Array.IndexOf(columns, items[k]);
Type datatype = CheckDataType(indexOfOrginialColumn);
if (datatype == typeof(double))
{
sortColumnNames[k] = items[k] + "Sort";
data.Columns.Add(sortColumnNames[k], typeof(double));
for (int i = 0; i < data.Rows.Count; i++)
{
//these three lines add the values in the original column to the column used to sort formated to the proper datatype
NumberStyles styles = NumberStyles.Any;
double value = double.Parse(data.Rows[i].Field<string>(indexOfOrginialColumn), styles);
bool test = data.Columns.Contains("QtySort");
data.Rows[i].SetField(sortColumnNames[k], value);//this is line that throws a null ref exception
}
}
else
{
sortColumnNames[k] = items[k];
}
}
return sortColumnNames;
}
This is the code that deletes the columns afterward:
private void RemoveSortColumns(string[] columnsToRemove)
{
for (int i = 0; i < columnsToRemove.Length; i++)
{
if (columnsToRemove[i].Contains("Sort"))
{
sortedData.Columns.Remove(columnsToRemove[i]);
}
}
}
NOTE:
I've been able to fix the problem by just keeping the column in data and just deleting the column from sortedData as I use .Clear() on the sorted table which seems to ensure the exception is not thrown.
I would still like an answer though as to why this is throwing an exception. If I use .Contains() on the line right before the one where the exception is thrown is says the column exists and returns true and in case anyone is wondering the params sortColumnNames[k] and value are never null either.
Your problem is probably here:
private void RemoveSortColumns()
{
for (int i = 0; i < data.Columns.Count; i++)
{
if (data.Columns[i].ColumnName.Contains("Sort"))
{
data.Columns.RemoveAt(i);
sortedData.Columns.RemoveAt(i);
}
}
}
If you have 2 columns, and the first one matches the if, you will never look at the second.
This is because it will run:
i = 0
is i < columns.Count which is 2 => yes
is col[0].Contains("sort") true => yes
remove col[0]
i = 1
is i < columns.Count which is 1 => no
The solution is to readjust i after the removal
private void RemoveSortColumns()
{
for (int i = 0; i < data.Columns.Count; i++)
{
if (data.Columns[i].ColumnName.Contains("Sort"))
{
data.Columns.RemoveAt(i);
sortedData.Columns.RemoveAt(i);
i--;//removed 1 element, go back 1
}
}
}
I fixed my original issue by changing a few lines of code in my SortByColumn() method:
private void SortByColumn()
{
if (cbAscDesc.SelectedIndex != -1)//if the user has selected ASC or DESC order
{
//clears the datatable object that stores the sorted defaultview
sortedData.Clear();
//grabs column names the user has selected to sort by and copies them to a string[]
string[] lbItems = new string[lbColumnsToSortBy.Items.Count];
lbColumnsToSortBy.Items.CopyTo(lbItems, 0);
//adds temp columns to data to sort numerical strings properly
string[] itemsToSort = AddSortColumns(lbItems);
//creates parameters for defaultview sort
string columnsToSortBy = String.Join(",", itemsToSort);
string sortDirection = cbAscDesc.SelectedItem.ToString();
DataView userSelectedSort = data.AsDataView();
userSelectedSort.Sort = columnsToSortBy + " " + sortDirection;
//copies the defaultview to the sorted table object
sortedData = userSelectedSort.ToTable();
RemoveSortColumns(itemsToSort);//removes temp sorting columns
}
}
Instead of sorting on data.DefaultView I create a new DataView object and pass data.AsDataView() as it's value then sort on that. Completely gets rid of the issue in my original code. For anyone wondering I still believe it is bug with .DefaultView in the .NET framework that Microsoft will probably never fix. I hope this will help someone with a similar issue in the future.
Here is the link again to where I figured out a solution to my problem.
https://stackoverflow.com/a/5665600

Skip Records by String Matching

I'm looping through a large excel file full of Products. We want to only process rows where Brand = x, or Product = 'y'. The following code worked there was a predictable filter ie. Product1, however we are unsure what data the xsl file will hold and it could be something like "Product1 (buy me)" which wouldn't pass with this logic and the record would get ignored.
What technique can we use to match Product names with our filters? Regex, pattern matching etc. ? Or do I simply need to split the filter and loop through each? Seems like there shuold be a more elegant way.
private static bool SkipRecord(string strFilters, string key, DataRow row)
{
//include the record if it matches our filter
var strField = row[key].ToString();
bool skip = true;
if (strField != null && strField != "")
{
skip = !strFilters.ToLower().Contains(strField.ToLower());
}
return skip;
}
List<ResultRow> xlsRows = new List<ResultRow>();
foreach (DataRow row in dataTable.Rows)
{
if (SkipRecord(f.brandFlag, "Brand", row) && SkipRecord(f.productFlag, "Name", row))
continue;
}
appSettings.json
"CustomSettings": {
"BrandFlag": "Gibson|Fender|Jackson",
"ProductFlag": "Product 1|ProductTwo|Product3",
}
(One comment first, I think the first method is missing the
return skip;
line).
For the specific case you mentioned it would work if you changed the order of the "Contains" arguments:
skip = !strField.ToLower().Contains(strFilters.ToLower());

How to Edit DataTable Column Value

Excel column name may contain trailing spaces which would hit exception if the column don't match due to spaces.
I am finding ways to handle trailing spaces in the column name in datatable.
foreach (DataRow row in caseTable.Rows)
{
foreach (DataColumn column in caseTable.Columns)
{
if (!(string.isNullOrEmpty(column.toString())))
{
//Cannot assign value to 'column' because it is in a 'foreach iteration variable'
column = column.ToString().TrimStart().TrimEnd();
trimmed = 1;
}
}
while (trimmed == 0) ;
}
...
//errored out due to 'Excel.firstName' value not existing in DataTable due to trailing spaces
if (row[Excel.firstName].ToString().Trim() != "")
{
caseEntity.Attributes[Case.firstName] = row[Excel.firstName];
}
There are two mistakes in your code:
You are iterating a sequence with foreach and trying to modify the iterated items; thus, the exception that is throwing.
You are trying to replace the column object instead of its name.
Additionally, you are abusing ToString and, as already stated by Michal Turczyn, you are not using built-in String methods explicitly designed to test for empty or null strings.
You can try replacing the code inside the inner loop with
var oldName = column.ColumnName;
if (!string.IsNullOrEmpty(oldName))
{
var newName = oldName.Trim();
if (newName != oldName)
{
column.ColumnName = newName;
trimmed = 1;
}
}
From this replacement code You can see that:
You should read/write ColumnName property instead of using ToString.
You can avoid invoking TrimStart and TrimEnd one after another (in any order) by using Trim.
You should use string.IsNullOrEmpty instead of checking for null andempty string.
By declaring oldName and newName, you can track a column name as trimmed only when that's really true.
More over, if you are assigning only values 0 and 1 to trimmed variable, then you should consider declaring it as bool and assign false or true.
Otherwise you can keep trimmed variable as a number, but increasing its value rather than assigning always the same constant (1).
If what you are trying to change is not the column name, but is the cell value in the current row for such column, then you are missing to get (and later set) the cell value (you are evaluating and trying to change only the column name).
In that case, the inner loop code become:
var oldValue = row[column] as string;
if (!string.IsNullOrEmpty(oldValue))
{
var newValue = oldValue.Trim();
if (newValue != oldValue)
{
row[column] = newValue;
trimmed = 1;
}
}

Test for an empty DataRow in C#

what I'm trying to do: I have a large datatable, and I'm going through a list of strings where some of them are in the datatable and some aren't. I need to make a list of those that are, and count those that aren't.
This is my code part:
DataRow[] foundRows;
foundRows = DTgesamt.Select("SAP_NR like '%"+SAP+"%'");
if (AreAllCellsEmpty(foundRows[0]) == false && !(foundRows[0]==null))
{
list.Add(SAP);
}
else
{
notfound++;
}
public static bool AreAllCellsEmpty(DataRow row)
{
if (row == null) throw new ArgumentNullException("row");
for (int i = row.Table.Columns.Count - 1; i >= 0; i--)
{
if (!row.IsNull(i))
{
return false;
}
}
return true;
}
DTgesamt ist a large DataTable. "SAP" is a string that is in the first column of the DataTable, but not all of them are included. I want to count the unfound ones with the int "notfound".
The problem is, the Select returns an empty DataRow {System.Data.DataRow[0]} when it finds nothing.
I'm getting the errormessage Index out of array area.
The two statements in the if-clause are what I read on the internet but they don't work. With only the 2nd statement it just adds all numbers to the list, with the first it still gives this error.
Thanks for any help :)
check count of items in foundRows array to avoid IndexOutOfRange exception
foundRows = DTgesamt.Select("SAP_NR like '%"+SAP+"%'");
if (foundRows.Length > 0 && AreAllCellsEmpty(foundRows[0])==false)
list.Add(SAP);
else
notfound++;
The found cells cannot be empty. Your select statement would be wrong. So what you actually need is:
if (DTgesamt.Select("SAP_NR like '%"+SAP+"%'").Any())
{
list.Add(SAP);
}
else
{
notfound++;
}
You probably don't even need the counter, when you can calculate the missed records based on how many SAP numbers you had and how many results you got in list.
If you have an original list or array of SAP numbers, you could shorten your whole loop to:
var numbersInTable = originalNumbers.Where(sap => DTgesamt.Select("SAP_NR like '%"+sap+"%'").Any()).ToList();
var notFound = originalNumbers.Count - numbersInTable.Count;

Ultrawingrid - Select row based on unique value

Is there a way to select a row in an ultrawingrid based on the value of one of its columns (ID column)? I have been trying to find out how to do this with little success.
I have a global variable that is the 'active ID' (i.e the ID that is currently being edited within the application - it is the ID that the system sees as being selected and active) - but sometimes the selected row of the grid and the 'selected ID' variable don't match. I need to make sure they are the same in order to prevent user confusion. I am hoping to call the following code inside a refresh() function...
Perhaps something like (kinda-pseudo-code-ish):
int index; // This could be any number
foreach (row r in grid)
{
if (row.cell["ID"].value = index)
grid.selectedindex = thisRow;
}
Am I thinking along the right lines? If so, what is the correct syntax? If not, how else should I do this?
Got it.
int index;
foreach (UltraGridRow row in grid.Rows)
{
if (Convert.ToInt32(row.Cells["ID"].Value) == index)
{
grid.ActiveRow = row;
break;
}
}
Works just how I needed it to - sorry for answering my own question ;)
Yes. You can use the FirstOrDefault function to find a row matching a criteria:
var row = ultraGrid1.Rows.FirstOrDefault(r => r.Cells["Id"].Value.ToString() == "1");
Now that you (potentially) have the row where the cell contains the value you'd like, you can activate it to select it:
if (row != null)
row.Activate();
If you are bound to a DataTable or a list that has the ability to find an item by key, you can use the GetRowWithListIndex method of the Rows collection to find the UltraGridRow.
For example the following will activate the row with a key of 5:
DataTable dt = this.ultraGrid1.DataSource as DataTable;
DataRow dr = dt.Rows.Find(5);
this.ultraGrid1.Rows.GetRowWithListIndex(dt.Rows.IndexOf(dr)).Activate();
If your list doesn't support finding an item by key, you could use linq to find the item in the list as well. There is an example of finding an item with link here.
If you have multiple bands you can use the following:
int index;
ultraGrid1.DisplayLayout.Bands.OfType<Infragistics.Win.UltraWinGrid.UltraGridBand>()
.SelectMany(s => s.GetRowEnumerator(Infragistics.Win.UltraWinGrid.GridRowType.DataRow)
.OfType<Infragistics.Win.UltraWinGrid.UltraGridRow>())
.Where(s => s.Cells.Exists("ID"))
.FirstOrDefault(s => (int)s.Cells["ID"].Value == index)?
.Activate();
Note: Null-conditional Operator (?) requires C# 6.0 or higher. Otherwise you have to check, if FirstOrDefault(...)!=null and activate it then.

Categories