ViewState values for string array in C# - 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();

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);

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();

Getting number of ITEMS in an array C#

I need to insert a string (from one window(QueryBuilder)) into an array(of another window(Main)).
In the Main i have a method as
public void DisplayCalcQuery(string argFromQueryBuilder)
{
int itemsInUserBuiltQueries = UserBuiltQueries.Count();
UserBuiltQueries[itemsInUserBuiltQueries] = argFromQueryBuilder.ToString();
//displayng the user built query(queries) on the stack panel meant to display it.
foreach (string query in UserBuiltQueries)
{
CheckBox checkQueries = new CheckBox() { Content = query };
stackPanel1.Children.Add(checkQueries);
checkboxes.Add(checkQueries);
}
}
Where UserBuiltQueries is declared as
string[] UserBuiltQueries;
However when from the other window i do
backscreen.DisplayCalcQuery(ttextBox1.Text.ToString()); //where backscreen is the Main
The argument is passed well but i get an error as
{"Value cannot be null.\r\nParameter name: source"}
What did I do wrong ?
These lines are wrong
int itemsInUserBuiltQueries = UserBuiltQueries.Count();
UserBuiltQueries[itemsInUserBuiltQueries] = argFromQueryBuilder.ToString();
Arrays start at index zero and end at index (Count - 1), so, if UserBuiltQueries.Count() returns 10 you could use indexes from 0 to 9. Essentially, using index 10, you are adding a new string outside the end of the array.
However, if your requirements force you to expand the array, it is better and more easy to code if you use a List<string> instead. Adding new elements will be a lot more easier and you could still use the List as an Array for common tasks.
List<string> UserBuiltQueries = new List<string>();
.....
public void DisplayCalcQuery(string argFromQueryBuilder)
{
UserBuiltQueries.Add(argFromQueryBuilder);
//displayng the user built query(queries) on the stack panel meant to display it.
foreach (string query in UserBuiltQueries)
{
CheckBox checkQueries = new CheckBox() { Content = query };
stackPanel1.Children.Add(checkQueries);
checkboxes.Add(checkQueries);
}
}
By the way, you should stop to unnecessarily convert a string to a string. You pass a ttextBox1.Text.ToString() but ttextBox1.Text is already a string. Inside the method the parameter argFromQueryBuilder is already a string and there is no need to convert to a string
Instead of using string[] for UserBuildQueries, use List. When you need it as an array, you can simply say: UserBuildQueries.ToArry()
Rewrite the function to
public void DisplayCalcQuery(string argFromQueryBuilder)
{
UserBuiltQueries.Add(argFromQueryBuilder.ToString());
//displayng the user built query(queries) on the stack panel meant to display it.
foreach (string query in UserBuiltQueries)
{
CheckBox checkQueries = new CheckBox() { Content = query };
stackPanel1.Children.Add(checkQueries);
checkboxes.Add(checkQueries);
}
}
In c# but I think in all programming language indexis start from 0:
so if an array has length or count =1 the index is 0 array[0], array.lenght==1
int itemsInUserBuiltQueries = UserBuiltQueries.Count()-1;
UserBuiltQueries[itemsInUserBuiltQueries] = argFromQueryBuilder.ToString();
And double check that your array is initialized before using it!

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