Conver binary tree to MenuStrip [closed] - c#

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I have a List<MenuReponse> menus like:
How can I convert it to MenuStrip when I load the Form like:

It's simply using recursion with data structure logic. Before going to answer the question, I have some suggestions:
It's not a binary tree, it's ordinary tree
Should use english naming parameters in SO to get fullly support, besides that, it's even not violate the naming convention rules :)
I'm assuming that your model like:
public class MenuResponse
{
public string Name { get; set; }
public MenuResponse Parent { get; set; }
public List<MenuResponse> Childrens { get; set; }
}
Create instance root MenuResponse which won't show on the menu. This root would be a combination tree for easier finding.
MenuResponse root = new MenuResponse();
root.Name = "Root";
root.Childrens = yourListMenuResponse; // Attach your list here
CreateMenuStrips(root);
CreateMenuStrips creates menu on top line, CreateDropDownMenus creates item using recursion
public void CreateMenuStrips(MenuResponse root)
{
foreach (var child in root.Childrens)
{
var menu = new ToolStripMenuItem(child.Name);
CreateDropDownMenus(child, menu);
baseMenuStrip.Items.Add(menu);
}
}
public void CreateDropDownMenus(MenuResponse menuRes, ToolStripMenuItem menu)
{
if (menuRes.Childrens == null)
return;
foreach (var child in menuRes.Childrens)
{
var childMenu = menu.DropDownItems.Add(child.Name);
CreateDropDownMenus(child, childMenu as ToolStripMenuItem);
}
}
Result
I implemented the data function for anyone would like to test
public static class MenuUtils
{
public static MenuResponse AddChildMenu(this MenuResponse menu, string name)
{
if (menu.Childrens is null)
menu.Childrens = new List<MenuResponse>();
MenuResponse newMenu = new MenuResponse();
newMenu.Name = name;
newMenu.Parent = menu;
menu.Childrens.Add(newMenu);
return newMenu;
}
public static MenuResponse AddSiblingMenu(this MenuResponse menu, string name)
{
return menu.Parent.AddChildMenu(name);
}
}
Create data
MenuResponse root = new MenuResponse();
root.Name = "Root";
root.Childrens = new List<MenuResponse>();
root.AddChildMenu("Feature")
.AddChildMenu("Feature 1")
.AddSiblingMenu("Feature 2")
.AddChildMenu("Feature 2.1").Parent
.AddSiblingMenu("Feature 3")
.AddChildMenu("Feature 3.1")
.AddSiblingMenu("Feature 3.2")
.AddChildMenu("Feature 3.2.1");
root.AddChildMenu("Test")
.AddChildMenu("Test 1")
.AddChildMenu("Test 1.1")
.AddChildMenu("Test 1.1.1")
.AddSiblingMenu("Test 1.1.2");

Related

Array of Objects to String - ASP.NET C# [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 months ago.
Improve this question
Trying to convert Array of Objects to String using C#. Able to achieve the same using LINQ, however trying to make use of reusable functions which would accept array of Objects and return back string. Understand that generics must be used but it's been hard time understanding it. Thanks in advance!
public class HelloWorld {
public static void Main() {
Root root = new Root();
List<A> obj = new List<A>();
obj.Add(new A() { Code = "WAY"});
obj.Add(new A() { Code = "DOWN"});
obj.Add(new A() { Code = "WE"});
obj.Add(new A() { Code = "GO"});
root.A = obj;
string _Result = string.Join("-", root.A.Where(x => x.Code != "").Select(p => p.Code.ToString()).ToArray());
Console.WriteLine(_Result); //Expected OP: WAY-DOWN-WE-GO
Console.WriteLine(Utility.ToArray(root.A)); //System.Collections.Generic.List`1[A]
}
//Trying for much simpler Generic function here.
public class Utility{
public static string ToArray(IList<Object> obj){
foreach(var v in obj){
//generic function..
}
StringBuilder sb = new StringBuilder();
return sb.ToString();
}
}
}
public class Root
{
public List<A> A { get; set; }
public List<B> B { get; set; }
}
public class A
{
public string Code { get; set; }
}
public class B
{
public string Mode { get; set; }
}
If you're looking for a system that works without having to have your classes implement an interface (for objects you didn't create, for example), it's possible to use a Func<T, object> to select a specific property/field:
// IEnumerable is more generic over "lists" (sets, maps, etc)
// \/
public static string ToArray<T>(IEnumerable<T> obj, Func<T, object> func) {
return string.Join('-', obj.Select(func));
}
Usage example:
List<A> aObjects = new();
//add aObjects
List<B> bObjects = new();
//add bObjects
Console.WriteLine(Utilities.ToArray(aObjects, a => a.Code));
Console.WriteLine(Utilities.ToArray(bObjects, b => b.Mode));
Reference: How to join as a string a property of a class?

