Argument Exception - Value does not fall within the expected range - c#

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

Related

Use of Unassigned Local Variable Error C# and LINQ

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.

SharePoint CAML Query: Value does not fall into expected range

I've created the following method in a class which is intended to fetch all items in a SharePont list and load them into my entity:
public List<ItemEntity> FetchItems(SPList list)
{
// build the CAML query of field names that we wish to retreive
var query = new SPQuery
{
ViewFields = string.Concat("<FieldRef Name='Modified' />",
"<FieldRef Name='Modified By' />",
"<FieldRef Name='Created' />",
"<FieldRef Name='Created By' />")
};
SPListItemCollection items = list.GetItems(query);
return (from SPListItem item in items
select Load("", // item id
"", // content type
"", // display name
"", // name
"", // title
"", // url
"", // author
"", // editor
Convert.ToDateTime(item["Modified"]), // date time modified
item["Modified By"].ToString(), // modified by
Convert.ToDateTime(item["Created"]), // date time created
item["Created By"].ToString() // created by
)).ToList();
}
For some reason that I don't understand it's throwing the following error:
Value does not fall within the expected range.
I thought this could be something to do with the results returned by my CAML query, but even then I restricted it down to meta data fields (which I believe should exist on every file) and unfortunately I'm still receiving the error. Where am I going wrong?
I believe you are missing the correct internal names of some built-in fields.
Try to use:
item["Author"].ToString() instead of item["Created By"].ToString() and
item["Editor"].ToString() instead of item["Modified By"].ToString()
For a full reference of sharepoint 2010 internal field names I usually consult the following link:
http://sharepointmalarkey.wordpress.com/2010/10/12/sharepoint-internal-field-names-sharepoint-2010/

Sharepoint list Dynamic Linq query

I need to query a list in SharePoint where the columns may be added in the future.
For instance at the moment I have the following columns
Name, Job, interests, address
I want to be able to query this string dynamically using a parameter from the browser so if columns are added in the future I don’t have to change the code but just the parameter.
The address may look like this www.contoso.com/sites/mypage.aspx?property=Interests
And the code something on the line of this:
var SiteParameter = Request.QueryString["property"];
var ItemsFromList = from item in ListItems where item[try to put the parameter in here] select item;
I use SPmetal to get the list details, so if I press item. Visual Studio2010 will return the columns within the list.
This may be easier without SPMetal.
var qy = new SPQuery();
qy.Query =
"<Where><Eq>" +
"<FieldRef Name=`" + siteParameter + "'/>" +
// You may have to worry about the type of the field here, too.
"<Value Type='Text'>" + desiredValue + "</Value>" +
"</Eq></Where>";
var itemCollection = myList.GetItems(qy);

Only Alternating values in SPFieldMultiChoice saved

I am busy building a custom webpart with various textboxes and lookup fields. All of them are saving correctly apart from the lookup fields that allows for multiple selections. I dont have this problem with lookup fields that only allow for one value to be selected.
Below is the code for getting all the selected items in my checkboxlist, converting it to a multichoice value and assigning to my list[columnname]
try
{
SPFieldMultiChoiceValue _segmentchoices = new SPFieldMultiChoiceValue();
foreach (ListItem ls3 in _segment.Items)
{
if (ls3.Selected) _segmentchoices.Add(ls3.Value);
}
myItems["Segment"] = _segmentchoices;
myItems.Update();
}
catch (Exception ex) { _errorMessage += "||| Segment : " + ex.Message; }
The values list (_segmentchoices) is correctly created and looks like this : {;#1;#2;#3;#4;#5;#}
However when its saved it only saves values 1, 3, and 5.
My code is not generating an error, so I am at a loss at what could be wrong. Any ideas on what I need to look at? Am I going about it the wrong way?
Any assistance would be appreciated.
Thank you
I just realized you are talking about a multi-select lookup field. The format should be something like: 2;#Procedures;#3;#Systems;#7;#Services
The behavior you describe makes sense because it is probably interpreting ;#1;#2;#3;#4;#5;# like this: get the item in the lookup list with a lookupID of 1 (lookupValue is 2), lookupID of 3 (lookupValue is 4), and lookupID of 5 (lookupValue is empty)
Here is some code that you can use to update a multi-select choice field:
using (SPSite site = new SPSite(siteUrl))
{
using (SPWeb web = site.OpenWeb())
{
SPList list = web.Lists[listName];
SPListItem item = list.Items[0];
SPFieldLookupValueCollection spflvc = new SPFieldLookupValueCollection();
spflvc.Add(new SPFieldLookupValue(3, string.Empty));
spflvc.Add(new SPFieldLookupValue(7, string.Empty));
item["Keywords"] = spflvc;
item.Update();
}
}
The second parameter to SPFieldLookupValue doesn't seem to care if it is passed string.Empty which also might explain why it ignores them above.

How do I access the XML data in my column using LINQ to XML?

I have this XML in a column in my table:
<keywords>
<keyword name="First Name" value="|FIRSTNAME|" display="Jack" />
<keyword name="Last Name" value="|LASTNAME|" display="Jones" />
<keyword name="City" value="|CITY|" display="Anytown" />
<keyword name="State" value="|STATE|" display="MD" />
</keywords>
I'm getting a record out of that table using LINQ to SQL via this:
GeneratedArticle ga = db.GeneratedArticles.Single(p => p.GeneratedArticleId == generatedArticleId);
That works, I get my GeneratedArticle object just fine.
I'd like to walk through the data in the ArticleKeywords field, which is XML. I started doing this:
var keywords = from k in ga.ArticleKeywords.Elements("Keywords")
select k;
foreach (var keyword in keywords)
{
//what goes here?
}
I'm not 100% sure that I'm getting that data correctly. I need help with the proper syntax to get the value and display out of my XML field.
Once again I am amazed that people don't even try their answers and people still up vote when they don't work.
The .Elements will get the list of elements at the current root, which is not a keyword.
Also the one using .Attributes["X"] does not even compile you need to use () of course again it would be operating on each instance of "keywords" not "keyword"
You could use
var keywords = from kw in ga.ArticleKeywords.Element("keywords").Elements()
or
var keywords = from kw in ga.ArticleKeywords.Element("keywords").Elements("keyword")
or (this will get all the keyword elements regardless of level)
var keywords = from kw in ga.ArticleKeywords.Descendants("keyword")
Here is a sample code:
To read keywords we need to call Elements("keyword") not Elements("keywords") since keywords is a root node.
// IEnumerable sequence with keywords data
var keywords = from kw in ga.ArticleKeywords.Elements("keyword")
select new {
Name = (string)kw.Attribute("name"),
Value = (string)kw.Attribute("value"),
Display = (string)kw.Attribute("display")
};
foreach (var keyword in keywords)
{
var kw = "Name: " + keyword.Name +
" Value: " + keyword.Value +
" Display: " + keyword.Display;
Console.WriteLine(kw);
}
You can get attribute value using foo.Attribute("bar").Value, but this method would throw exception if attribute is missing. Safe way to get attribute value is (string)foo.Attribute("bar") - it will give you null if attribute is missing
I would think something like this would work
var keywordData = from k in ga.ArticleKeywords.Elements("Keywords")
select new { Value = k.Attributes["value"].Value,
Display = k.Attributes["display"].Value};
This would give you an IEnumerable of an anonymous type containing a Value and a Display property. Depending on what your doing you could easily replace the anonymous type with a concrete type.

Categories

Resources