How to display form variables based on variable name - c#

I have a list of variable names, lets say:
List<string> list = new List<string>();
list.Add("size");
list.Add("width");
list.Add("name");
list.Add("zip");
and i have text controls with those exact names, is there a way to loop through the list and only display what the value of the text control that i am asking for, like lets say something like this:
foreach (string txtctl in list)
{
Response.Write(Request.Form[txtctl]);
}
When i run this code the value just displays blank. Any suggestions?

string str = "";
foreach (string item in list)
{
TextBox txt = (TextBox)Form.FindControl(item);
if (txt != null)
{
str += item+":"+ txt.Text+"<br>";
}
}
Response.Write(str);

Related

How to access a group of Text Boxes based on the Index Id in their Name

I have 16 text boxes in my Form whose names are suffixed sequentially from 1 to 16 respectively.
i.e. The 16 test boxes are names TextBox1, 'TextBox2, .... all the way until the 16th one, which is namedTextBox16`.
I would like to read the contents of these 16 text boxes in a loop and modify the ith TextBox's contents or properties based on a certain condition.
How do I do this?
If you use WinForms, easiest way is to store text boxes references in array, in constructor of window:
TextBox[] data = new TextBox[16]{textBox1,textBox2, [...],textBox16};
then you can use for loop to access them.
You can try something like this:
Dictionary<string, string> yourValues = new Dictionary<string, string>();
foreach (Control x in this.Controls)
{
if (x is TextBox)
{
yourValues.Add(((TextBox)x).Name, ((TextBox)x).Text);
}
}
NOTE: On your future question please provide more information and make your question more clear.
i would try to find and modify using Linq:
using System.Linq;
//...
int x = 5; //number of textbox to search
var textbox = this.Controls.OfType<TextBox>().Single(tb => tb.Name.EndsWith(x.ToString()));
textbox.Text = "abc";
In case you have to loop thru all the texboxes in form, you can do something like this:
List<TextBox> textboxes = this.Controls.OfType<TextBox>().ToList();
foreach (TextBox box in textboxes)
{
box.Text = "something";
}
Easiest way according to what you specified is to use Linq.
Let's assume you have 3 TextBoxes :
// 1st -> which is named meTextBox1
// 2nd -> which is named meTextBox2
// 3rd -> which is named meTextBox3
As you can see from above every line differs only by the number ( index .. call it whatever you want ).
Now you can make your base "query" which would look like :
const string TB_NAME = "meTextBox{0}";
And as you can presume right now this will be used inside of string.Format method. Now to retrieve desired TextBox all you have to do is to make Linq statement :
string boxName = string.Format(TB_NAME, 7); // retrieve 7th text box
TextBox tBox = Controls.OfType<TextBox>().FirstOrDefault(tb => tb.Name == boxName);
This example does not consider nested Controls but you can make do this recursively which will retrieve nested Controls:
TextBox ByIndex(int idx, Control parent)
{
TextBox result = null;
string searchFor = string.Format(TB_NAME, idx);
foreach(Control ctrl in parent.Controls)
{
if(!(ctrl is TextBox) && ctrl.HasChildren)
{
result = ByIndex(idx, ctrl);
if( result != null)
break;
}
else if(ctrl is TextBox)
{
if(ctrl.Name = searchFor)
{
result = ctrl as TextBox;
break;
}
}
}
return result;
}
To use above method you can just call it like such :
public class MeForm : Form
{
//.. your code here ..
void meImaginaryMethodToRetrieveTextBox()
{
int meRandomIndex = 7;
TextBox tb = ByIndex(meRandomIndex, this);
// rest of the code...
}
}

Directory.GetFiles error

my code
private void m1()
{
List<string> list = new List<string>();
foreach (string str in Directory.GetFiles("a1"))
{
if (Path.GetExtension(str).Contains("txt")) -- get all txt file in a1 folder
{
list.Add(Path.GetFileNameWithoutExtension(str));
}
}
base.SuspendLayout();
this.Combobox_1.Items.AddRange(list.ToArray());
base.ResumeLayout();
}
but combobox cannot list txt file in folder a1
Please helpme.
i think there is no need to store values first in a list and then add to a combobox.
it can be done directly to a combobox.
i have replace relative path a1 to a real one to let you understand easily.
foreach (string str in Directory.GetFiles(#"D:\"))
{
if (System.IO.Path.GetExtension(str).Contains("txt"))
{
this.Combobox_1.Items.Add(System.IO.Path.GetFileNameWithoutExtension(str));
}
}

How to add value and text both property to dropdown list

I have three dropdown menu the value part is in web.config.for Drp_List3 dropdowm menu I have value and Text both but I want to show text value in dropdown but to concatenate I want value.Sry guys to bother or if I sound foolish.
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
string server = ConfigurationManager.AppSettings["SV"].ToString();
string[] val1 = server.Split(',');
foreach (string str1 in val1)
{
Drp_List1.Items.Add(str1);
}
string website = ConfigurationManager.AppSettings["site"].ToString();
string[] val2 = website.Split(',');
foreach (string str2 in val2)
{
Drp_List2.Items.Add(str2);
}
string sitetype = ConfigurationManager.AppSettings["ErrorLog"].ToString();
string[] val3 = sitetype.Split(',');
foreach (string str3 in val3)
{
Drp_List3.Items.Add(new ListItem(str3));
}
string sitetypedetail = ConfigurationManager.AppSettings["ErrorLogType"].ToString();
string[] val4 = sitetypedetail.Split(',');
foreach (string str4 in val4)
{
Drp_List3.Items.Add(new ListItem(str4));
}
}
}
Let's try this all over again. For the Page_Load part, here is something to try:
Drp_List3.Items.Add("Website"+ConfigurationManager.AppSettings["MyStuff"]);
Where the "MyStuff" is the key in the web.config that you want to add for the Drp_List3 set of values.
For the dropdowns that are further down in the code sample, I give you this to help with that:
I am presuming that the filename can come straight from the web.config and that other stuff can be done to generate all of the Text and Value portions for the DropDownList which has an Items collection you are trying to fill:
string filename = ConfigurationManager.AppSettings["filename"];
string TextPart = "c:\\mystuff\\"+filename;
string ValuePart = filename;
ListItem li = new ListItem(TextPart,ValuePart);
ddlValues.Items.Add(li);
This will give you a ListItem that you can add to the Items collection of the DropDownList so that the text portion of the option will be the TextPart and the value of the option will be the ValuePart. Now, if you want something else to be set in the Text or Value, just do that prior to creating the ListItem. Something else to note is that a ListBox is not the same as a DropDownList, as the former will just have a collection of values in it that is a straightforward List of text values rather than the KeyValuePair that a DropDownList has. This is why you have to be careful with your language and terminology as I've done more than a few things with various classes that had similar names.
Do you meen something like this ?
DropDownListSearchPrices.Items[0].Value = DropDownListSearchPrices.Items[1].Text;
OR
DropDownListSearchPrices.Items[1].Text = DropDownListSearchPrices.Items[0].Value.toString();