Why does instantiating a new object in each iteration of a for loop overwrite previous list entries? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I'm trying to dynamically populate a list of objects as follows:
using System;
using System.Collections.Generic;
namespace test
{
class MainClass
{
public static void Main(string[] args)
{
List<string> items = new List<string>() { "item1", "item2", "item3" };
List<MainObject> objects = new List<MainObject>();
foreach (var item in items)
{
objects.Add(new MainObject(item));
foreach (MainObject o in objects)
Console.WriteLine(o.getString());
}
}
}
class MainObject
{
public MainObject() { }
public MainObject(string theString) { nString = theString; cString = theString; }
private static string nString { get; set; }
private static string cString { get; set; }
public string getString() { return nString; }
}
}
I figure that since I'm using the "new" operator I'm instantiating a new object each loop, but it overwrites the previous entry every time.
It gives an output like the following:
item1
item2
item2
item3
item3
item3
It is side effect of the way how you use WriteLine, or, to be more precise, where you use WriteLine.
Modify your code to something like this:
List<Object> objects = new List<Object>();
foreach (var theString in stringList)
{
objects.Add(new Object(theString));
}
//this should be outside of first loop
foreach (Object object in objects)
{
Console.WriteLine(object.getValue());
}
The definition of MainClass is using static fields and that's causing their values to be overwritten each time a new MainObject is created.
There's only one memory location for each static field. In the constructor, that memory location is being assigned the value of the parameter, which overwrites any value previously passed to the constructor.
On the other hand, an instance (non-static) field has a separate location within each instance. In that case, the assignment affects that object instance and not any others.
All you have to do is remove the static modifier from those properties.
class MainObject
{
public MainObject() { }
public MainObject(string theString) { nString = theString; cString = theString; }
// Remove 'static' from these two declaration
private string nString { get; set; }
private string cString { get; set; }
public string getString() { return nString; }
}

fetch details from csv file on basis of name search c#

Step 1: I have created a C# application called : Student details
Step 2: Added four TextBoxes and named them as :
Image below to refer:
Studentname.Text
StudentSurname.Text
StudentCity.Text
StudentState.Text
DATA INSIDE CSV FILE
vikas,gadhi,mumbai,maharashtra
prem,yogi,kolkata,maha
roja,goal,orissa,oya
ram,kala,goa,barka
Issue is How do I fetch all the data(surname,city,state) of user prem into above textboxes studentsurname,studentcity,studentstate from csv file when I search the name in textbox 1 => studentname.Text as prem
Below is the Code where I am stuck at return null and code inside Load_Script_Click
void Connection_fetch_details(String searchName)
{
var strLines = File.ReadLines(filePath);
foreach (var line in strLines)
{
if (line.Split(',')[0].Equals(searchName))
{
Connection_fetch_details cd = new Connection_fetch_details()
{
username = line.Split(',')[1]
};
}
}
return;
}
private void Load_Script_Click(object sender, EventArgs e)
{
// load script is button
String con_env = textenv.Text.ToString();
//Address Address = GetAddress("vikas");
//textsurname.text = Address.Surname
Connection_fetch_details cd = Connection_fetch_details(con_env);
textusername.Text = cd.username;
}
==============================================================
Class file name : Address.class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace DDL_SCRIPT_GENERATOR
{
public class Connection_fetch_details
{
public string username { get; set; }
}
}
The main problem is that your method is void, which means it doesn't return any value. So even though you may be finding a match, and creating a Connection_fetch_details object, you aren't returning that result back to the calling method.
This will fix that problem:
Connection_fetch_details Connection_fetch_details(String searchName)
{
var strLines = File.ReadLines(filePath);
foreach (var line in strLines)
{
if (line.Split(',')[0].Equals(searchName))
{
Connection_fetch_details cd = new Connection_fetch_details()
{
username = line.Split(',')[1]
};
return cd; //return the object containing the matched username
}
}
return null;
}
Now it will return a Connection_fetch_details object if there is a match, or null if there is no match.
Next, you asked about returning all the fields, not just one. For that you would need to
a) add more properties to your object
b) add more code to populate those properties from the CSV
c) add code to populate the textboxes with the results from the object.
I'm also going to rename "username" to something more relevant, since none of the field names you described in the question match that. I'm also going to rename your class to "Student", and rename your search method, for the same reason.
Here's an example:
Student searchStudent(String searchName)
{
var strLines = File.ReadLines(filePath);
foreach (var line in strLines)
{
var split = line.Split(',');
if (split[0].Equals(searchName))
{
Student s = new Student()
{
firstname = searchName,
surname = split[1],
city = split[2],
state = split[3]
};
return s; //return the object containing the matched name
}
}
return null;
}
private void Load_Script_Click(object sender, EventArgs e)
{
// load script is button
String con_env = textenv.Text.ToString();
//Address Address = GetAddress("vikas");
//textsurname.text = Address.Surname
Student st = searchStudent(con_env);
textsurname.Text = st.surname;
txtcity.Text = st.city;
txtstate.Text = st.state;
}
namespace DDL_SCRIPT_GENERATOR
{
public class Student
{
public string firstname { get; set; }
public string surname { get; set; }
public string city { get; set; }
public string state { get; set; }
}
}
To accomplish your goal you have to further separate your problem in more granular steps and also distinguish between what you show in your UI and what informations you hold in the background in which format.
Create a class with the desired properties
public class Student { public string Name { get; set; } ... }
Learn how to read a csv file into such an object by using an existing library like CsvHelper or CsvReader.
When you have something like List<Student> from this part. Learn how you can visualize such a thing by using some Binding (also depends on the visualization you use Winforms, WPF, etc.).
Depending on the visualization component it already supports filtering or you need to filter by yourself by using e.g. LINQ to get the matching elements students.Where(student => student.Name.StartsWith(search)).
So far a lot of smaller problems which is simply to much to answer in a single one. Please try to break down your problems into smaller ones and search for their solutions. If you get stuck, ask a new question. That's all I can do for you now.

