C# Add 2 comboBox to csv text file - c#

Am close with this but it still failing. Just adds combobox1 item many times then changes. Combobox2 gets added correctly for each entry of cbo1.
Also adds the delimiter , at front of line in MyFile.txt
I load this with a split no problem, going back is the trouble
I'm like new real new C#.
StreamWriter OutFile = new StreamWriter("MyFile.txt",false);
foreach(object L in comboBox1.Items)
foreach(object M in comboBox2.Items)
{
string lineoftext1 = (L.ToString());
string lineoftext2 = (",");
string lineoftext3 = (M.ToString());
string joinedText;
joinedText = String.Join(lineoftext1, lineoftext2, lineoftext3);
//MessageBox.Show(joinedText);
OutFile.WriteLine(joinedText);
}
OutFile.Close();

OOOOH, i see the problem, it's in the way you are handling your strings, you don't use string.join that way, you can either join them explicitly like this:
joinedText = lineoftext1 + lineoftext2 + lineoftext3;
or you need to create something that the join method accepts, i would use a list, so the inside of your foreach loop would look like this
List<string> mystrings = new List<string>();
mystrings.add(L.ToString());
mystrings.add(M.ToString());
joinedText = String.Join(",", mystrings);
alternativly you could leave it how you have it, but change some values around
joinedText = String.Join(lineoftext2, lineoftext1, lineoftext3);
The first parameter passed to String.Join is the seperator. you were passing it the text.
If this doesn't help, then i would want to see your expected output as i mentioned in my comments above.
Edit: Try this if you want a 1-1 2-2 style
int i = 0;
foreach (object M in comboBox1.Items)
{
List<string> mystrings = new List<string>();
mystrings.Add(comboBox2.Items[i].ToString());
mystrings.Add(M.ToString());
OutFile.WriteLine(String.Join(",", mystrings));
i++;
}
just be aware, this will error if there are different numbers of items in each combobox. (you will get an outside array bounds error)

I am not sure , i think in your combobox1, same items are added when a post back is done, so it repeats back to combobox1 even any changes happens in combobox2. If this is your question, you can overcome this by adding your code inside, if (!IsPostBack), something like this,
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//write you code here
}
}

Nikerym you got it man I just added combobox1 below
129 lines as was the original
Thanks M8
StreamWriter OutFile = new StreamWriter("MyFile.txt", false);
int i = 0;
foreach (object M in comboBox1.Items)
{
List<string> mystrings = new List<string>();
mystrings.Add(comboBox1.Items[i].ToString());
mystrings.Add(comboBox2.Items[i].ToString());
OutFile.WriteLine(String.Join(",", mystrings));
i++;
}
OutFile.Close();

Related

Modify List<string> to convert contents to hyperlinks

I have a List<string> that get's populated with URLs. What I'd like to do is convert the contents of the List to hyperlinks that the user can click on. I've seen a bunch of examples of how to do this, but most of them were to insert in to an email, or switch the word here to a hyperlink. I just don't know what I'm looking at, so it's a little confusing. Here's what I have:
List<string> lstUrls = new List<string>();
//PROGRAM GETS URLS FROM ELEMENTS IN HERE....
foreach (string s in lstUrls)
{
s = ""; //THIS DOESN'T WORK...
}
I don't want to change the content of the string - just to be able to display as a hyperlink. For example, one string value will be https://www.tyco-fire.com/TD_TFP/TFP/TFP172_02_2014.pdf; and how Stack Overflow displays it as a link, that's what I would like to accomplish.
I know I'm obviously botching the syntax. Any help is appreciated.
You canĀ“t change the content of a List<T> while iterating it using foreach. But you can using for:
for(int i = 0; i < lstUrls.Count; i++)
{
var s = lstUrls[i];
lstUrls[i] = "" + s + "";
}
A bit easier to read was this:
lstUrls[i] = String.Format("{0}", s);
You could use linq for it:
lstUrls = lstUrls.Select(s => $"").ToList();
Or rather displaying the url in it:
lstUrls = lstUrls.Select(s => $"{s}").ToList();

C# Converting List to 2d list and adding additional values

Hello need some assistance with this issue. Hopefully i can describe it well.
I have a parser that goes though a document and find sessionID's, strips some tags from them and places them into a list.
while ((line = sr.ReadLine()) != null)
{
Match sID = sessionId.Match(line);
if (sID.Success)
{
String sIDString;
String sid = sID.ToString();
sIDString = Regex.Replace(sid, "<[^>]+>", string.Empty);
sessionIDList.Add(sIDString);
}
}
Then I go thought list and get the distinctSessionID's.
List<String> distinctSessionID = sessionIDList.Distinct().ToList();
Now I need to go thought he document again and add the lines that match the sessionID and add them to the list. This is the part that I am having issue with.
Do I need to create a 2d list so I can add the matching log lines to the corresponding sessionids.
I was looking at this but cannot seem to figure out a way that I could copy over my Distinct list then add the Lines I need into the new array.
From what I can test it looks like this would add the value into the masterlist
List<List<string>> masterLists = new List<List<string>>();
Foreach (string value in distinctSessionID)
{
masterLists[0].Add(value);
}
How do I add Lines I need to the corresponding Masterlist. Say masterList[0].Add value is 1, how do i add the lines to 1?
masterList[0][0].add(myLInes);
Basically i want
Sessionid1
-------> related log line
-------> Related log line
SessionID2
-------> related log line
-------> related log line.
So on and so forth. I have the parsing all working, it's just getting the values into a 2nd string list is the issue.
Thanks,
What you can do is, simple create a class with public properties, and make list of that custom class.
public class Session
{
public int SessionId{get;set;}
public List<string> SessionLog{get;set;}
}
List<Session> objList = new List<Session>();
var session1 = new Session();
session1.SessionId = 1;
session1.SessionLog.Add("description lline1");
objList.Add(session1);
Here is one way to do it:
public class MultiDimDictList: Dictionary<string, List<int>> { }
MultiDimDictList myDictList = new MultiDimDictList ();
Foreach (string value in distinctSessionID)
{
myDictList.Add(value, new List<int>());
for(int j=0; j < lengthofLines; j++)
{
myDictList[value].Add(myLine);
}
}
You would need to replace lengthofLines with a number to indicate how many iterations of lines you have.
See Charles Bretana's answer here

