Saving selected listbox(binded) items to an array in c# - c#

string[] chkItems = new string[4];
string[] str = new string[4];
str[0] = txtID.Text;
str[1] = txtName.Text;
str[2] = txtEmail.Text;
itemCount = ltbxInterests.SelectedItems.Count;
for (int i = 0; i <= itemCount; i++)
{
ltbxInterests.SelectedItems.CopyTo(chkItems, 0);
// here it is returning an exception
//"Object cannot be stored in an array of this type."
}
Please help me how to get out from this exception

Couple issues here, chkItems is defined as length 4 so you will get an exception if you try and put more than 4 items in. The source array SelectedItems is of type object so you would need to cast the result.
Assuming you are only putting strings into the listbox you could use (remember to reference System.Linq)
string[] str = new string[4];
str[0] = txtID.Text;
str[1] = txtName.Text;
str[2] = txtEmail.Text;
string[] chkItems = ltbxInterests.SelectedItems.OfType<string>().ToArray();
If you are wanting to limit to the first 4 items, you could replace the last line to
string[] chkItems = ltbxInterests.SelectedItems.OfType<string>().Take(4).ToArray();
Also you could shorten the code to use an array initializer (but this wil make str length 3 because you only have 3 items):
string[] str = new [] {
txtID.Text,
txtName.Text,
txtEmail.Text,
}

SelectedItems is a collection of Object, then, in order to use CopyTo methods, chkItems must be an array of type object (i.e. object[]).
Otherwise, you can use LINQ to convert, for example, to a list of strings:
var selectedList = ltbxInterests.SelectedItems.OfType<object>()
.Select(x => x.ToString()).ToList();

You chould check the Type of > chkItems .

Related

3 Arrays into 1 Array with all Combinations (code inside)

I have the following code:
static void Main(string[] args)
{
string[] h = new string[2];
h[0] = "h0";
h[1] = "h1";
string[] d = new string[2];
d[0] = "d0";
d[1] = "d1";
string[] a = new string[2];
a[0] = "a0";
a[1] = "a1";
}
What would be the code to generate an array containing each of the following items:
h0h1,h0d1,h0a1,d0h1,d0d1,d0a1,a0h1,a0d1,a0a1
I have been trying with nested for loops, but can't get the list of combinations above.
Dim list as New List<string[]>
Dim result = new string[N] /* N in this case will be 9 (3^2) */
list.Add(h)
list.Add(d)
list.Add(a)
for(int i =0; i< N; i++)
{
result[i] = list[Math.Truncate(i/3)][0] + list[i%3][1]
}
I think it's clear enough, I will extend if needed, for now:
list[Math.Truncate(i/3)][0]: we get the array in the list
(1st one for i:0..2, 2nd one for i:3..5 and 3nd one for i:6..8)
and we get its first item ([0]) value
list[i%3][1]: we get the array in the list (1st one for i:0,3,6; 2nd one for i:1,4,7; and 3nd one for i:2,5,8) and we get its second ([1]) item's value
Then just concatenate both ítems and store them in their index

How to make string list to "string array"

This is what I want to convernt: {"apple", "banana"} to "["apple", "banana"]"
I have tried convert string list to string array first, then convert string array to string, but did not work.
var testing = new List<string> {"apple", "banana"};
var arrayTesting = testing.ToArray();
var result = arrayTesting.ToString();
You can use string.Join(String, String[]) method like below to get a , separated string values (like csv format)
var stringifiedResult = string.Join(",", result);
You can try this, should work;
var testing = new List<string> { "apple", "banana" };
var arrayTesting = testing.ToArray<string>();
var result = string.Join(",", arrayTesting);
You can also use StringBuilder
StringBuilder sb = new StringBuilder();
sb.Append("\"[");
for (int i = 0; i < arrayTesting.Length; i++)
{
string item = arrayTesting[i];
sb.Append("\"");
sb.Append(item);
if (i == arrayTesting.Length - 1)
{
sb.Append("\"]");
}
else
sb.Append("\",");
}
Console.WriteLine(sb);
Instead of converting it to an array, you could use a linq operator on the list to write all the values into a string.
string temp = "";
testing.ForEach(x => temp += x + ", ");
This will leave you with a single string with each value in the list separated by a comma.

