How I Select value from object on the listbox? - c#

Here is the list item Class:
class ListItem
{
public string Key;
public string Value;
public ListItem()
{
}
public string key
{
get { return Key; }
set { key = value; }
}
public string value
{
get { return Value; }
set { Value = value; }
}
public override string ToString()
{
return Key;
}
public string getvalue(string blabla)
{
return Value;
}
}
private void btnOpen_Click(object sender, EventArgs e)
{
string[] Folders = Directory.GetDirectories(txtFolder.Text);
foreach (string f in Folders)
{
ListItem n = new ListItem();
n.Value = f;
n.Key = Path.GetFileName(f);
listBoxSidra.Items.Add(n);
}
}
private void listBoxSidra_SelectedIndexChanged_1(object sender, EventArgs e)
{
try
{
lblmsg.Text = null;
comboBoxSeason.Items.Clear();
string[] seasons = Directory.GetDirectories(listBoxSidra.SelectedValue.ToString());
for (int i = 0; i < seasons.Length; i++)
{
comboBoxSeason.Items.Add(seasons[i]);
}
comboBoxSeason.SelectedIndex = 0;
}
catch (Exception ex)
{
lblmsg.Text = ex.Message;
}
}
First Method : I open class named it ListItem , its contains foldername(key) and folder location (value).
Secound Method: I created an array wich contains all the subdirectories from the the directory I set on the text box .
I also created ListItem object named it 'n' , then I set Values to 'n' ,n.Value(represnt the directory location) and n.Key(represnt the directory name).
next step is to add the 'n' object to the list box, now on the listbox i can see the directory name , and each object contains his location .
Thrid Method : thats where im stuck , i created an array, the array suppoed to contain the subdirectory from the chosen listbox item , I mean ,when I will click on a listbox item I want to get his value(the value represent the location ) and by that add the subdirectories to the array , what should i write instead of listBoxSidra.SelectedValue.ToString() ??
Thanks!

In order to make your code work make following changes
private void btnOpen_Click(object sender, EventArgs e)
{
string[] Folders = Directory.GetDirectories(txtFolder.Text);
var dataSource = new List<ListItem>();
foreach (string f in Folders)
{
ListItem n = new ListItem();
n.Value = f;
n.Key = Path.GetFileName(f);
dataSource.Add(n);
}
listBoxSidra.DataSource = dataSource;
listBoxSidra.DisplayMember = "key";
listBoxSidra.ValueMember = "value";
}

Related

Returning objects from list to a listbox

I've been trying to create a method which adds items in to the listbox.
There is a class Member and each Member belongs to the ProjectGroup. Member has a method getName() which returns string name. So the problem appears when I try to add more than 1 person. The listbox gets stuck at first person in the list, and nothing new appears. The code looks like this:
public class ProjectGroup
{
List<Member> members = new List<Member>();
public void addMember(string name)
{
Member newPerson = new Member(name);
members.Add(newPerson);
}
public string getInfo()
{
foreach (Member item in members)
{
return item.getName();
}
return null;
}
}
And the code in the form:
ProjectGroup group = new ProjectGroup();
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string name = textBox1.Text;
lbStudents.Items.Clear();
textBox1.Text = "";
group.addMember(name);
lbStudents.Items.Add(group.getInfo());
}
public List<string> getInfo()
{
var result= new List<string>();
foreach (Member item in members)
{
result.Add(item.getName());
}
return result;
}
and change it:
lbStudents.Items.AddRange(group.getInfo());

Get selected value from asp SharePoint DropDownList of custom class type