Stringbuilder add new line inside foreach loop

I'm trying to add a new line after looping through the group names inside of a foreach loop. However, it never adds the new line. Everything is printed in single line.
string [] groups = client.GetGroups(username.TrimEnd());
StringBuilder groupNames = new StringBuilder();
foreach (string groupName in groups)
{
groupNames.Append(string.Format(groupName,Environment.NewLine));
}
Label1.Text = groupNames.ToString();
After reading few questions posted here in SO, I have tried many different solutions such as:
{
groupNames.Append(groupName);
groupNames.AppendLine();
}
Label1.Text = groupNames.ToString();
Also tried:
{
groupNames.Append(groupName);
groupNames.Append(System.Environment.NewLine);
}
Label1.Text = groupNames.ToString();
However, if in any of the solution I add:
groupNames.Append("|");
//or
groupNames.Append(",");
it will work. The only thing is not working is the newline.
One thing to note is I'm grabbing the users groupNames from Active Directory and when the groupNames returned it contains \ in the name. I also tried removing the \ before adding new line, didn't work either.
groupNames.Append(groupName);
groupNames.Replace(#"\", " ");
groupNames.Append(System.Environment.NewLine);
Any suggestions?
In html new line is not \r\n but it's <br>, so you need to add <br> after each element, a simple string.Join should work fine:
var result = string.Join("<br>", groups);

how to add values in array

i just want to ask help again. I've created a method to read values in gridview, i was able to get and read values from the gridview. The problem now, is how can i store the values inside an array and i want it to pass on the other page.
here's the code i've created
private void getrowvalues()
{
string combinedvalues;
foreach (GridViewRow row in gvOrderProducts.Rows)
{
string prodname = ((Label)row.FindControl("lblProductName")).Text;
string txtvalues = ((TextBox)row.FindControl("txtQuantity")).Text;
combinedvalues = prodname + "|" + txtvalues;
}
}
i want the result string combinedvalues to be put in an array or collection of strings which i can be access in other page. Is there a way to do it? Any inputs will be greatly appreciated.
thanks!!
Just saw KroaX answer which is the same, I leave mine for the example code.
private void getrowvalues()
{
string combinedvalues;
List<string> combinedValuesList = new List<string>();
foreach (GridViewRow row in gvOrderProducts.Rows)
{
string prodname = ((Label)row.FindControl("lblProductName")).Text;
string txtvalues = ((TextBox)row.FindControl("txtQuantity")).Text;
combinedvalues = prodname + "|" + txtvalues;
combinedValuesList.Add(combinedvalues);
}
// use combinedValuesList or combinedValuesList.ToArray()
}
Notepad code, untested...
To pass something from one page to another, you can store it in the session (sometimes it depends).
Session["combinedvalueList"] = combinedvalueList;
While in another page, you can access it.
if (Session["combinedvalueList"]!=null)
combinedValueList = Session["combinedvalueList"] as List<string>;
//Before Foreach
List<string> combinedvalueList = new List<string>();
//Inside Foreach
combinedvalueList.add(combinedvalues);
Please also see
List MSDN
There you can see samples and Methods of List class. It seems to me you are completely new to c# and programming in general ?

how to dissect string values

How can I dissect or retrieve string values?
Here's the sample code that I'm working on now:
private void SplitStrings()
{
List<string> listvalues = new List<string>();
listvalues = (List<string>)Session["mylist"];
string[] strvalues = listvalues.ToArray();
for (int x = 0; x < strvalues.Length; x++)
{
}
}
Now that I'am able to retrieve list values in my session. How can I separately get the values of each list using foreach or for statement?
What I want to happen is to programmatically split the values of the strings depending on how many is in the list.
If you have a list of string values, you can do the following:
private void SplitStrings()
{
List<string> listValues = (List<string>) Session["mylist"];
// always check session values for null
if(listValues != null)
{
// go through each list item
foreach(string stringElement in listValues)
{
// do something with variable 'stringElement'
System.Console.WriteLine(stringElement);
}
}
}
Note that I test the result of casting the session and that I don't create a new list first-off, which is not necessary. Also note that I don't convert to an array, simply because looping a list is actually easier, or just as easy, as looping an array.
Note that you named your method SplitStrings, but we're not splitting anything. Did you mean to split something like "one;two;three;four" in a four-element list, based on the separator character?
I'm not sure what you're trying to obtain in this code, I don't know why you're converting your List to an Array.
You can loop through your listValues collection with a foreach block:
foreach(string value in listValues)
{
//do something with value, I.e.
Response.Write(value);
}
I don't know what's in the strings but you can start by simplifying. There is no point allocating a new List if you're going to overwrite it immediately.
private void SplitStrings()
{
List<string> list = (List<string>)Session["mylist"];
foreach(string value in list)
{
}
}
List listvalues = (List)Session["mylist"];
foreach (string s in listvalues)
{
//do what you want with s here
}

Categories

Resources