Making empty textbox - c#

When I want to clear the following array:
userInfo[0] = txtPassword.Text;
userInfo[1] = txtVoornaam.Text;
userInfo[2] = txtAchternaam.Text;
userInfo[3] = txtWoonplaats.Text;
userInfo[4] = txtPostcode.Text;
userInfo[5] = txtTelnr.Text;
I'm doing the following:
for (int i = 0; i < 5; i++)
{
userInfo[i] = "";
}
That obviously doesn't work and when I try this:
foreach (string item in userInfo)
{
item = "";
}
Also does not work. How can I do this without saying:
userinfo[0] = txtPassword;

If you want to treat them array-like, you need to add them to an array, or rather and much better a List<TextBox>. Do it once and you can loop over it for any or your needs..
Do it once..:
List<TextBox> boxes = new List<TextBox>()
{ txtPassword, txtVoornaam, txtAchternaam, txtWoonplaats, txtPostcode, txtTelnr};
Now you can pull out the values into a string array
string[] myTexts = boxes.Select(x => x.Text).ToArray();
..or a List :
List<string> myTexts = boxes.Select(x => x.Text).ToList();
or you can clear them all:
foreach (TextBox tb in boxes) tb.Text = "";
If you need to you can access the List elements by variable:
boxes.Find(x => x == textBox2).Text = "12345";
..or by Name:
boxes.Find(x => x.Name == "txtVoornaam").Text = "Jens";
(All checks omitted..)

Related

Formatting List of String

I have an array of strings. I need to sort the list and save each letter's item in a single line. After this, I need to find the longest line of string.
I have done the first part in an inefficient way but I am trying to make it concise.
List<string> fruits = new List<string>
{
"Pomme",
"Apple",
"Apricots",
"Avocado",
"Banana",
"Blackberries",
"Blackcurrant",
"Blueberries",
"Cherries",
"Clementine",
"Cranberries",
"Custard-Apple",
"Durian",
"Elderberries",
"Feijoa",
"Figs",
"Gooseberries",
"Grapefruit",
"Grapes",
"Guava",
"Breadfruit",
"Cantaloupe",
"Carambola",
"Cherimoya",
};
fruits.Sort();
List<string> sortedString = new List<string> { };
foreach (var str in fruits)
{
sortedString.Add(str);
}
//string A, B, C, D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S;
var A = "";
var B = "";
var C = "";
var D = "";
var E = "";
var F = "";
var G = "";
foreach (var item in sortedString)
{
if (item.StartsWith('A'))
{
A += item;
}
else if (item.StartsWith('B'))
{
B += item;
}
else if (item.StartsWith('C'))
{
C += item;
}
else if (item.StartsWith('D'))
{
D += item;
}
else if (item.StartsWith('E'))
{
E += item;
}
else if (item.StartsWith('F'))
{
F += item;
}
}
The result will be like -
AppleApricotsAvocado
BananaBlackberriesBlackcurrantBlueberriesBreadfruit
CantaloupeCarambolaCherimoyaCherriesClementineCranberriesCustard-Apple
Durian
Elderberries
FeijoaFigs
GooseberriesGrapefruitGrapesGuava
After this, I need to find the longest line and put space between each item. Without effective looping, the code will be messy. Can you assist me to show the right way to solve the problem?
The Sort() method already sorts your list and you don't need to assign it to a new one.
My proposal to resolve your problem is
fruits.Sort();
var result = fruits.GroupBy(f => f[0]);
int[] lineslength = new int[result.Count()];
int index = 0;
foreach (var group in result)
{
foreach (var item in group)
{
lineslength[index] += item.Length;
Console.Write(item + " ");
}
Console.WriteLine();
index++;
}
int longestIndex = Array.FindIndex(lineslength, val => val.Equals(lineslength.Max()));
Console.WriteLine(longestIndex);
I used the GroupBy method to group strings by their first letter. Then when I was displaying strings I also counted their length. Using the static FindIndex method of the Array class, I found the index containing the maximum value of the array what corresponds to the line with the maximum length. So index zero is the first line, one is the second line etc.