Isolate characters from string

So I have a string called today with the value "nick_george_james"
it looks like this
string today = "_nick__george__james_";
how can i isolate the text between the '_' into a new string? i want to get the 3 names into seperate strings so that in the end i have name1, name2, name3 with the values nick, george and james
my application is written in c#
use string.Split
string[] array = today.Split('_');
After editing your question, I realized that you have multiple _ in your string. You should try the following.
string[] array = today.Split("_".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
Or
string[] array = today.Split(new []{"_"}, StringSplitOptions.RemoveEmptyEntries);
Later your array will contain:
array[0] = "nick";
array[1] = "george";
array[2] = "james";
string[] array = today.Split('_');
name1=array[0];
name2=array[1];
name3=array[2];
Thought of coming up with an idea other than string.Split.
string today = "_nick__george__james_";
//Change value nNoofwordstobeFound accordingly
int nNoofwordstobeFound = 3;
int nstartindex = 0;
int nEndindex = 0;
int i=1;
while (i <= nNoofwordstobeFound)
{
Skip:
nstartindex = today.IndexOf("_",nEndindex);
nEndindex = today.IndexOf("_", nstartindex + 1);
string sName = today.Substring(nstartindex + 1, nEndindex - (nstartindex + 1));
if (sName == "")
{
goto Skip;
}
else
{
//Do your code
//For example
string abc= sName;
}
i++;
}
I'd still prefer string.split method over this anytime.
string[] nameArray = today.Split('_');
Here you will get a array of names. You can get each name from by specifying index positions of the nameArray.
ie Now the the nameArray contains values as below
nameArray[0] = "nick", nameArray[1] = "george", nameArray[2] = "james"

System.IndexOutOfRangeException for a dynamic initialized array

var objTypeIndex = from u in context.sistema_DocType_Index where u.docTypeId == id select u.indexId;
indexIds = objTypeIndex.ToList();
int count = indexIds.Count();
string[] names = new string[] {};
int i = 0;
foreach (int indexId in indexIds)
{
//resgata nome do indice e armazena em um array
string strIndiceID = indexId.ToString();
int indiceID = Convert.ToInt32(strIndiceID);
var objIndexName = from u in context.sistema_Indexes where u.id == indiceID select u.idName;
name =
names[i] = objIndexName.First();
i++;
}
This line above the last:
names[i] = objIndexName.First();
gives the following error:
System.IndexOutOfRangeException: Index was outside the bounds of the array.
I know what that means.. I just can´t figure out why.
Look here:
string[] names = new string[] {};
You've created an empty array. You can't put any element into that array. There is no value of i for which this statement will work:
names[i] = objIndexName.First();
It's not clear what you're trying to do, but perhaps you want a List<string> to build up (with Add) rather than an array? Or you could probably do the whole thing with a single LINQ query...
Replace
string[] names = new string[] {};
By
var names = new List<string>();
And instead of
names[i] = objIndexName.First();
Use
names.Add(objIndexName.First());
Then, you will be able to get your array as follow:
var nameArray = names.ToArray();

how to assign empty to string array in c#

How can I assign empty to string array in c#?
string [] stack; //string array
how to assign
stack = ""; //this statement gives error cannot implicitly convert to type string to string []
You cannot use:
string[] stack = "";
Since stack in here is an array of string. If you want to initialize empty string for each elements in array, you can use LINQ with Enumerable.Range to get the result, assume there are 10 items in here:
string[] stack = Enumerable.Range(0, 10)
.Select(i => string.Empty)
.ToArray();
This will create an array with three empty strings.
string[] arr1 = new string[] { "", "", "" };
or if you only need one:
string[] arr1 = new string[] { "" };
or another example (with 3 strings):
string[] arr1 = new string[3];
arr1[0] = "";
arr1[1] = "";
arr1[2] = "";
Just iterate over the array like this:
int length = stack.Length;
for(int i = 0; i < length; i++)
{
stack[i] = string.Empty;
}
If you just want to create empty array of string[] object.
string [] stack = new string[]{};

Categories