Setting selected values on MultiSelectList C# - c#

I'm working with a simple MultiSelectList on C#.
I just want to populate this MultiSelectList with some string values (not a pair such as <"Key", "Value"> just <"Value">) and set some selected items.
Here's my code:
IEnumerable<string> ubicaciones = new string[] { "NEGOCIOS", "TERRITORIOS",
"LOCALIDADES" };
IEnumerable<string> ubicacionesSelected = Ubicaciones.Split(',');
UbicacionesPermitidas = new MultiSelectList(ubicaciones, ubicacionesSelected);
IEnumerable<string> transacciones = new string[] { "CARGA: ACCESORIOS",
"CARGA: EQUIPOS", "ASIGNACIONES", "DESINCORPORACIONES",
"PRÉSTAMOS", "TRASLADOS", "SALIDAS" };
IEnumerable<string> transaccionesSelected = Transacciones.Split(',');
TransaccionesPermitidas = new MultiSelectList(transacciones,
transaccionesSelected);
However, is not working... (it shows all the values on the MultiSelectList but it doesn't show any item selected) what am I missing?
Thanks.

The values in Ubicaciones do not match up with the values in ubicaciones. It's the same with Transacciones and transacciones. If you don't believe that that's the case, please post the code which defines Ubicaciones and Transacciones and we can troubleshoot it further.

Related

C# Comparing if two lists have the same order of items (alphabetical)

I'm facing a huge problem with comparing two lists. I just made copy of my first list and I tried to sort it. The problem is, I want to compare my original list and sorted one to see if they have same alphabetical order. I hope I provided enough information for my problem.
Thanks in advance
public void VerifyDataPrijave(string username)
{
List<string> listaTekstova = new List<string>(); //initializing new, empty List
var kartice = Repo.Kartice.CreateAdapter<Unknown>(false).Find(".//div[class='_63fz removableItem _95l5']");
foreach (var kartica in kartice) {
var slika = kartica.Find(".//tag[tagname='img']")[0];
var ime = slika.Find("following-sibling::div")[0];
string text = ime.GetAttributeValue("InnerText").ToString(); //loop through profile cards and getting Names as InnerText in variable text
listaTekstova.Add(text); //adding those "texts" I just found to an empty list initialized before
List<string> novaListaTekstova = new List<string>(listaTekstova); //clone (copy) of the very first one list
novaListaTekstova.Sort(); //sorting that list alphabetically (I suppose, not sure)
}
}
You can use SequenceEqual to compare to IEnumerables. In your case you can do something like this once all sorting has been done:
var isEqual = novaListaTekstova.SequenceEqual(listaTekstova);

List of strings stored as values in dictionary C#

I have a testing framework that needs to be updated to include testing in Spanish. I have a CSV file that contains the field label, english text, and Spanish text. I've decided to use a dictionary to store the field label as the key and the values would be a list of strings for Spanish and English text.
private List<string> ReadTranslationCsv()
{
var pathToCSV = #"C:\Location";
Dictionary<string, List<string>> translations = new Dictionary<string, List<string>>();
string label, englishText, spanishText;
using (TextReader fileReader = File.OpenText(pathToCSV))
{
var csv = new CsvReader(fileReader);
csv.Configuration.HasHeaderRecord = false;
while (csv.Read())
{
for (int i = 0; csv.TryGetField<string>(i, out label);)
{
List<string> Spanglish = new List<string>();
csv.TryGetField<string>(i + 1, out englishText);
Spanglish.Add(englishText);
csv.TryGetField<string>(i + 2, out spanishText);
Spanglish.Add(spanishText);
if (label != "")
{
translations.Add(label, Spanglish);
}
i = i + 3;
}
}
}
}
I want to be able to search within the list of values to see if anything matches some string of text. I'm not sure how to search the lists that are within the dictionary, none of the default methods or properties are working.
I'm using the below code but this will return me a bool, which is not what I need, I need the list value that matches the elementWithText
public void GivenElementMatches(string elementWithText)
{
if (Config.Language == "Spanish")
{
var list = new List<string> { elementWithText };//must create list in order to pass text to any translations methods
Hooks.translations.ContainsValue(list); // Even though the labels are the key, I need to search for the english text which is index 1 of the list and all values should be returned
}
//TODO
}
My suggestion would be to use a Dictionary with a class you create, inside that class you can have a compare function.
The advantage of this method is you may add more language equivalents later and only have to change your model.
Please note, this code is not complete and you will have to bug check and alter it to suit.
Dictionary <string, LangEquivalents> model;
public KeyValuePair<string, LangEquivalents> findField(string input)
{
return model.First(x=>x.Value.Comparison(input));
}
You could also make it a comparable object type and just use model.First(x=>x.Value == input));