Select multiple ListItems in an <asp:ListBox> from codebehind c#

I've got a ListBox(with selectionMode=multiple) and store the selected values in a cookie.
When the user comes back I want to provide him with all the options selected again.
What I do so far: I get all the selected values and store the indices ","-separated in a string in the cookie.
When the user comes back I split the string and loop through all ListItems to select each one again!
but with:
foreach (string str in selectedStr)
{
listbox1.SelectedIndex = Int32.Parse(str);
}
I only get one (random?) selected value.
Can anyone help me to get all the selected values selected again?
maybe even a better solution?
Just try using FindByValue property of Listview as follow...
foreach (string str in selectedStr)
{
if(listbox1.Items.FindByValue(str) != null)
{
listbox1.Items.FindByValue(str).Selected = true;
}
}
You can iterate through your splitted string array, and access the ListBox.Items[] based on the index and set the Selected property to true.
foreach (string str in selectedStr)
{
listbox1.Items[Int32.Parse(str)].Selected = true;
}
Make sure that str is indeed an integer and its in range with Items.Length

Tag problem c# listbox

Hi i'm trying to use the tag item of a listbox.
heres my code.
int number = 0;
foreach (ListViewItem item in listBox1.Items)
{
Tag tag = (Tag) item.Tag;
saveSlide(showid, tag.photoid, enumber);
number++;
}
problem im havin is when i run the program i get an error message sayin cannot convert type string to system.ListView but i haven't declared item as a string anywher in my program
This is where i add the items to the listbox. Please help. Im on a dead line and have sooo much more to do
private void buttonAdd_Click(object sender, EventArgs e)
{
//add selected item into listBox
DataRowView drv = (DataRowView)listBox1.SelectedItem;
Tag tag = new Tag();
string title = drv["title"].ToString();
ListViewItem item = new ListViewItem(title);
item.Tag = tag;
tag.photoid = (int)drv["photoid"];
listBox1.Items.Add(title);
}
Poppy you are adding title to listBox1.Items.
title is of type string.
So when you access it use string type like this foreach (string item in listBox1.Items).
Try. Does it help?
int number = 0;
foreach (string item in listBox1.Items)
{
Tag tag = (Tag) item.Tag;
saveSlide(showid, tag.photoid, enumber);
number++;
}
This works, you need to show the code where you add items to the list:
private class Tag
{
public override string ToString()
{
return "Tag";
}
}
ListBox listBox = new ListBox();
listBox.Items.Add(new ListViewItem { Tag = new Tag() });
foreach (ListViewItem item in listBox.Items)
{
Tag tag = (Tag)item.Tag;
Console.WriteLine(tag);
}
Edit following more code:
You are adding strings to your ListBox instead of the ListViewItem:
listBox1.Items.Add(title); should be listBox1.Items.Add(item);
ListBox.Items is an ObjectCollection. That means you can choose the kind of object to put in it.
When you're doing this:
string title = drv["title"].ToString();
listBox1.Items.Add(title);
you are putting string objects into it, so you would need to get them out like this:
foreach (string item in listBox1.Items)
Instead, you probably want your code to be more like this:
ListViewItem item = new ListViewItem(title);
item.Tag = tag;
tag.photoid = (int)drv["photoid"];
listBox1.Items.Add(item); // The difference is here - add *item* not *title*
then you'll be able to use this the way you initially wrote it:
foreach (ListViewItem item in listBox1.Items)
Does Tag has a member named photoid? Maybe you need a cast in there to convert your 'tag' to whatever it's supposed to be?
//Tag tag = (Tag) item.Tag;
MyObject tag = (MyObject)item.Tag;
saveSlide(showid, tag.photoid, enumber);
number++;
Unless you named things weird I'd say the error is that you're trying to get a ListViewItem from a ListBox.
Just change the last line of code of the second code-snippet and everything will be ok, which is as follows.
listBox1.Items.Add(item);
About the Error
You added strings to the listBox as items and in the foreach an item(which is a string) is tried to convert(caste) to ListViewItem implicitly to hich doesn't work and the compiler gives the error.
Hope it will work.

Categories