How to handle parameters right in c#?

I just started using c# again and now I have a strange problem with my parameters.
I tried to build a List by my self.
So I have:
class NodeList
{
public Node FirstCity { get; set; }
public Node findNode(String name)
{
//...stuff
}
}
And This:
class Node
{
public String Name {get; set;}
public Node next {get; set;}
}
So, in my project I (lets say on button click) create a new Nodelist.
(By default I have already a few nodes in it.)
Now I do this:
Node n = nodelist.findNode("test");
and then I have another class I called tool.
tool.doSomething(n , nodelist);
Now the strange thing is that, when I look at nodelist, when I call the above the list is correct. The doSomething method, doesn´t even call the nodelist but it changes it.
doSomething(n, list)
{
NodeList nl = new NodeList();
nl.Add(n);
//other stuff
}
At the point where I change the new List for some reason the other list, which is in a different class, changes too.
Can anyone please explain why and how I can fix this!?
Edit:
This is my Add Method:
Add(Node node){
node.next = null;
Node current = FirstCity;
if (current == null)
FirstCity = node;
else
{
while (current.next != null)
{
current = current.next;
}
current.next = node;
}
}

C# help in classes [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I have two classes, SuperHero and SuperTeam. How can I add instances of SuperHero to the TeamList property of SuperTeam?
namespace SuperLeague
{
class SuperHero
{
string SuperHeroName;
string ComicTitle;
public SuperHero()
{
SuperHeroName = "";
ComicTitle = "";
}
public SuperHero(string nSuperHeroName,string nComicTitle)
{
SuperHeroName = nSuperHeroName;
ComicTitle = nComicTitle;
}
public string nSuperHeroName
{
get { return SuperHeroName; }
set { SuperHeroName = nSuperHeroName; }
}
public string nComicTitle
{
get { return ComicTitle; }
set { ComicTitle = nComicTitle; }
}
}
class SuperTeam
{
string SuperTeamName;
List<SuperTeam> TeamList = new List<SuperTeam>();
public SuperTeam()
{
SuperTeamName = "";
}
public SuperTeam(string nSuperTeamName)
{
SuperTeamName = nSuperTeamName;
}
public string nSuperTeamName
{
get { return SuperTeamName; }
set { SuperTeamName = nSuperTeamName; }
}
public void SuperTeamAdd(SuperHero NewHero)
{
TeamList.Add(NewHero);
}
public void SuperTeamRemove(string NameToFind)
{
SuperHero SuperHeroToDel = null;
for (int i = 0; i < TeamList.Count; i++)
{
if (TeamList[i].nSuperHeroName.Equals(NameToFind))
{
SuperHeroToDel = TeamList[i];
TeamList.Remove(SuperHeroToDel);
}
}
}
}
}
Given the provided code;
Your SuperHero class represents a single hero.
Your SuperTeam class represents a single team which contains a list of hero's.
If you want multiple team's with super hero's we'll need another container. Something like
List<SuperTeam> listOfTeams;
This will allow you to store multiple "SuperHero"'s into the "SuperTeam", and store multiple teams in "listOfTeams"
Since you mention you want to get a team used on it's name, you could also use a "Dictionary<string, SuperTeam> CollectionOfTeams". This will allow you to get a team from 'CollectionOfTeams' using the a key.
SuperHero superMan = new SuperHero();
// fill in superMan properties
SuperTeam flyingTeam = new SuperTeam();
flyingTeam.members.Add(superMan);
// add more super hero members that fly to the team
collectionOfTeams.Add("Flying", flyingTeam);
// Getting the 'flying team'
SuperTeam currentTeam = CollectionOfTeams["Flying"];
Hope this helps,
Like this:
SuperHero hero = new SuperHero();
SuperTeam team = new SuperTeam();
team.TeamList.Add(hero);
Also, change the TeamList property to this:
List<SuperHero> TeamList;

Categories

Resources