I am writing a SharePoint app. There I have page with drop down list. I have
a handler for SelectedIndexChanged. I want to get the selected value but as CustomObject and the only option I see is string. I tried SelectedValue and it is still string.
That's how I set the list:
protected void Page_Load(object sender, EventArgs e)
{
List<CustomObject> customList = //retrieving data
myDropDownList.DataSource = customList.Select(x => new { x.Name, Value = x});
myDropDownList.DataTextField = "Name";
myDropDownList.DataValueField = "Value";
myDropDownList.DataBind();
}
And that's one of the ways I tried:
protected void myDropDownList_SelectedIndexChanged(object sender, EventArgs e)
{
var index = groupingDropDownList.SelectedIndex;
CustomObject obj = (CustomObject)myDropDownList.Items[index].Value;
obj.DoSomething();
}
Is it even possible? Or do I have to have somewhere Dictionary with with objects?
You will want to leverage the html5 data attributes that you can then place onto the dropdown options. Here is an example of what you could do with your data.
// add Agencies' addresses as HTML5 data-attributes.
var agencies = agencyNames.ToList();
for (int i = 0; i < requesting_agency.Items.Count - 1; i++) {
requesting_agency.Items[i + 1].Attributes.Add("data-address",
agencies[i].address);
servicing_agency.Items[i + 1].Attributes.Add("data-address",
agencies[i].address);
}
Then when processing the information you could do something like so.
var index = groupingDropDownList.SelectedIndex;
var selectedText = myDropDownList.Items[index].SelectedValue;
var selectedValue = myDropDownList.Items[index].Attributes["attribute"];
// put into obj
// do something with object
Let me know if you have any questions.
You 're binding a object (x => new { x.Name, Value = x}) to dropdown value, you should bind actual value to it.
Test demo:
public class CustomObject
{
public int ID { get; set; }
public string Name { get; set; }
public CustomObject(int _ID,string _Name)
{
this.ID = _ID;
this.Name = _Name;
}
}
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
List<CustomObject> customList = new List<CustomObject>();
customList.Add(new CustomObject(1,"test1"));
customList.Add(new CustomObject(2,"test2"));
myDropDownList.DataSource = customList.Select(x => new { x.Name, Value = x.ID });
myDropDownList.DataTextField = "Name";
myDropDownList.DataValueField = "Value";
myDropDownList.DataBind();
}
}

Add objects to arraylist and read them

I'm trying to add objects of DataPerLabel to my Arraylist allData, following the code of DataPerLabel:
class DataPerLabel
{
public String labelName;
public String labelAdress;
public String dataType;
public DataPerLabel(String labelName, String labelAdress, String dataType)
{
this.labelName = labelName;
this.labelAdress = labelAdress;
this.dataType = dataType;
}
public String getLabelName()
{
return labelName;
}
public String getLabelAdress()
{
return labelAdress;
}
public String getDataType()
{
return dataType;
}
}
In the following code I try to add the objects of DataPerLabel to my arraylist:
submitButton.Click += (sender, args) =>
{
String label = textboxLabel.Text;
String adress = textboxAdress.Text;
String dataType = "hey";
if (buttonsLabelBool.Checked)
{
dataType = "Bool";
}
else if (buttonsLabelReal.Checked)
{
dataType = "Real";
}
else if (buttonsLabelInt.Checked)
{
dataType = "Int";
}
allData.Add(new DataPerLabel(label, adress, dataType));
};
And finally I try to read out the arrayList by displaying it in a textbox, see the following code:
private void test()
{
Button btn = new Button();
btn.Location = new Point(500,500);
btn.Text = "test";
btn.Click += (sender, args) =>
{
foreach (var item in allData)
{
//Display arraylist per object here
//Something like : item.getLabelName();
}
};
}
I'm not sure what I'm doing wrong, hope you can help!
ArrayList stores a list of System.Object. You need to cast the object back to DataPerLabel as follows:
foreach (var item in allData)
{
((DataPerLabel)item).getLabelName();
}
Alternatively, you could specify the data type in the foreach instead of var as Jakub DÄ…bek pointed out in the comment as follows:
foreach (DataPerLabel item in allData)
{
item.getLabelName();
}
A better approach would be to use generic list/collection List<DataPerLabel> to store the data so that the casting can be avoided.
Yiu should use a List<T> instead of ArrayList. This way every item in your list has the right type already and you can access the members:
foreach (DataPerLabel item in allData)
{
item.GetLabelItem();
}
This assumes allData is defined like this:
allData = new List<DataPerLabel>();
instead of allData = new ArrayList()
If you really have to use an ArrayList than you should cast your item to the actual type. The code above actually does this allready. However you could also use this:
foreach (var item in allData)
{
((DataPerLabel)item).GetLabelItem();
}