How do I make List of Lists? And then add to each List values?

class ExtractLinks
{
WebClient contents = new WebClient();
string cont;
List<string> links = new List<string>();
List<string> FilteredLinks = new List<string>();
List<string> Respones = new List<string>();
List<List<string>> Threads = new List<List<string>>();
public void Links(string FileName)
{
HtmlDocument doc = new HtmlDocument();
doc.Load(FileName);
foreach (HtmlNode link in doc.DocumentNode.SelectNodes("//a[#href]"))
{
HtmlAttribute att = link.Attributes["href"];
if (att.Value.StartsWith("http://rotter.net/forum/scoops1"))
{
links.Add(att.Value);
}
}
for (int i = 0; i < links.Count; i++)
{
int f = links[i].IndexOf("#");
string test = links[i].Substring(0, f);
FilteredLinks.Add(test);
}
for (int i = 0; i < FilteredLinks.Count; i++)
{
contents.Encoding = System.Text.Encoding.GetEncoding(1255);
cont = contents.DownloadString(FilteredLinks[i]);
GetResponsers(cont);
}
}
private void GetResponsers(string contents)
{
int f = 0;
int startPos = 0;
while (true)
{
string firstTag = "<FONT CLASS='text16b'>";
string lastTag = "&n";
f = contents.IndexOf(firstTag, startPos);
if (f == -1)
{
break;
}
int g = contents.IndexOf(lastTag, f);
startPos = g + lastTag.Length;
string responser = contents.Substring(f + firstTag.Length, g - f - firstTag.Length);
foreach (List<string> subList in Threads)
{
}
}
}
}
I created this variable :
List<List<string>> Threads = new List<List<string>>();
The first thing I don't know yet how to do is how to create inside Threads number of Lists according to the FilteredLinks.Count inside the Links method.
Second thing is in the GetResponsers method I did:
foreach (List<string> subList in Threads)
{
}
But what I want is that first time it will add all the values from variable responser to the first List in Threads. Then when it's getting to the break; it stop then and then in the Links methods its calling GetResponsers(cont); again this time I want that all the values in responser to be added to the second List in Threads.
I know that each time it's getting to the break; it will get the next FilteredLink from FilteredLinks.
How do I create number of Lists in Threads according to the FilteredLinks.Count?
How do I make the code in GetResponsers to add the responser ?
You don't need to specify the count for the number of lists in Threads, since it is a list, you can simply keep adding lists to it. So the first part is correct where you are declaring it.
The second part --> Your calling method will change. Look below for the calling method.
The third part --> Change private void GetResponsers(string contents) to private void GetResponsers(List threadList, string contents). Look below for implementation change.
Also the loop will look like this then
//other code you have
List<List<string>> Threads = new List<List<string>>();
public void Links(string FileName)
{
// ...other code you have
for (int i = 0; i < FilteredLinks.Count; i++)
{
threads.Add(new List<string>);
contents.Encoding = System.Text.Encoding.GetEncoding(1255);
cont = contents.DownloadString(FilteredLinks[i]);
GetResponsers(threads[threads.Count - 1], cont);
}
}
private void GetResponsers(List<string> threadList, string contents)
{
int f = 0;
int startPos = 0;
while (true)
{
string firstTag = "<FONT CLASS='text16b'>";
string lastTag = "&n";
f = contents.IndexOf(firstTag, startPos);
if (f == -1)
{
break;
}
int g = contents.IndexOf(lastTag, f);
startPos = g + lastTag.Length;
string responser = contents.Substring(f + firstTag.Length, g - f - firstTag.Length);
threadList.Add(responser);
}
}
PS: Please excuse the formatting.
How do i make List of Lists ? And then add to each List values?
The following codesnippet demonstrates you, how to handle List<List<string>>.
List<List<string>> threads = new List<List<string>>();
List<string> list1 = new List<string>();
list1.Add("List1_1");
list1.Add("List1_2")
threads.Add(list1);
List<string> list2 = new List<string>();
list1.Add("List2_1");
list1.Add("List2_2")
list1.Add("List2_3")
threads.Add(list2);
How do i create number of Lists in Threads according to the
FilteredLinks.Count ?
for(int i = 0; i < FilteredLinks.Count; i++)
{
var newList = new List<string>();
newList.Add("item1"); //add whatever you wish, here.
newList.Add("item2");
Threads.Add(newList);
}
I'm afraid I can't help you with Question #2, since I don't understand what you try to achieve there exactly.