How to add Ms-Access database column in any String [] in C#

I am a newbie to C#.
I want to add my one of database's column in string[] but fail to do so. I have created string[] with name "Items" and also create a control with name autocompletemenu1. Now when I type autocompetemenu1.Items = Database Column then the contents of database column should be filled in ITEM string[]. I have tried but it is not working so I just mention some name in it and it is working but it is not taking database column. Don't know why! Please help
Thank you in advance.
This is the method ITEM I am using to take collections. Way to write is
autocompleteMenu1.Items = Database column
My code:
[DefaultValue(null)]
public string[] Items
{
get
{
if (sourceItems == null)
return null;
var list = new List<string>();
foreach (AutocompleteItem item in sourceItems)
list.Add(item.ToString());
return list.ToArray();
}
set { SetAutocompleteItems(value);
}
Here is the assignment of String [] to Item method but I want to add database column instead of string [] ... how can I do this...?
this.autocompleteMenu1.Items = new string []
{
"Jamal",
"Javed",
"Jameel",
"James",
"Jamshed",
"abc",
"abcd",
"Ahmed",
};

BindingList<String> populating data view with string lengths not the string itself

Morning!
I have a list<string> which gets converted to a BindingList<string> as shown below. This then gets bound to a datagridview so that I can populate it with the appropriate values from this list.
However, instead of displaying the strings themselves it is instead being populated with the lengths of the strings. I have never worked with datagrids before so any help would be appreciated!
Thanks in advance, I have attached the relevant section of code below:
DataGridViewCell cell = new DataGridViewTextBoxCell();
DataGridViewTextBoxColumn colExisting = new DataGridViewTextBoxColumn()
{
CellTemplate = cell,
Name = "Template",
HeaderText = "Existing Template",
};
findReplaceGrid.Columns.Add(colExisting);
var bTemplatesInFiles = new System.ComponentModel.BindingList<string>(templatesInSelection);
findReplaceGrid.DataSource = bTemplatesInFiles;
Edit:
templatesInSelection is defined as such:
public static System.Collections.Generic.List<string> templatesInSelection;
and instantiated as such:
templatesInSelection = new System.Collections.Generic.List<string>();
Old question, I know. But maybe somebody will come across this question like I did today trying to solve this problem.
What I did was to use a BindingSource instead of a BindingList and setting the BindingSources DataSource to ListOfStrings.ConvertAll(x => new { Value = x }).
I found this solution on this post.
A BindingList is designed for Complex-Object-Binding.
If you try to bind there strings only, it will enumerate the chars building the string and only display the Count-Property.
A possible solution is this (ugly but working):
WrapperClass
public class StringValue {
public StringValue(string s) {
this._value = s;
}
public string Text {
get {
return this._value;
}
set {
this._value = value;
}
}
private string _value;
}
Usage
var l = new List<StringValue>();
l.Add(new StringValue("Hello"));
l.Add(new StringValue("beautiful"));
l.Add(new StringValue("World"));
var bTemplatesInFiles = new BindingList<StringValue>(l);
this.dataGridView1.DataSource = bTemplatesInFiles;
Hope this helps!
EDIT
A simpler approach (as you wished)
First, add a column somehow (Designer or Code)
Then do:
var l = new List<string>();
l.Add("Hello");
l.Add("beautiful");
l.Add("World");
foreach (var s in l)
{
this.dataGridView1.Rows.Add(s);
}

ViewState values for string array in C#

I need to store the values into an array which I already implemented. Sadly, only the latest value is stored on looping. I want all the values to be stored, I tried to use ViewState, but this code below is not working or getting me what I wanted. Please help me.
foreach loop
{
successBenefitCodes = new [] {ben.BenefitCode.ToString()};
ViewState["successBenefitCodes"] = successBenefitCodes;
successBenefitCodes = ViewState["successBenefitCodes"] as string[];
}
You want something like this.
List<string> successBenefitCodes = new List<string>();
foreach(var ben in youritems)
{
successBenefitCodes.Add(ben.BenefitCode.ToString());
}
ViewState["successBenefitCodes"] = successBenefitCodes.ToArray();

Categories

Resources