Use of Unassigned Local Variable Error C# and LINQ - c#

I am trying to use LINQ to pull information from a database made using SQLite into a List. I am then trying to search that list using text entered from two textboxes on my Windows Store app page. I get a error that states "use of unassigned local variable" once I try and use the list.
private void button_LINQ_Click(object sender, RoutedEventArgs e)
{
List<Notes> manyNotes;
int cursorPosition = TextBox_Results.SelectionStart;
var x = (from n in manyNotes
where (n.Note.Contains(textBox1.Text) && n.Note.Contains(textBox2.Text))
select n).ToList();
TextBox_Results.Text = TextBox_Results.Text.Insert(cursorPosition, "Notes containing " + textBox1.Text + " and " + textBox2.Text + ":\n");
foreach (Notes y in x)
TextBox_Results.Text = TextBox_Results.Text.Insert(cursorPosition, y.Note + "\n");
}

You declare manyNotes as a List, but you never instantiate it with anything (even an empty List). At minimum, you need to change your declaration of the list to:
List<Notes> manyNotes = new List<Notes>();
However, unless I'm not following your code, you still need to add the code to populate the manyNotes List with data. Otherwise, your query to instantiate var x will always be an empty list. It's like you're querying an empty table. No matter what you filter by, selecting any combination of rows from a collection of 0 rows will always return 0 rows. Make sense?

Your problem is here:
List<Notes> manyNotes;
You never intialise this variable and then try to use it in the Linq query.
You can change it to
List<Notes> manyNotes = new List<Notes>();
But this would still result in an empty list (meaning that x would also be empty) but your code will still run.
You need to populate the list for the foreach loop to actually do anything.

Related

c# Object properties is loading from cache

in my win-form application, there is a method that combines some items that have been created previously, when the code is the first time to run, everything is fine, but in second and later runs combined items have the wrong length.
the code reads items from a SQL server using LINQ that has object type named "BetaData"
BetaData has a property named "Length" that is double.
I have another list that processed items is stored in name "PartList" of type "ModifiedPartList".
in method length property changes for some items, but nothing gets stored or saved on SQL.
this is the main method:
private List<ModifiedPartList> CombinePartList(ProgressBar Bar)
{
PartList.Clear();
List<BetaData> PartsinOrder = new List<BetaData>();
foreach (int view in Globals.Views)
{
List<int> OrdersInView = new List<int>();
foreach (Tuple<int, int> tuple in Globals.Orders)
{
if (tuple.Item1 == view)
{
if (!OrdersInView.Contains(tuple.Item2))
OrdersInView.Add(tuple.Item2);
}
}
if(OrdersInView.Count>0)
{
OrdersInView.Sort();
foreach (int order in OrdersInView)
{
//this is the section that problem occurs:
var parts = from BetaData in BetaContext.BetaDatas
where BetaData.ProjectName == Globals.ProjectName &&
BetaData.ProjectCode == Globals.ProjectCode &&
BetaData.ParentItem != Globals.ProjectName + "(" + Globals.ProjectCode + ")" &&
BetaData.View == view &&
BetaData.Order == order
select BetaData;
PartsinOrder.Clear();
PartsinOrder = parts.ToList();
foreach(BetaData part in PartsinOrder)
{
Bar.PerformStep();
}
}
}
PartsinOrder.Clear();
}
return PartList;
}
in the section that i have commented as problem location when the code is running for the second time, optimized length property is loaded to items instead of their original value from SQL. i cannot understand that because each time i read all items from SQL server.
the point is in this stage after that i ran the method for several times and getting the wrong results when i close the program and start it again, on first run results are true.
after selecting from SQL and converting it to list, i review items and their properties in list, and they are all true, but in foreach loop when each part comes into loop their Length property is wrong.
the issue was solved using this article and refreshing context after retrieving data from SQL

Argument Exception - Value does not fall within the expected range

I am trying to get a column value from a SharePoint list and populate it to an ASP text box. I used SPQuery to filter and get the value. I even mentioned view fields and increased the List View Lookup Threshold. But when I am trying to assign the text box value with the column field, I am getting this exception:
Argument exception was unhandled by user- value does not fall within the expected range.
Is there any workaround for this? Code sample:
SPQuery qrySeriesDesc = new SPQuery();
qrySeriesDesc.Query = "<Where><Eq><FieldRef Name='Series'/><Value Type='Text'>" + SeriesNumber + "</Value></Eq></Where>";
qrySeriesDesc.ViewFields = "<FieldRef Name='Series Description'/>";
SPListItemCollection itemCol = list.GetItems(qrySeriesDesc);
foreach (SPListItem item in itemCol)
{
if (item != null)
{
tboxSeriesDescription.Text = item["Series Description"].ToString();
}
}
I am getting the mentioned exception at:
tboxSeriesDescription.Text = item["Series Description"].ToString();
Try to get it from field, not from item:
SPField fieldSerDesc = item.Fields.GetFieldByInternalName("SeriesDescription"); //internal name of your fields. Usually eq StaticName.
tboxSeriesDescription.Text = item[fieldSerDesc.Id].ToString();
Or, if your field is lookup for example, you can do it like this:
SPFieldLookup fieldSerDesc = (SPFieldLookup)item.Fields.GetFieldByInternalName("SeriesDescription");
tboxSeriesDescription.Text = fieldSerDesc.GetFieldValueAsText(item[fieldSerDesc.Id]);
}
You get the error because the field do not exist or is misspelled.
Please note that if you select a column that does not exist SharePoint does not raise any error.
Try to check the field's name using a tool like Sharepoint Manager and use ALWAYS the internal name