How to make listitems highlighted/selected in the listbox from an array?

i have a listbox with 3 listitems (bob, peter, john). How do I make the listitems selected/highlighted depending on what is applicable in the array. Currently I have this:
string names = reader["staffName"].ToString();
string[] selectedName = names.Split(',');
for (int i = 0; i < selectedName.Length; i++)
{
lbName.SelectedIndex = lbName.Items.IndexOf(lbName.Items.FindByValue(selectedName[i]));
}
But it only highlights the last item in the array. e.g. selectedName consist of 2 names (bob and john), but only john is highlighted
First you should check if lbName.SelectionMode is ListSelectionMode.Multiple
then you should the following
string names = reader["staffName"].ToString();
string[] selectedName = names.Split(',');
lbName.SelectedIndex = -1;
foreach (var name in selectedName)
{
lbName.Items.First(item => item.Value == name).Selected = true;
}

How to assign dynamically created objects to a string?

I have a form with this code assigned to a button:
TextBox[] tbxCantServ = new TextBox[1];
int i;
for (i = 0; i < tbxCantServ.Length; i++)
{
tbxCantServ[i] = new TextBox();
}
foreach (TextBox tbxActualCant in tbxCantServ)
{
tbxActualCant.Location = new Point(iHorizontal, iVertical);
tbxActualCant.Visible = true;
tbxActualCant.Width = 44;
tbxActualCant.MaxLength = 4;
this.Controls.Add(tbxActualCant);
iVertical = iVertical + 35;
}
And this code creates textboxes dynamically, one for every "button click", so I can have an "add" button to call it and the user can write a list of things that is not limited.
The question is: How can I assign these "textboxes.Text" to a string? They haven't got a name :S
something like:
string sAllBoxes = tbx1.Text + tbx2.Text + "..." + tbxN.Text;
Thanks!!
If your tbxCantServ is defined as local to a method, then you have to assign a Name to your TextBoxes like:
int counter = 0;
foreach (TextBox tbxActualCant in tbxCantServ)
{
tbxActualCant.Location = new Point(iHorizontal, iVertical);
tbxActualCant.Name = "tbx" + counter++;
tbxActualCant.Visible = true;
tbxActualCant.Width = 44;
tbxActualCant.MaxLength = 4;
this.Controls.Add(tbxActualCant);
iVertical = iVertical + 35;
}
And later in some other method if you want to get the joined text then you can do:
string sAllBoxes = string.Join(",", this.Controls.OfType<TextBox>()
.Where(r => r.Name.StartsWith("tbx"))
.Select(r => r.Text));
But if you have tbxCantServ defined at class level then you can do:
string sAllBoxes = string.Join(",", tbxCantServ
.Where(r=> r != null)
.Select(r => r.Text));
In string.Join, you can replace , with an empty string or any string depending on your requirement.
You can do it in the same way you created them.
Try this:
string sAllBoxes="";
foreach (TextBox tbxActualCant in tbxCantServ)
{
sAllBoxes+=tbxActualCant.Text;
}
OR
Using a StringBuilder:
StringBuilder textBuilder = new StringBuilder();
foreach (TextBox tbxActualCant in tbxCantServ)
{
textBuilder.Append(tbxActualCant.Text);
}
string allText = textBuilder.ToString();
If you have access to your textbox array, you can easily do this:
string sAllBoxes = string.Join(" ", tbxCantServ.Select(x => x.Text));
If you don't then use Control collection of your Form, and give name to your textboxes so you can access them using this.Controls[txtBoxName].
If you just want to concatanate your texts without a separator, you can also use string.Concat method:
string sAllBoxes = string.Concat(tbxCantServ.Select(x => x.Text));

