Issue displaying dictionary list values in listbox C# - 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;
}
}

Related

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

Last item only being added to db

I am trying to add some controls to a list but for some reason its only saving the last view to the db.
public List<tblPortalIandEValue> createIandERecord(Guid _userId, string fieldName, string fieldValue)
{
List<tblPortalIandEValue> _iandevalues = new List<tblPortalIandEValue>();
_iandevalues.Add(new tblPortalIandEValue { userId = _userId, field_name = fieldName, field_value = fieldValue });
return _iandevalues;
}
I think my problems lies in my save cause I'm calling this list add new and then returning it think I should be returning the record instead
protected void btnSave_Click(object sender, EventArgs e)
{
List<tblPortalIandEValue> _iandevalues = new List<tblPortalIandEValue>();
_customerId = Guid.NewGuid();
_iandevalues=_dal.createIandERecord(_customerId , "mortagecic", mortagecic.Value.ToString());
_iandevalues = _dal.createIandERecord(_customerId, "gascic", gascic.Value.ToString());
_iandevalues = _dal.createIandERecord(_customerId, "electricitycic", electricitycic.Value.ToString());
_iandevalues.ForEach(n =>_dal.portalEntities.tblPortalIandEValues.Add(n));
_dal.portalEntities.SaveChanges();
}
Your problem is in your createIandERecord method since you are renewing the list everytime. change your code to this:
public tblPortalIandEValue createIandERecord(Guid _userId, string fieldName, string fieldValue)
{
return new tblPortalIandEValue { userId = _userId, field_name = fieldName, field_value = fieldValue });
}
protected void btnSave_Click(object sender, EventArgs e)
{
List<tblPortalIandEValue> _iandevalues = new List<tblPortalIandEValue>();
_customerId = Guid.NewGuid();
_iandevalues.Add(_dal.createIandERecord(_customerId, "mortagecic", mortagecic.Value.ToString()));
_iandevalues.Add(_dal.createIandERecord(_customerId, "gascic", gascic.Value.ToString()));
_iandevalues.Add(_dal.createIandERecord(_customerId, "electricitycic", electricitycic.Value.ToString()));
_iandevalues.ForEach(n => _dal.portalEntities.tblPortalIandEValues.Add(n));
_dal.portalEntities.SaveChanges();
}

How I Select value from object on the listbox?

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";
}

Adding a row in a gridview from a Dictionary<Key,Value>

I have a LinkButton on my Page1.aspx with the fields
Attached below is the image of page1.aspx. And a gridview in Page2.aspx.. When i click onto the linkbutton , the page redirects to Page2.aspx and fill the gridview with the required fields..
where the Required Fields are
Image,
Name = Black Cap,
Title = Topi,
Price = 1200
The Code of Page1.aspx:
protected void ListView1_ItemCommand(object sender, ListViewCommandEventArgs e)
{
Dictionary<string, string> OrderDict = new Dictionary<string, string>();
if (e.CommandName == "orderClick")
{
string value = e.CommandArgument.ToString();
string id = this.ListView1.DataKeys[e.Item.DataItemIndex].Value.ToString();
OrderDict.Add(id, value);
Session["Order"] = OrderDict;
Response.Redirect("Page2.aspx");
Response.Write(OrderDict);
}
}
The Code of Page2.aspx:
protected void Page_Load(object sender, EventArgs e)
{
Dictionary<string, string> Dictionary = (Dictionary<string, string>)Session["Order"];
//Regex reg = new Regex(#"\[([^\]]+)\]([^\[]+)");
if (Dictionary != null)
{
GridView1.DataSource = Dictionary;
//Dictionary = reg.Matches(Dictionary.ToString()).Cast<Match>().ToDictionary(x => x.Groups[1].Value
// , x => x.Groups[2].Value.Trim());
//string slit = Dictionary.s
this.GridView1.DataBind();
//this.GridView1.DataSource = Dictionary;
Response.Write(Dictionary.Values.Count);
}
}
This is the first time I see code that binds to a dictionary. You should bind to the Keys property of the dictionary.
// Change your original line in Page_Load to this... The variable name conflicts with the class name
Dictionary<string, string> orderDictionary = (Dictionary<string, string>)Session["Order"];
// Bind like this:
GridView1.DataSource = orderDictionary.Keys;
See Dictionary(Of TKey, TValue).Keys Property
Have you considered creating a class that represents the list of items you're storing in the Session? For example:
public class SelectedOrder
{
public string ID { get; set; }
public string Value { get; set; }
}
// Then in your ListView ItemCommand in Page1.aspx
var orders = ((List<SelectedOrder>)Session["Order"]) ?? new List<SelectedOrder>();
orders.Add(new SelectedOrder() { ID = id, Value = value });
Session["Order"] = orders;
// And in Page2
List<SelectedOrder> orders = (List<SelectedOrder>)Session["Order"];
if (null != orders) {
GridView1.DataSource = orders;
GridView1.DataBind();
// Rest of code follows...
}
I think this will be an easier approach to deal with in your code.

Categories