I am trying to sort an ObservabkeCollection object containing the following class
public Favourites(string title=null, string uri=null, string folder=null, bool delete=false)
{
this.pageTitle = title;
this.pageURI = uri;
this.folder = folder;
this.deleteEnabled = delete;
}
I am trying to sort by folder then by uri. While the uri and title can be null, in my case I always assign them with something not null. However the folder property can be null.
My code to sort
private void sortCollectionFolderFirst()
{
IEnumerable<Favourites> sort;
ObservableCollection<Favourites> tempSortedFavourites = new ObservableCollection<Favourites>();
tempFavs.Clear();
tempFavs = settings.FavouritesSetting;
sort = tempFavs.OrderByDescending(item => item.Folder).ThenBy(item => item.PageURI);
foreach (var item in sort)
{
tempSortedFavourites.Add(item);
}
settings.FavouritesSetting = tempSortedFavourites;
}
The sorting is fine when the class item is
this.pageTitle = sometitle;
this.pageURI = someuri;
this.folder = null;
this.deleteEnabled = false or true;
But sort returns empty when it encounters an item with the following content
this.pageTitle = sometitle;
this.pageURI = someuri;
this.folder = somefoldername;
this.deleteEnabled = false or true;
Why is that?
Related
i want to add dynamically selected items in ExpandoObject then print it in the form of json value. if i selected 2values, it is printing only the last value 2times.My problem is whatever im selecting it prints last value only.
My code:
Declaration
dynamic output = new List<dynamic>();
dynamic foo = new ExpandoObject();
List<int> selected = new List<int>();
switch toggle function:
private void Switch_Toggled(object sender, ToggledEventArgs e)
{
var switch1 = (Switch)sender;
var human = (Human)switch1.BindingContext;
var id = human.retail_modified_item_id;
var name = human.name;
var old_price = human.old_price;
var new_price = human.new_price;
if (switch1.IsToggled)
{
if (!selected.Contains(id))
{
selected.Add(id);
foo.id = id;
foo.name = name;
foo.old_price=old_price;
foo.new_price=new_price;
output.Add(foo);
}
}
else
{
if (selected.Contains(id)) selected.Remove(id);
}
}
Printing Json value ;
string json = Newtonsoft.Json.JsonConvert.SerializeObject(output);
Debug.WriteLine(json);
My output is:
[{"id":1000739,"name":"Hashbrowns","old_price":0.99,"new_price":8.5},{"id":1000739,"name":"Hashbrowns","old_price":0.99,"new_price":8.5}]
if i selected 2values, it is printing only the last value 2times.
dynamic foo = new ExpandoObject();
you declare global variables here,so the second time you call the following code, you are reassuming the first foo and adding it again, so there are two identical items in the output List.
foo.id = id;
foo.name = name;
foo.old_price=old_price;
foo.new_price=new_price;
output.Add(foo);
you could change like this :
if (!selected.Contains(id))
{
selected.Add(id);
dynamic foo = new ExpandoObject(); // local variables
foo.id = id;
foo.name = name;
foo.old_price=old_price;
foo.new_price=new_price;
output.Add(foo);
}
I've followed the advice given here : How to bind Enum to combobox with empty field in C# but it gave me some unusable content:
which is not what I would like to see... Here's the code I used to bind:
comboBox2.DataSource = GetDataSource(typeof (MessageLevel), true);
And here's the background:
public enum MessageLevel
{
[Description("Information")]
Information,
[Description("Warning")]
Warning,
[Description("Error")]
Error
}
----
public static string GetEnumDescription(string value)
{
Type type = typeof(MessageLevel);
var name = Enum.GetNames(type).Where(f => f.Equals(value, StringComparison.CurrentCultureIgnoreCase)).Select(d => d).FirstOrDefault();
if (name == null)
{
return string.Empty;
}
var field = type.GetField(name);
var customAttribute = field.GetCustomAttributes(typeof(DescriptionAttribute), false);
return customAttribute.Length > 0 ? ((DescriptionAttribute)customAttribute[0]).Description : name;
}
public static List<object> GetDataSource(Type type, bool fillEmptyField = false)
{
if (type.IsEnum)
{
var data = Enum.GetValues(type).Cast<Enum>()
.Select(E => new { Key = (object)Convert.ToInt16(E), Value = GetEnumDescription(E.ToString()) })
.ToList<object>();
var emptyObject = new { Key = default(object), Value = "" };
if (fillEmptyField)
{
data.Insert(0, emptyObject); // insert the empty field into the combobox
}
return data;
}
return null;
}
How can I make a correct binding and adding one empty entry?
So the solution is to also set DisplayMember and ValueMember properties on ComboBox, so that it will know how to treat Key and Value properties.
comboBox2.DataSource = GetDataSource(typeof (MessageLevel), true);
comboBox2.DisplayMember = "Value";
comboBox2.ValueMember = "Key";
When I try to get the id from:
string idValue = item[Lookup].ToString();
I get the next value by example:
1;#1
I need the value this way:
1
Actually this code handle the requirement:
using (SPSite site = new SPSite(context.CurrentWebUrl))
{
using (SPWeb web = site.OpenWeb())
{
//Context list
SPList list = web.Lists[context.ListId];
SPList child = web.Lists[List];
SPListItem currentItem = list.GetItemById(context.ItemId);
string updateItems = "";
int ID = currentItem.ID;
foreach (SPListItem item in child.Items)
{
string idValue = item[Lookup].ToString();
int partial = idValue.LastIndexOf(";");
string idPure = idValue.Substring(0, partial);
if (idPure == ID.ToString())
{
item[Field] = Value;
item.Update();
updateItems += item.ID.ToString();
}
}
//Return Items*/
results["Items"] = updateItems;
SPWorkflow.CreateHistoryEvent(web, context.WorkflowInstanceId, 0,
web.CurrentUser, TimeSpan.Zero, "Information",
"Event from sandboxed, updates: " + updateItems, string.Empty);
}
}
I want to know a better function or property to get the ID from lookup field.
SPFieldLookupValue fieldLookupValue = new SPFieldLookupValue(item["FieldName"].ToString());
int lookupID = fieldLookupValue.LookupId;
Here you go :)
SPList mySPList = oWeb.Lists["ProjectList"];
newItem["LookupFieldName"] = new SPFieldLookupValue(getLookUp(mySPList,LookupFieldValue), LookupFieldValue);
public static int getLookUp(SPList oList, string FieldValue, string sFieldName="Title")
{
foreach (SPListItem spi in oList.GetItems())
{
if (spi[sFieldName].ToString() == FieldValue)
{
return spi.ID;
}
}
return 0;
}
i can set lookup field in SharePoint by use this code
<script>
window.onload = (event) => {
document.getElementById("tafahomNameId_78ec7c44-beab-40de-9326-095f474519f4_$LookupField").value = 1;
};
</script>
So I've been looking to set a default value for my combobox. I found a few things but none of them seem to work.
Actually, it works if I create a simple combobox and use comboBox1.SelectedIndex = comboBox1.Items.IndexOf("something") but once I dynamically generate the contents of the comboboxes, I can't get it to work anymore.
This is how I fill my combo box (located in the class's constructor);
string command = "SELECT category_id, name FROM CATEGORY ORDER BY name";
List<string[]> list = database.Select(command, false);
cbxCategory.Items.Clear();
foreach (string[] result in list)
{
cbxCategory.Items.Add(new ComboBoxItem(result[1], result[0]));
}
I can't seem to get it to work to set a default value, like if I place cbxCategory.SelectedIndex = cbxCategory.Items.IndexOf("New") below the above code, it won't work.
WinForms, by the way.
Thank you in advance.
cbxCategory.SelectedIndex should be set to an integer from 0 to Items.Count-1 like
cbxCategory.SelectedIndex = 2;
your
cbxCategory.SelectedIndex = cbxCategory.Items.IndexOf("New")
should return -1 as long as no ComboboxItem mutches the string ("New");
another solution though i don't like it much would be
foreach(object obj in cbxCategory.Items){
String[2] objArray = (String[])obj ;
if(objArray[1] == "New"){
cbxCategory.SelectedItem = obj;
break;
}
}
perhaps this also requires the following transformation to your code
foreach (string[] result in list)
{
cbxCategory.Items.Add(result);
}
I haven't tested the code and i am not sure about the casting to String[2] but something similar should work
It looks like you're searching the cbxCategory.Items collection for a string, but it contains items of type ComboBoxItem. Therefore the search will return -1.
You can use LINQ.
//string command = "SELECT category_id, name FROM CATEGORY ORDER BY name";
//List<string[]> list = database.Select(command, false);
// sample data...
List<string[]> list = new List<string[]> { new string[] { "aaa", "bbb" }, new string[] { "ccc", "ddd" } };
cbxCategory.Items.Clear();
foreach (string[] result in list)
{
cbxCategory.Items.Add(new ComboBoxItem(result[1], result[0]));
}
ComboBoxItem tmp = cbxCategory.Items.OfType<ComboBoxItem>().Where(x => x.ResultFirst == "bbb").FirstOrDefault();
if (tmp != null)
cbxCategory.SelectedIndex = cbxCategory.Items.IndexOf(tmp);
ComboBoxItem class:
class ComboBoxItem
{
public string ResultFirst { get; set; }
public string ResultSecond { get; set; }
public ComboBoxItem(string first, string second)
{
ResultFirst = first;
ResultSecond = second;
}
}
Here's my simple solution
var list = comboBox1.Items.Cast<string>().ToList();
cbxCategory.SelectedIndex = list.FindIndex(c => c.StartsWith("test"));
My solution:
int? defaultID = null;
foreach (DataRow dr in dataSource.Tables["DataTableName"].Rows)
{
if ((dr["Name"] != DBNull.Value) && ((string)dr["Name"] == "Default Name"))
{
defaultID = (int)dr["ID"];
}
}
if (defaultID != null) comboBox.SelectedValue = defaultID;
I'm trying to write to a model for the first time to use in my view: the first time I write to the model I get an ArgumentOutOfRangeException.
Getting error on first write to array:
private IAdditionalQuestionsService _service;
private SelectedAdditionalQuestionAnswerModel _model;
private void InitializeController()
{
_service = GetObject<IAdditionalQuestionsService>();
//GetPageHeaderText(inst);
ViewBag.GetPageTitle = "Additional Questions";
}
[HttpGet]
public virtual ActionResult Edit()
{
Institution inst = _service.GetInstitution(State.GetInstitutionRecordId());
_model = GetObject<SelectedAdditionalQuestionAnswerModel>();
_model.AddQuestAnswModel = new List<AdditionalQuestionAnswerModel>();
GetPageConfiguration1(inst);
return View(_model);
}
AdditionalQuestionAnswerModel m = GetObject<AdditionalQuestionAnswerModel>();
int c = 0;
foreach (var x in inst.AdditionalQuestions)
{
foreach (var y in x.AdditionalQuestionAnswers)
{
// Error is happening on next line *************
_model.AddQuestAnswModel[c].QuestionText = x.QuestionText;
_model.AddQuestAnswModel[c].InstitutionId = x.InstitutionId;
_model.AddQuestAnswModel[c].AdditionalQuestionId = x.Id;
_model.AddQuestAnswModel[c].AnswerText = y.AnswerText;
_model.AddQuestAnswModel[c].IsSelected = false;
c++;
}
}
You can't use _model.AddQuestAnswModel[c] because you never added any items to your list.
Instead of that, create a new object and set its values and then add the item to your list.
Something like this:
AdditionalQuestionAnswerModel newItem = new AdditionalQuestionAnswerModel();
//set the values here to newItem
_model.AddQuestAnswModel.Add(newItem);
You're firstly instantiating your list
_model.AddQuestAnswModel = new List<AdditionalQuestionAnswerModel>();
then you try to access to the first element
_model.AddQuestAnswModel[c] // c == 0
without adding any element to the list.
Add an element before trying to access to a list by index, or more simple:
foreach (var y in x.AdditionalQuestionAnswers)
{
AdditionalQuestionAnswerModel newObj = new AdditionalQuestionAnswerModel
{
QuestionText = x.QuestionText;
InstitutionId = x.InstitutionId;
AdditionalQuestionId = x.Id;
AnswerText = y.AnswerText;
IsSelected = false;
};
_model.AddQuestAnswModel.Add(newObj);
}
Ir means that there no item in your _model.AddQuestAnswModel at the indicated postition, and from your code, I see that _model.AddQuestAnswModel has only be initiated with new List<AdditionalQuestionAnswerModel>(), so it does not contain items (unless you're doing it in the contructor).
You need to fill it like so :
_model.AddQuestAnswModel.Add(item);