How do I modify selected items in asp:listbox for use in a proper string?

Lets say I wanted to create an application for a user to select trouble departments for reporting purposes. The user would go in and select multiple trouble departments from a asp:ListBox and when the user hits send the email would read,
We are having trouble in the following departments: DepartmentA, DepartmentB.
What I have been able to is figure out how to properly loop the items out from the loop, however the last item has a , at the end of the last item. For example instead of reading the proper way as noted above it looks like this:
We are having trouble in the following departments: DepartmentA, DepartmentB,.
Here is my code:
string DeptID = string.Empty;
foreach (ListItem li in lstDSXDepartment.Items)
{
if (li.Selected == true)
{
DeptID += li.Value + ",";
}
}
Response.Write("We are having trouble with the following Departments: " + DeptID + ".");
How do I fix the string so that the comma does not show at the end of list of selections?
You can use string.join. It is much easier.
var ids = lstDSXDepartment.Items
.Cast<ListItem>()
.Where(x=> x.Selected)
.Select(x=> x.Value);
string text = string.Join(",", ids);
Other thought:
If you want to use your original method, you should consider using StringBuilder instead of String because String is immutable.
StringBuilder will significantly improve the performance depending on the number of Items.
Just use a trim function to remove the unwanted comma.
DeptID = DeptID.TrimEnd(',');
Use after the loop, before writing.
Note: The TrimEnd function returns a new copy that is modified of the original string so you have to store it back into your original variable. This is because strings are immutable in C#.

Using lambda expression to get values in an array

Alright, here's the deal. I am doing a data conversion where I'm taking data from two databases and putting it into another. I'm adding a list of contacts, and then I'm adding a list of communication records. In order to simplify the process, I made a small array of all of the communication records with the household address of the contacts. Now I'm trying to use a lambda expression to sort out email addresses from the array, but I'm having a problem. The code so far is as follows:
DataRow[] Comms = dtComms.Select("household_id = " + previousID);
if (Comms.Where(x => x.Field<string>("communication_type") == "Home Phone").Count() > 0)
{
string HomePhone = rNDigits.Replace(Comms[0].Field<string>("communication_value").ToString().Trim(), "");
if (HomePhone.Length > 6)
oAddress._Phone = HomePhone;
}
if (Comms.Where(x => x.Field<string>("communication_type") == "Email").Count() > 0)
{
string FamilyEmail = rNDigits.Replace(Comms[0].Field<string>("communication_value").ToString().Trim(), "");
if (FamilyEmail.Contains('#') && FamilyEmail.Contains('.'))
oAddress._FamilyEmail = FamilyEmail;
}
The problem is that obviously, this always will return the first value in the array, which might not always be the one that I want. How can I change the code so that it selects only the value from the array that matches the entry containing the email? Or, is there a better way to search through values in an array?
I suggesting to use a simple for or foreach loop in this case, LINQ can't modify data only select it.

Convert DataTable to LINQ: Unable to query multiple fields

Importing a spreadsheet I have filled a DataTable object with that data and returns expected results.
Attempting to put this into a format I can easily query to search for problem records I have done the following
public void Something(DataTable dt)
{
var data = from row in dt.AsEnumerable()
select row["Order"].ToString();
}
Works as expected giving me a list of orders. However I cannot add other fields to this EnumerableRowCollection. Attempting to add other fields as follows gives me an error
public void Something(DataTable dt)
{
// row["Version"] throws an error on me
var data = from row in dt.AsEnumerable()
select row["Order"].ToString(), row["Version"].ToString();
}
Error: "A local variable named 'row' cannot be declared in this scope because it would give a different meaning to 'row' which is already used in a 'child' scope to donate something else"
I'm thinking I need to alias the column name but I'm having no luck. What am I missing here?
It sounds like you're writing a bad select statement. Try the following:
public void Something(DataTable dt)
{
var data = from row in dt.AsEnumerable()
select new {
Order = row["Order"].ToString(),
Something = row["Something"].ToString(),
Customer = row["Customer"].ToString(),
Address = row["Address"].ToString()
};
}
That will create a new collection of Anonymously Typed objects that you can iterate over and use as needed. Keep in mind, though, that you want be able to return data from the function. If you need that functionality, you need to create a concrete type to use (in place of anonymous types).
I think you should use select new like this query for example:
var q = from o in db.Orders
where o.Products.ProductName.StartsWith("Asset") &&
o.PaymentApproved == true
select new { name = o.Contacts.FirstName + " " +
o.Contacts.LastName,
product = o.Products.ProductName,
version = o.Products.Version +
(o.Products.SubVersion * 0.1)
};
You probably want the following.
var data = from row
in dt.AsEnumerable()
select new { Order = row["Order"].ToString(), Version = row["Version"].ToString() };

Categories

Resources