Linq write new list from old list sublist, change said list, write back to old list

I'm rather new to Linq. I'm having trouble coding this.
I have a list with many different sublists.
oldList[0] some type
oldList[1] another different type
oldList[2] the type I want
oldList[3] more types
I want to select all the parameters from a specific type and write them to a temp list.
If that temp list is empty, I want to assign some values (values don't actually matter).
After changing the values, I want to write temp list back into oldList.
Please advise. This is a huge learning experience for me.
public void myFunction(list)
{
//list contains at least 5 sublists of various type
//check if the type I want is null
IEnumerable<TypeIWant> possiblyEmptyList = list.OfType<TypeIWant>(); //find the type I want from the list and save it
if (possiblyEmptyList == null) //this doesn't work and possiblyEmptyList.Count <= 1 doesn't work
{
//convert residence address to forwarding address
IEnumerable<ReplacementType> replacementList = list.OfType<ReplacementType>();
forwardingAddress = replacementList.Select(x => new TypeIWant /* this statement functions exactly the way I want it to */
{
Address1 = x.Address1,
Address2 = x.Address2,
AddressType = x.AddressType,
City = x.City,
CountryId = x.CountryId,
CountyRegion = x.CountyRegion,
Email = x.Email,
ConfirmEmail = x.ConfirmEmail,
Fax = x.Fax,
Telephone = x.Telephone,
State = x.State,
PostalCode = x.PostalCode
});
//write forwarding address back to list
//don't know how to do this
}
LINQ purpose is querying. It doesn't allow you to replace some items in collection with other items. Use simple loop instead:
IEnumerable<TypeIWant> possiblyEmptyList = list.OfType<TypeIWant>();
if (!possiblyEmptyList.Any())
{
for (int i = 0; i < list.Count; i++)
{
ReplacementType item = list[i] as ReplacementType;
if (item == null)
continue;
list[i] = ConvertToTypeIWant(item);
}
}
And conversion (which is better to do with something like automapper):
private TypeIWant ConvertToTypeIWant(ReplacementType x)
{
return new TypeIWant
{
Address1 = x.Address1,
Address2 = x.Address2,
AddressType = x.AddressType,
City = x.City,
CountryId = x.CountryId,
CountyRegion = x.CountyRegion,
Email = x.Email,
ConfirmEmail = x.ConfirmEmail,
Fax = x.Fax,
Telephone = x.Telephone,
State = x.State,
PostalCode = x.PostalCode
};
}
Not LINQ but an example.
class Program
{
static void Main(string[] args)
{
// Vars
var list = new List<List<string>>();
var a = new List<string>();
var b = new List<string>();
var c = new List<string> { "one", "two", "three" };
var d = new List<string>();
// Add Lists
list.Add(a);
list.Add(b);
list.Add(c);
list.Add(d);
// Loop through list
foreach (var x in list)
{
if (x.Count < 1)
{
var tempList = new List<string>();
tempList.Add("some value");
x.Clear();
x.AddRange(tempList);
}
}
// Print
int count = 0;
foreach (var l in list)
{
count++;
Console.Write("(List " + count + ") ");
foreach (var s in l)
{
Console.Write(s + " ");
}
Console.WriteLine("");
}
}
}
(List 1) some value
(List 2) some value
(List 3) one two three
(List 4) some value

Categories