C# Reading from multiple text files, splitting lines into a List, and then loading into ListBox

I'm getting a few errors and also my code is unfinished. I was using another Stackoverflow question to set this up to begin with but it wasn't fit to my needs.
I have three text files which the data is split by commas such as "Name,25,25.6" so string, int, decimal. I have all three text files that have three columns like that, same data types, but just different names/numbers.
I have three different list boxes that I want to split them into but I'm having trouble getting the three different split list items to get into three different list boxes. I'll copy and paste all the code I have. I am also using a combo box to allow the user to select the file they want to load into the combo box which I believe I got it right.
The errors I get are in the displayLists(), it says on the lstItemName.DataSource = Inventory; line that Inventory does not exist in the current context. There are also a plenitude of other errors.
Any help will be appreciated, I'll copy and paste my code. I have a Windows Form and I'm using Visual Studio Express 2012 in C#
namespace TCSCapstone
{
public partial class frmInventory : Form
{
public frmInventory()
{
InitializeComponent();
}
string cstrItemName;
int cintNumberOfItems;
decimal cdecPrice;
decimal cdecTotalPrices;
string selectedList = "";
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
selectedList = this.cmbList.GetItemText(this.cmbList.SelectedItem);
if (selectedList == "Creative Construction")//if the selected combo
box item equals the exact string selected
{
selectedList = "creative"; //then the string equals creative,
which is creative.txt but I add the .txt in the btnLoadInfo method
} else if (selectedList == "Paradise Building")
{
selectedList = "paradise";//this is for paradise.txt
}
else if (selectedList == "Sitler Construction")
{
selectedList = "sitler";//this is for sitler.txt
}
else
{
MessageBox.Show("Please select one of the items.");
}
}
private void btnLoadInfo_Click(object sender, EventArgs e)
{
List<frmInventory> Inventory = new List<frmInventory>();
using (StreamReader invReader = new StreamReader(selectedList +
".txt"))
{
while (invReader.Peek() >= 0)
{
string str;
string[] strArray;
str = invReader.ReadLine();
strArray = str.Split(',');
frmInventory currentItem = new frmInventory();
currentItem.cstrItemName = strArray[0];
currentItem.cintNumberOfItems = int.Parse(strArray[1]);
currentItem.cdecPrice = decimal.Parse(strArray[2]);
Inventory.Add(currentItem);
}
}
displayLists();
}//end of btnLoadInfo
void displayLists()
{
int i;
lstItemName.Items.Clear();
lstNumberOfItems.Items.Clear();
lstPrice.Items.Clear();
lstTotalPrices.Items.Clear();
lstItemName.DataSource = Inventory;
lstItemName.ValueMember = "cstrItemName";
lstItemName.DisplayMember = "cintNumberOfItems";
}
}//end of frmInventory
}//end of namespace
I do not know if this is exactly what you need, but try something like this:
public partial class Form2 : Form
{
List<Inventory> inventory;
public Form2()
{
InitializeComponent();
}
public void ReadFiles()
{
if (inventory == null)
inventory = new List<Inventory>();
using (TextReader r = new StreamReader("file.txt"))
{
string line = null;
while ((line = r.ReadLine()) != null)
{
string[] fields = line.Split(',');
Inventory obj = new Inventory();
obj.Name = fields[0];
obj.Qtd = Convert.ToInt32(fields[1]);
obj.Price = Convert.ToInt32(fields[2]);
inventory.Add(obj);
}
}
SetDataSourceList();
}
public void SetDataSourceList()
{
listBox1.DisplayMember = "Name";
listBox2.DisplayMember = "Qtd";
listBox3.DisplayMember = "Price";
listBox1.DataSource =
listBox2.DataSource =
listBox3.DataSource =
inventory;
}
}
public class Inventory
{
public string Name { get; set; }
public int Qtd { get; set; }
public decimal Price { get; set; }
}

