how to add values in array - c#

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 ?

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

How can show my list and make it searchable? C#

Ok, i'm super new to this and this is for a schoolproject.
The project is to code a program where a person can store, update and search information.
In my program i make lists which store cloth information (brand, type, color, size) and i think my information gets stored but i don't know how access it / make a search function for it.
Is my code correct? Should i use another strategy?
This is where my list is defined(?!)
public class klädDATALIST
{
public string märke;
public string typ;
public string färg;
public string storlek;
public klädDATALIST(string _märke, string _typ, string _färg, string _storlek)
{
this.märke = _märke;
this.typ = _typ;
this.färg = _färg;
this.storlek = _storlek;
}
}
This is wehre the string variabels will be filled through a couple of Readline() functions.
For exampel:
string _färg = Console.ReadLine().ToUpper();
Then after i've saved it ill make a new list, i think?:
List<klädDATALIST> newklädDataList = new List<klädDATALIST>();
newklädDataList.Add(new klädDATALIST(_märke, _typ, _färg, _storlek));
I hope you can help me, thank you!
Elements can be accessed by iterating through the collection/List.
foreach( var item in newklädDataList)
{
// access or read item members.
Console.WriteLine(item.märke);
}
When you want to find an element in the List, you can either use Linq
var item = newklädDataList.FirstOrDefault(e=>e.märke == "searchstring"); //Any key to identify list item.
if(item != null)
{
Console.WriteLine(item.märke);
}
Or use Find
var item = newklädDataList.Find(e=>e.märke == "searchstring");
Hope this helps!

C# Add 2 comboBox to csv text file

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

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

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!

Categories

Resources