Issue displaying dictionary list values in listbox C#

I currently have two list boxes. One is to store the key and the second is to view the list associated with it.
The following code I have displays the key in the first listBox but fails to show the list in the second:
public void button1_Click(object sender, EventArgs e)
{
var xmlDoc = new XmlDocument();
xmlDoc.Load(textBox1.Text);
var node = xmlDoc.SelectNodes("pdml/packet/proto[#name='ip']/#showname");
foreach (XmlAttribute attribute1 in node)
{
string ip = attribute1.Value;
var arr = ip.Split(); var src = arr[5]; var dst = arr[8];
Dictionary<string, List<string>> dict = new Dictionary<string,List<string>>(StringComparer.OrdinalIgnoreCase);
List<string> listDST;
if (!dict.TryGetValue(src, out listDST))
{
dict[src] = l = new List<string>();
}
l.Add(listDST);
listBoxSRC.DataSource = new BindingSource(dict,null);
listBoxSRC.DisplayMember = "Value";
listBoxSRC.ValueMember = "Key";
}
}
private void listBoxSRC_SelectedIndexChanged(object sender, EventArgs e)
{
if (listBoxSRC.SelectedItem != null)
{
var keyValue = (KeyValuePair<string, List<String>>)listBoxSRC.SelectedItem;
listBoxDST.DataSource = keyValue.Value;
}
else
{
listBoxDST.DataSource = null;
}
}
I have checked using the debugger to make sure that there is data contained in the dictionaries list so I am not sure what the problem is.
Can anyone point out where I maybe going wrong?
Thanks
Lists of 'naked' strings can't be used as a DataSource. You need to wrap them in a simple class with a real property. See here
After you have declared a simple string wrapper class:
class aString { public string theString { get; set; }
public aString(string s) { theString = s; }
public override string ToString() {return theString;} }
you can either change your Dictionary to contain a List<aString> or you can create a List<aString> from your Dictionary Values:
List<aString> aStringList = dict [src].Select(item => new aString(item) ).ToList();
listBoxDST.DataSource = aStringList ;
The ListBox can now display the aString.ToString() values.
try this man
public void button1_Click(object sender, EventArgs e)
{
var xmlDoc = new XmlDocument();
xmlDoc.Load(textBox1.Text);
var node = xmlDoc.SelectNodes("pdml/packet/proto[#name='ip']/#showname");
foreach (XmlAttribute attribute1 in node)
{
string ip = attribute1.Value;
var arr = ip.Split(); var src = arr[5]; var dst = arr[8];
Dictionary<string, List<string>> dict = new Dictionary<string,List<string>>(StringComparer.OrdinalIgnoreCase);
List<string> listDST;
if (!dict.TryGetValue(src, out listDST))
{
dict[src] = l = new List<string>();
}
l.Add(listDST);
}
listBoxSRC.DataSource = new BindingSource(dict,null);
listBoxSRC.DisplayMember = "Value";
listBoxSRC.ValueMember = "Key";
}
private void listBoxSRC_SelectedIndexChanged(object sender, EventArgs e)
{
if (listBoxSRC.SelectedItem != null)
{
var keyValue = (KeyValuePair<string, List<String>>)listBoxSRC.SelectedItem;
listBoxDST.DataSource = keyValue.Value;
}
else
{
listBoxDST.DataSource = null;
}
}

Categories