I am trying to create a multilevel tree view using ObjectListview. But problem is that it create only one parent and add the child in that parent.
My tree stricture in any form
A
-a1
-a2
-a3
-a4
- a4(i)
B
- b (a)
- c (a)
C
Means my tree can be multilevel. Below is my code that i use to bind the treeListView
private void InitializeData(int appId)
{
try
{
UserDAC _UserDAC = new UserDAC();
DataTable SEC_InfoTreeView = _UserDAC.GetAPPITEMSbyAPPID(appId, "", this.FindForm().Name, "InitializeFristTabValue()").Tables[0];
data = new List<Node> { }; // this i bind my treelistview
var Blank = new Node(0, "User Name", "Status", "Static Caption");
var parent1= new Node(0,"", "", " ");
treeListView1.SmallImageList = imageList1;
if (SEC_InfoTreeView.Rows.Count > 0)
{
for (int i = 0; i < SEC_InfoTreeView.Rows.Count; i++)
{
if (i == 0)
data.Add(Blank);
int PrentID = Convert.ToInt32(SEC_InfoTreeView.Rows[i]["PARENTID"]);
if (Convert.ToString(SEC_InfoTreeView.Rows[i]["INDENT"]) != "")
{
if (PrentID == 0 && Convert.ToInt32(SEC_InfoTreeView.Rows[i]["INDENT"]) == 0)
{
data.Add(parent1);
var parentAdd = new Node(Convert.ToInt32(SEC_InfoTreeView.Rows[i]["APPITEMID"]), Convert.ToString(SEC_InfoTreeView.Rows[i]["USERNAME"]), "", Convert.ToString(SEC_InfoTreeView.Rows[i]["ACAPTION"]));
parent1 = parentAdd;
}
else if (PrentID != 0 && Convert.ToInt32(SEC_InfoTreeView.Rows[i]["INDENT"]) == 2)
{
parent1.Children.Add(new Node(Convert.ToInt32(SEC_InfoTreeView.Rows[i]["APPITEMID"]),Convert.ToString(SEC_InfoTreeView.Rows[i]["USERNAME"]), "", Convert.ToString(SEC_InfoTreeView.Rows[i]["ACAPTION"])));
}
else if (PrentID != 0 && Convert.ToInt32(SEC_InfoTreeView.Rows[i]["INDENT"]) == 4)
{
parent1.Children.Add(new Node(Convert.ToInt32(SEC_InfoTreeView.Rows[i]["APPITEMID"]),Convert.ToString(SEC_InfoTreeView.Rows[i]["USERNAME"]), "", Convert.ToString(SEC_InfoTreeView.Rows[i]["ACAPTION"])));
}
else if (PrentID != 0 && Convert.ToInt32(SEC_InfoTreeView.Rows[i]["INDENT"]) == 6)
{
parent1.Children.Add(new Node(Convert.ToInt32(SEC_InfoTreeView.Rows[i]["APPITEMID"]),Convert.ToString(SEC_InfoTreeView.Rows[i]["USERNAME"]),"", Convert.ToString(SEC_InfoTreeView.Rows[i]["ACAPTION"])));
}
else if (PrentID != 0 && Convert.ToInt32(SEC_InfoTreeView.Rows[i]["INDENT"]) == 10)
{
parent1.Children.Add(new Node(Convert.ToInt32(SEC_InfoTreeView.Rows[i]["APPITEMID"]),Convert.ToString(SEC_InfoTreeView.Rows[i]["USERNAME"]), "", Convert.ToString(SEC_InfoTreeView.Rows[i]["ACAPTION"])));
}
else if (PrentID != 0 && Convert.ToInt32(SEC_InfoTreeView.Rows[i]["INDENT"]) == 8)
{
parent1.Children.Add(new Node(Convert.ToInt32(SEC_InfoTreeView.Rows[i]["APPITEMID"]),Convert.ToString(SEC_InfoTreeView.Rows[i]["USERNAME"]),"", Convert.ToString(SEC_InfoTreeView.Rows[i]["ACAPTION"])));
}
else if (PrentID != 0 && Convert.ToInt32(SEC_InfoTreeView.Rows[i]["INDENT"]) == 12)
{
parent1.Children.Add(new Node(Convert.ToInt32(SEC_InfoTreeView.Rows[i]["APPITEMID"]),Convert.ToString(SEC_InfoTreeView.Rows[i]["USERNAME"]), "", Convert.ToString(SEC_InfoTreeView.Rows[i]["ACAPTION"])));
}
else if (PrentID != 0 && Convert.ToInt32(SEC_InfoTreeView.Rows[i]["INDENT"]) == 14)
{
parent1.Children.Add(new Node(Convert.ToInt32(SEC_InfoTreeView.Rows[i]["APPITEMID"]),Convert.ToString(SEC_InfoTreeView.Rows[i]["USERNAME"]), "", Convert.ToString(SEC_InfoTreeView.Rows[i]["ACAPTION"])));
}
else if (PrentID != 0 && Convert.ToInt32(SEC_InfoTreeView.Rows[i]["INDENT"]) == 16)
{
parent1.Children.Add(new Node(Convert.ToInt32(SEC_InfoTreeView.Rows[i]["APPITEMID"]),Convert.ToString(SEC_InfoTreeView.Rows[i]["USERNAME"]), "", Convert.ToString(SEC_InfoTreeView.Rows[i]["ACAPTION"])));
}
}
}
}
}
catch (Exception ex)
{
}
}
class Node
{
public int Id { get; private set; }
public string Name { get; private set; }
public string Column1 { get; private set; }
public string Column2 { get; private set; }
public List<Node> Children { get; private set; }
public Node(int id, string name, string col1, string col2)
{
this.Id = id;
this.Name = name;
this.Column1 = col1;
this.Column2 = col2;
this.Children = new List<Node>();
}
}
And for bind the treeview i use this code this.treeListView1.Roots = data; Almost i try this from last 21 hrs but not get the correct treeview structure . Very thanks for your help .
Related
I have a report viewer in reportviewer.aspx. After I generated the report, I chose Excel format and click Export. I found that in backend, when I press the export button, it goes to load the data again and it make export take 20 minutes or more. I am doubting whether the export is just dumping the already generated report content or will load the functions and do the calculation once again. How can I avoid the export to do the calculation again but just dumping the already generated report?
Here is my code behind the reportviewer.aspx.
public partial class ReportViewer : CustomPage
{
private string _reportSourceFolder = ConfigurationManager.AppSettings["ReportSourceFolder"];
protected void Page_Load(object sender, EventArgs e)
{
try
{
EW_REPORTS, true); // added by HC on 2014-10-21, for permission checking
string reportFileName = Request.QueryString["ReportFileName"];
if (string.IsNullOrEmpty(reportFileName))
{
}
else
{
int? yearInt = null;
string year = Request.QueryString["Year"];
if (string.IsNullOrEmpty(year))
{
yearInt = DateTime.Now.Year;
}
else
{
try
{
yearInt = Convert.ToInt32(year);
}
catch { }
}
string reportFullPath = Path.Combine(_reportSourceFolder, reportFileName);
Telerik.Reporting.UriReportSource uriReportSource = new Telerik.Reporting.UriReportSource();
uriReportSource.Parameters.Add(new Telerik.Reporting.Parameter("lang", WebUtil.GetLanguage()));
uriReportSource.Parameters.Add(new Telerik.Reporting.Parameter("companyID", WebUtil.GetCompanyID()));
if (yearInt != null)
{
uriReportSource.Parameters.Add(new Telerik.Reporting.Parameter("year", yearInt));
}
if (
!"AuditReport.trdx".Equals(reportFileName, StringComparison.OrdinalIgnoreCase)
//"Report1.trdx".Equals(reportFileName, StringComparison.OrdinalIgnoreCase)
//|| "ESGSummaryReport.trdx".Equals(reportFileName, StringComparison.OrdinalIgnoreCase)
)
{
int? fromYear = Common.Util.TryToConvertToInt32(Request.QueryString["fromYear"]);
int? fromMonth = Common.Util.TryToConvertToInt32(Request.QueryString["fromMonth"]);
int? toYear = Common.Util.TryToConvertToInt32(Request.QueryString["toYear"]);
int? toMonth = Common.Util.TryToConvertToInt32(Request.QueryString["toMonth"]);
string indicatorIDs = Request.QueryString["indicatorIDs"];
string locationIDs = Request.QueryString["locationIDs"];
if (fromYear == null || fromMonth == null || toYear== null || toMonth == null)
{
try
{
DateTime? fiscalYearStartDate = Util.GetCorporateFiscalYearStartDate();
if (fiscalYearStartDate != null)
{
DateTime now = DateTime.Now;
DateTime startDate = new DateTime(now.Year, fiscalYearStartDate.Value.Month, 1);
if (now < startDate)
{
startDate = startDate.AddYears(-1);
}
DateTime endDate = startDate.AddYears(1).AddMilliseconds(-1d);
if (fromYear == null)
{
fromYear = startDate.Year;
}
if (fromMonth == null)
{
fromMonth = startDate.Month;
}
if (toYear == null)
{
toYear = endDate.Year;
}
if (toMonth == null)
{
toMonth = endDate.Month;
}
}
}
catch { }
}
// prevent incorrect numbers
List<int> indicatorIDsList = new List<int>(1024);
string[] indicatorIDsArr = new string[] { };
if (indicatorIDs != null)
{
indicatorIDsArr = indicatorIDs.Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
}
foreach(string indicatorID in indicatorIDsArr)
{
int? temp = Common.Util.TryToConvertToInt32(indicatorID);
if (temp != null && !indicatorIDsList.Contains(temp.Value))
{
indicatorIDsList.Add(temp.Value);
}
}
if (indicatorIDsList.Count > 0)
{
indicatorIDs = string.Join(",", indicatorIDsList);
}
else
{
indicatorIDs = "0";
}
List<int> locationIDsList = new List<int>(1024);
string[] locationIDsArr = new string[] { };
if (locationIDs != null)
{
locationIDsArr = locationIDs.Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
}
foreach (string locationID in locationIDsArr)
{
int? temp = Common.Util.TryToConvertToInt32(locationID);
if (temp != null && !locationIDsList.Contains(temp.Value))
{
locationIDsList.Add(temp.Value);
}
}
if (locationIDsList.Count > 0)
{
locationIDs = string.Join(",", locationIDsList);
}
else
{
locationIDs = "0";
}
uriReportSource.Parameters.Add(new Telerik.Reporting.Parameter("fromYear", fromYear));
uriReportSource.Parameters.Add(new Telerik.Reporting.Parameter("toYear", toYear));
uriReportSource.Parameters.Add(new Telerik.Reporting.Parameter("fromMonth", fromMonth));
uriReportSource.Parameters.Add(new Telerik.Reporting.Parameter("toMonth", toMonth));
//uriReportSource.Parameters.Add(new Telerik.Reporting.Parameter("indicatorIDs", indicatorIDs));
uriReportSource.Parameters.Add(new Telerik.Reporting.Parameter("locationIDs", locationIDs));
}
if ("AuditReport.trdx".Equals(reportFileName, StringComparison.OrdinalIgnoreCase))
{
uriReportSource.Parameters.Add(new Telerik.Reporting.Parameter("performedDateFrom", DateTime.Now.AddDays(-1d)));
uriReportSource.Parameters.Add(new Telerik.Reporting.Parameter("performedDateTo", DateTime.Now));
}
uriReportSource.Uri = reportFullPath;
if (IsPrintPreviewMode())
{
uiReportViewer.ViewMode = Telerik.ReportViewer.WebForms.ViewMode.PrintPreview;
}
uiReportViewer.ReportSource = uriReportSource;
} // end if
}
catch (Exception ex)
{
uiPanel.Alert(Convert.ToString(HttpContext.GetGlobalResourceObject("Resource", "Message_Error_Occurs")));
Logger.Log(string.Format("Error occurs in the '{0}.{1}' method.{2}{3}"
, System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.ToString()
, System.Reflection.MethodBase.GetCurrentMethod().Name
, Environment.NewLine
, ex.ToString()));
}
} // end method
private bool IsPrintPreviewMode()
{
bool val = false;
string temp = Request.QueryString["IsPrintPreviewMode"];
if (!string.IsNullOrEmpty(temp))
{
try
{
val = Convert.ToBoolean(temp);
}
catch { }
}
return val;
}
protected void uiBack_Click(object sender, EventArgs e)
{
string reportFileName = Request.QueryString["ReportFileName"];
Response.Redirect(string.Format("~/ReportCriteria.aspx?ReportFileName={0}", reportFileName), false);
Context.ApplicationInstance.CompleteRequest();
}
}
I am using https://courses.cs.washington.edu/courses/cse326/07su/prj2/kruskal.html psuedocode as reference when writing my code.
Code is in C#, and my code can only generate mazes up to 11x11, anything more than than it will run, seemingly, forever (e.g. 12x11 or 12x12 won't work)
Grid Properties are just storing the dimension of the size of the maze
public class GridProperties
{
private int xLength;
private int yLength;
public GridProperties(int xlength, int ylength)
{
xLength = xlength;
yLength = ylength;
}
public int getXLength()
{
return this.xLength;
}
public int getYLength()
{
return this.yLength;
}
}
Cell Properties generates the grid
public class CellProperties
{
private GridProperties Grid;
private bool topWall, bottomWall, rightWall, leftWall;
private int? xCoord, yCoord;
private CellProperties topCell, bottomCell, rightCell, leftCell;
private CellProperties topParentCell, bottomParentCell, rightParentCell, leftParentCell;
private HashSet<String> passageID = new HashSet<String>();
public CellProperties(GridProperties grid = null, int? targetXCoord = null, int? targetYCoord = null,
CellProperties tpCell = null, CellProperties bpCell = null,
CellProperties rpCell = null, CellProperties lpCell = null)
{
this.Grid = grid;
this.xCoord = targetXCoord;
this.yCoord = targetYCoord;
this.updatePassageID(this.xCoord.ToString() + this.yCoord.ToString());
this.topWall = true;
this.bottomWall = true;
this.rightWall = true;
this.leftWall = true;
this.topParentCell = tpCell;
this.bottomParentCell = bpCell;
this.rightParentCell = rpCell;
this.leftParentCell = lpCell;
this.topCell = this.setTopCell();
this.bottomCell = this.setBottomCell();
if (this.yCoord == 0)
{
this.rightCell = this.setRightCell();
}
this.leftCell = this.setLeftCell();
}
public CellProperties setTopCell()
{
if (this.Grid == null)
{
return null;
}
if (this.yCoord == this.Grid.getYLength() - 1)
{
return new CellProperties();
}
else
{
return new CellProperties(this.Grid, this.xCoord, this.yCoord + 1, null, this, null, null);
}
}
public CellProperties setBottomCell()
{
if (this.yCoord == 0)
{
return new CellProperties();
}
else
{
return this.bottomParentCell;
}
}
public CellProperties setRightCell()
{
if (this.Grid == null)
{
return null;
}
if (this.xCoord == this.Grid.getXLength() - 1)
{
return new CellProperties();
}
else
{
return new CellProperties(this.Grid, this.xCoord + 1, this.yCoord, null, null, null, this);
}
}
public CellProperties setLeftCell( )
{
if (this.xCoord == 0)
{
return new CellProperties();
}
else
{
if (this.Grid == null)
{
return null;
}
if (this.yCoord == 0)
{
return this.leftParentCell;
}
else
{
CellProperties buffer = this.bottomCell;
for (int depth = 0; depth < this.yCoord - 1; depth++)
{
buffer = buffer.bottomParentCell;
}
buffer = buffer.leftParentCell.topCell;
for (int depth = 0; depth < this.yCoord - 1; depth++)
{
buffer = buffer.topCell;
}
buffer.rightCell = this;
return buffer;
}
}
}
public GridProperties getGrid()
{
return this.Grid;
}
public CellProperties getBottomCell()
{
return this.bottomCell;
}
public CellProperties getTopCell()
{
return this.topCell;
}
public CellProperties getLeftCell()
{
return this.leftCell;
}
public CellProperties getRightCell()
{
return this.rightCell;
}
public void setBottomWall(Boolean newBottomWall)
{
this.bottomWall = newBottomWall;
}
public void setTopWall(Boolean newTopWall)
{
this.topWall = newTopWall;
}
public void setLeftWall(Boolean newLeftWall)
{
this.leftWall = newLeftWall;
}
public void setRightWall(Boolean newRightWall)
{
this.rightWall = newRightWall;
}
public Boolean getBottomWall()
{
return this.bottomWall;
}
public Boolean getTopWall()
{
return this.topWall;
}
public Boolean getLeftWall()
{
return this.leftWall;
}
public Boolean getRightWall()
{
return this.rightWall;
}
public void updatePassageID(String newPassageID)
{
this.passageID.Add(newPassageID);
}
public void setPassageID(HashSet<String> newPassageID)
{
this.passageID = new HashSet<string>(newPassageID);
}
public HashSet<String> getPassageID()
{
return this.passageID;
}
}
This class is where the magic happens ... or suppose to happen.
public class KruskalMazeGenerator
{
private CellProperties Cell0x0;
private CellProperties CurrentCell;
private CellProperties NeighbourCell;
private int WallsDown;
private int TotalNumberOfCells;
private Random rnd = new Random();
private int rndXCoord, rndYCoord;
private String rndSide;
public KruskalMazeGenerator(CellProperties cell0x0)
{
Cell0x0 = cell0x0;
WallsDown = 0;
TotalNumberOfCells = Cell0x0.getGrid().getXLength() * Cell0x0.getGrid().getYLength();
}
public void selectRandomCellCoords()
{
this.rndXCoord = rnd.Next(0, this.Cell0x0.getGrid().getXLength());
this.rndYCoord = rnd.Next(0, this.Cell0x0.getGrid().getYLength());
}
public void selectRandomSide(String[] possibleSides)
{
if (possibleSides.Length != 0)
{
this.rndSide = possibleSides[rnd.Next(0, possibleSides.Length)];
}
}
public void selectRandomCurrentCell()
{
this.selectRandomCellCoords();
this.CurrentCell = this.Cell0x0;
for (int xWalk = 0; xWalk < this.rndXCoord; xWalk++)
{
this.CurrentCell = this.CurrentCell.getRightCell();
}
for (int xWalk = 0; xWalk < this.rndYCoord; xWalk++)
{
this.CurrentCell = this.CurrentCell.getTopCell();
}
}
public CellProperties checkWallBetweenCurrentAndNeighbour(List<String> possibleSides)
{
if (this.rndSide == "top")
{
if (this.CurrentCell.getTopCell() == null || this.CurrentCell.getTopCell().getGrid() == null)
{
possibleSides.Remove("top");
this.selectRandomSide(possibleSides.ToArray());
return this.checkWallBetweenCurrentAndNeighbour(possibleSides);
}
return this.CurrentCell.getTopCell();
}
else if (this.rndSide == "bottom")
{
if (this.CurrentCell.getBottomCell() == null || this.CurrentCell.getBottomCell().getGrid() == null)
{
possibleSides.Remove("bottom");
this.selectRandomSide(possibleSides.ToArray());
return this.checkWallBetweenCurrentAndNeighbour(possibleSides);
}
return this.CurrentCell.getBottomCell();
}
else if (this.rndSide == "left")
{
if (this.CurrentCell.getLeftCell() == null || this.CurrentCell.getLeftCell().getGrid() == null)
{
possibleSides.Remove("left");
this.selectRandomSide(possibleSides.ToArray());
return this.checkWallBetweenCurrentAndNeighbour(possibleSides);
}
return this.CurrentCell.getLeftCell();
}
else if (this.rndSide == "right")
{
if (this.CurrentCell.getRightCell() == null || this.CurrentCell.getRightCell().getGrid() == null)
{
possibleSides.Remove("right");
this.selectRandomSide(possibleSides.ToArray());
return this.checkWallBetweenCurrentAndNeighbour(possibleSides);
}
return this.CurrentCell.getRightCell();
}
return null;
}
public void selectRandomNeigbhourCell()
{
this.selectRandomSide(new String[4] { "top", "bottom", "left", "right" });
this.NeighbourCell = this.checkWallBetweenCurrentAndNeighbour(new List<String>(new String[4] { "top", "bottom", "left", "right" }));
}
public void checkForDifferentPassageID()
{
if (!this.CurrentCell.getPassageID().SetEquals(this.NeighbourCell.getPassageID()))
{
if (this.rndSide == "top")
{
this.CurrentCell.setTopWall(false);
this.NeighbourCell.setBottomWall(false);
this.unionAndResetPassageID();
this.WallsDown += 1;
}
else if (this.rndSide == "bottom")
{
this.CurrentCell.setBottomWall(false);
this.NeighbourCell.setTopWall(false);
this.unionAndResetPassageID();
this.WallsDown += 1;
}
else if (this.rndSide == "left")
{
this.CurrentCell.setLeftWall(false);
this.NeighbourCell.setRightWall(false);
this.unionAndResetPassageID();
this.WallsDown += 1;
}
else if (this.rndSide == "right")
{
this.CurrentCell.setRightWall(false);
this.NeighbourCell.setLeftWall(false);
this.unionAndResetPassageID();
this.WallsDown += 1;
}
}
}
public void unionAndResetPassageID()
{
HashSet<String> oldCurrentPassageID = new HashSet<String>(this.CurrentCell.getPassageID());
HashSet<String> oldNeighbourPassageID = new HashSet<String>(this.NeighbourCell.getPassageID());
HashSet <String> newPassageID = new HashSet<String>();
newPassageID = this.CurrentCell.getPassageID();
newPassageID.UnionWith(this.NeighbourCell.getPassageID());
CellProperties xwalkCell = new CellProperties();
CellProperties ywalkCell = new CellProperties();
for (int xWalk = 0; xWalk < this.Cell0x0.getGrid().getXLength(); xWalk++)
{
xwalkCell = xWalk == 0 ? this.Cell0x0 : xwalkCell.getRightCell();
for (int yWalk = 0; yWalk < this.Cell0x0.getGrid().getYLength(); yWalk++)
{
xwalkCell.setBottomWall(xWalk == 0 && yWalk == 0 ? false : xwalkCell.getBottomWall());
xwalkCell.setBottomWall(xWalk == this.Cell0x0.getGrid().getXLength() - 1 && yWalk == this.Cell0x0.getGrid().getYLength() - 1 ? false : xwalkCell.getBottomWall());
ywalkCell = yWalk == 0 ? xwalkCell : ywalkCell.getTopCell();
if (ywalkCell.getPassageID().SetEquals(oldCurrentPassageID) ||
ywalkCell.getPassageID().SetEquals(oldNeighbourPassageID))
{
ywalkCell.setPassageID(newPassageID);
}
}
}
}
public CellProperties createMaze()
{
while (this.WallsDown < this.TotalNumberOfCells - 1)
{
this.selectRandomCurrentCell();
this.selectRandomNeigbhourCell();
if (this.NeighbourCell != null)
{
this.checkForDifferentPassageID();
}
}
return this.Cell0x0;
}
}
then this is my visual representation class
public class drawGrid : CellProperties
{
private CellProperties Cell0x0 = new CellProperties();
private CellProperties yWalkBuffer = new CellProperties();
private CellProperties xWalkBuffer = new CellProperties();
private String bottomWall = "";
private String topWall = "";
private String leftAndrightWalls = "";
public drawGrid(CellProperties cell0x0)
{
Cell0x0 = cell0x0;
}
private void WallDrawingReset()
{
this.bottomWall = "\n";
this.topWall = "\n";
this.leftAndrightWalls = "\n";
}
private void Draw()
{
// draw bottom wall
{
if (this.bottomWall == "\n")
{
Console.Write("");
}
else
{
Console.Write(this.bottomWall);
}
}
Console.Write(this.leftAndrightWalls);
// draw top wall
{
if (topWall == "\n")
{
Console.Write("");
}
else
{
Console.Write(this.topWall);
}
}
}
public void yWalk()
{
for (int yWalk = 0; yWalk < this.Cell0x0.getGrid().getYLength(); yWalk++)
{
this.yWalkBuffer = yWalk == 0 ? this.Cell0x0 : this.yWalkBuffer.getTopCell();
this.WallDrawingReset();
this.xWalk(yWalk);
this.Draw();
}
}
private void xWalk(int yWalk)
{
for (int xWalk = 0; xWalk < this.Cell0x0.getGrid().getXLength(); xWalk++)
{
this.xWalkBuffer = xWalk == 0 ? this.yWalkBuffer : this.xWalkBuffer.getRightCell();
if (yWalk == 0)
{
this.bottomWall = xWalkBuffer.getBottomWall() ? this.bottomWall + "----" : this.bottomWall + " ";
this.topWall = xWalkBuffer.getTopWall() ? this.topWall + "----" : this.topWall + " ";
}
else
{
this.topWall = this.xWalkBuffer.getTopWall() ? this.topWall + "----" : this.topWall + " ";
}
if (xWalk == 0)
{
leftAndrightWalls = this.xWalkBuffer.getLeftWall() ? this.leftAndrightWalls + "| " : this.leftAndrightWalls + " ";
leftAndrightWalls = this.xWalkBuffer.getRightWall() ? this.leftAndrightWalls + "| " : this.leftAndrightWalls + " ";
}
else
{
leftAndrightWalls = this.xWalkBuffer.getRightWall() ? this.leftAndrightWalls + "| " : this.leftAndrightWalls + " ";
}
}
}
}
this is how i call them
class Program
{
static void Main(string[] args)
{
{
CellProperties cell = new CellProperties(new GridProperties(12, 11), 0, 0, null, null, null, null);
drawGrid draw = new drawGrid(cell);
draw.yWalk();
KruskalMazeGenerator kmaze = new KruskalMazeGenerator(cell);
cell = kmaze.createMaze();
Console.WriteLine("Final");
draw = new drawGrid(cell);
draw.yWalk();
}
Console.ReadKey();
}
}
Since I got you guys here, please don't mind pitching in what I can improve on as in coding style and other things that you are displeased with.
Thanks in advance.
Error seems to be here:
this.updatePassageID(this.xCoord.ToString() + this.yCoord.ToString());
Image those two scenarios:
xCoord = 1 and yCoord = 11.
xCoord = 11 and yCoord = 1.
both those result in newPassageID of 111.
So simply change the line to
this.updatePassageID(this.xCoord.ToString() + "|" + this.yCoord.ToString());
or written more sexy:
this.updatePassageID($"{xCoord}|{yCoord}");
With this you will receive
1|11 for the first scenario and 11|1 for the second which differs.
Edit based on comments:
I saw that your code is looping endlessly in the method createMaze. This method calls a method called checkForDifferentPassageID in there you check if two collections are equal or not. Once I saw that those collections are of type HashSet<string>, I thought that maybe your strings you put into the HashSet arent as unique as you think they are and there we go. So overall it took me like 10 minutes.
is there any way to simplify this code into a few lines, I have a class with string seq(number) has {get;set} functions. I am getting lucio and textValue from another class.
public static void setCategorySeq(string lucio, string textValue)
{
if (lucio == "0") { seq0 = textValue; }
else if (lucio == "1") { seq1 = textValue; }
else if (lucio == "2") { seq2 = textValue; }
else if (lucio == "3") { seq3 = textValue; }
else if (lucio == "4") { seq4 = textValue; }
else if (lucio == "5") { seq5 = textValue; }
else if (lucio == "6") { seq6 = textValue; }
else if (lucio == "7") { seq7 = textValue; }
else if (lucio == "8") { seq8 = textValue; }
else if (lucio == "9") { seq9 = textValue; }
else if (lucio == "10") { seq10 = textValue; }
else if (lucio == "11") { seq11 = textValue; }
else if (lucio == "12") { seq12 = textValue; }
else if (lucio == "13") { seq13 = textValue; }
else if (lucio == "14") { seq14 = textValue; }
else if (lucio == "15") { seq15 = textValue; }
}
May be this could help you reducing the LOC.
public static void setCategorySeq(string lucio, string textValue)
{
string[] seq = new string[16];
for (int i = 0; i <= 15; i++)
{
if (lucio == i.ToString())
seq[i] = textValue;
}
}
Maybe this code will suit you:
static Dictionary<string, string> seq = new Dictionary<string, string>();
public static void setCategorySeq(string lucio, string textValue)
{
seq[lucio] = textValue;
}
public static string setCategorySeq(string lucio)
{
if (seq.ContainsKey(lucio))
return seq[lucio];
return null;
}
Just use a dictionary
var lookup = new Dictionary<string,string>();
then to set an entry in the dictionary
lookup[lucio] = textValue;
and to access it
Console.WriteLine(lookup[lucio])
if you really want to verify that the string is a value between 0 an 15 then parse it first and validate it and use a dictionary with integer as a key
var lookup = new Dictionary<int,string>();
// Using C# 7 notation
if(int.TryParse(lucio, var out lucioInt) && lucionInt > 0 && lucioInt < 16){
lookup[lucioInt] = textValue;
}
I hope this might help
public static void setCategorySeq(string lucio, string textValue)
{
var seq = new string[15];
int noOfsequence=15;
for(int i=0;i<noOfsequence;i++)
{
if(lucio==i.ToString())
{
seq[i] = textValue;
break;
}
}
}
I have an input stream something like this:
John
Peter
Vanesa
Vanesa.New
Josh
Josh.New
Josh.New.Under
...
I need to Add Nodes to TreeView Someting like this:
+Customers
+John
+Peter
+Vanesa
+New
+Josh
+New
+Under
...
I have an idea to split every string with parameter '.', but i have a problem with dynamicly loaded nodes. Maybe i have to use some kind of foreach...
I have old database table "group" with records id and GroupName. The are filled with these strings. I need to create some kind of "address" like: John.Element or Vanesa.New.Element or Josh.New.Under.Element, where Element is record from other datatable. The DB connection is not the problem, the problem is the dynamicly fill the tree
For now i have done adding strings that don't contains '.':
reader = readGroups.ExecuteNonQuery();
while(reader.Read())
{
string[] buff = reader.GetValue(1).ToString().Split('.');
if (buff.Length == 1)
{
treeView1.Nodes[0].Nodes.Add(reader.GetValue(1));
}
else
{
//group contains '.'
}
}
EDIT:
I have one more problem. There is records like this: John, John.New, John.Old, John.Older, John.Oldest ... So when the AddNodes() method runs, the foreach in the end of the method clears John.New, John.Old, John.Older nodes, but they got to go into the treenode John. If you have some idea...
For winforms this is what you will need. I'm using recursion to add each child node inside each parent node. And I've made changes so that it will create a list of unique nodes before it starts adding any to the actual treeview
internal class TreeNodeHierachy
{
public int Level { get; set; }
public TreeNode Node { get; set; }
public Guid Id { get; set; }
public Guid ParentId { get; set; }
public string RootText { get; set; }
}
private List<TreeNodeHierachy> overAllNodeList;
private void AddNodes(IEnumerable<string> data)
{
overAllNodeList = new List<TreeNodeHierachy>();
foreach (var item in data)
{
var nodeList = new List<TreeNodeHierachy>();
var split = item.Split('.');
for (var i = 0; i < split.Count(); i++)
{
var guid = Guid.NewGuid();
var parent = i == 0 ? null : nodeList.First(n => n.Level == i - 1);
var root = i == 0 ? null : nodeList.First(n => n.Level == 0);
nodeList.Add(new TreeNodeHierachy
{
Level = i,
Node = new TreeNode(split[i]) { Tag = guid },
Id = guid,
ParentId = parent != null ? parent.Id : Guid.Empty,
RootText = root != null ? root.RootText : split[i]
});
}
// figure out dups here
if (!overAllNodeList.Any())
{
overAllNodeList.AddRange(nodeList);
}
else
{
nodeList = nodeList.OrderBy(x => x.Level).ToList();
for (var i = 0; i < nodeList.Count; i++)
{
var existingNode = overAllNodeList.FirstOrDefault(
n => n.Node.Text == nodeList[i].Node.Text && n.Level == nodeList[i].Level && n.RootText == nodeList[i].RootText);
if (existingNode != null && (i + 1) < nodeList.Count)
{
nodeList[i + 1].ParentId = existingNode.Id;
}
else
{
overAllNodeList.Add(nodeList[i]);
}
}
}
}
foreach (var treeNodeHierachy in overAllNodeList.Where(x => x.Level == 0))
{
treeView1.Nodes.Add(AddChildNodes(treeNodeHierachy));
}
}
private TreeNode AddChildNodes(TreeNodeHierachy node)
{
var treeNode = node.Node;
foreach (var treeNodeHierachy in overAllNodeList.Where(n => n.ParentId == node.Id))
{
treeNode.Nodes.Add(AddChildNodes(treeNodeHierachy));
}
return treeNode;
}
/// <summary>
/// Handles the Click event of the button1 control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
private void button1_Click(object sender, EventArgs e)
{
//SearchActiveDirectoryWithCriteria("(mailnickname=TM418)");
var test = new List<string>
{
"John",
"Peter",
"Vanesa",
"Vanesa.New",
"Josh",
"Josh.New",
"Josh.New.Under",
"Josh.Old"
};
AddNodes(test);
}
This will probably do mainly what you want, you'll also need some xaml with a TreeView called treeView:
public TreeViewItem root;
public MainWindow()
{
InitializeComponent();
root = new TreeViewItem
{
Header = "Customers"
};
treeView.Items.Add(root);
addNode("John");
addNode("Peter");
addNode("Vanesa.New");
addNode("Josh");
addNode("Josh.New");
addNode("Josh.New.Under");
}
private void addNode(string values)
{
var n = root;
foreach (var val in values.Split('.'))
{
var isNew = true;
foreach (var existingNode in n.Items)
{
if (((TreeViewItem)existingNode).Header.ToString() == val)
{
n = (TreeViewItem)existingNode;
isNew = false;
}
}
if (isNew)
{
var newNode = new TreeViewItem
{
Header = val
};
n.Items.Add(newNode);
n = newNode;
}
}
}
I had the same problem. i solved that in this way:
defining a class that implement a tree:
class TreeBuilder
{
public int index,depth;
public string text;
public Dictionary<string,TreeBuilder> childs;
public void addToTreeVeiw(System.Windows.Forms.TreeNode root, TreeBuilder tb) {
foreach (string key in tb.childs.Keys) {
System.Windows.Forms.TreeNode t = root.Nodes.Add(tb.childs[key].text);
addToTreeVeiw(t, tb.childs[key]);
}
}
}
and the main part:
string[] lis = {"a","b","a.a","a.ab","c","cc.a","a.b.dd","samad.hah.hoh"};
treeView1.Nodes.Clear();
TreeBuilder Troot = new TreeBuilder();
TreeBuilder son;
Troot.depth = 0;
Troot.index = 0;
Troot.text = "root";
Troot.childs = new Dictionary<string, TreeBuilder>();
foreach (string str in lis)
{
string[] seperated = str.Split('.');
son = Troot;
int index= 0;
for (int depth = 0; depth < seperated.Length; depth++)
{
if (son.childs.ContainsKey(seperated[depth]))
{
son = son.childs[seperated[depth]];
}
else {
son.childs.Add(seperated[depth],new TreeBuilder());
son = son.childs[seperated[depth]];
son.index= ++index;
son.depth = depth+1;
son.text = seperated[depth];
son.childs = new Dictionary<string, TreeBuilder>();
}
}
}
treeView1.Nodes.Add("root");
Troot.addToTreeVeiw(treeView1.Nodes[0], Troot);
I guess result is what you want:
Re #charles380 solution:
I have updated the code to work with WPF .Net Core tree view.
public class TreeNodeHierarchy
{
public int Level { get; set; }
public TreeViewItem Node { get; set; }
public Guid Id { get; set; }
public Guid ParentId { get; set; }
public string RootText { get; set; }
}
public class TreeManager{
public List<TreeNodeHierarchy> overAllNodeList;
public void AddNodes(IEnumerable<string> data, ref TreeView treeView1)
{
overAllNodeList = new List<TreeNodeHierarchy>();
foreach (var item in data)
{
//\test
var nodeList = new List<TreeNodeHierarchy>();
var split = item.Split('.', StringSplitOptions.RemoveEmptyEntries);
for (var i = 0; i < split.Count(); i++)
{
var guid = Guid.NewGuid();
var parent = i == 0 ? null : nodeList.First(n => n.Level == i - 1);
var root = i == 0 ? null : nodeList.First(n => n.Level == 0);
nodeList.Add(new TreeNodeHierarchy
{
Level = i,
Node = new TreeViewItem { Header = split[i], Tag = guid },
Id = guid,
ParentId = parent != null ? parent.Id : Guid.Empty,
RootText = root != null ? root.RootText : split[i]
});
}
// figure out dups here
if (!overAllNodeList.Any())
{
overAllNodeList.AddRange(nodeList);
}
else
{
nodeList = nodeList.OrderBy(x => x.Level).ToList();
for (var i = 0; i < nodeList.Count; i++)
{
var existingNode = overAllNodeList.FirstOrDefault(
n => n.Node.Header.ToString() == nodeList[i].Node.Header.ToString() && n.Level == nodeList[i].Level && n.RootText == nodeList[i].RootText);
if (existingNode != null && (i + 1) < nodeList.Count)
{
nodeList[i + 1].ParentId = existingNode.Id;
}
else
{
overAllNodeList.Add(nodeList[i]);
}
}
}
}
foreach (var treeNodeHierachy in overAllNodeList.Where(x => x.Level == 0))
{
treeView1.Items.Add(AddChildNodes(treeNodeHierachy));
}
}
private TreeViewItem AddChildNodes(TreeNodeHierarchy node)
{
var treeNode = node.Node;
foreach (var treeNodeHierachy in overAllNodeList.Where(n => n.ParentId == node.Id))
{
treeNode.Items.Add(AddChildNodes(treeNodeHierachy));
}
return treeNode;
}
}
}
Sample calling code:
var lstFolders= new List<string>
{
"John",
"Peter",
"Vanesa",
"Vanesa.New",
"Josh",
"Josh.New",
"Josh.New.Under",
"Josh.Old"
};
TreeManager treeManager = new TreeManager();
treeManager.AddNodes(lstFolders, ref tr);
I am binding the data grid view by using the following linq to entity framework query by using the following code..
private void EquipmentFinder_Load(object sender, EventArgs e)
{
SetupCategories();
productgridview.RowTemplate.Height = 130;
var products = from prods in axe.product1
select new
{
productid = prods.product_Id, //0
productnam = prods.product_Name, //1
productimage = prods.product_Image, //2
productprice = prods.product_Price,//3
productdescr = prods.product_Description, //4
};
productbindingsource.DataSource = products;
productgridview.DataSource = productbindingsource;
productgridview.Columns[0].Visible = false;
productgridview.Columns[4].Visible = false;
}
I have got the columns product id , product image ,product name ,product desription,product price..
i have made some of the columns are not visible for the purpose of client ..
now i want to sort the columns by clicking on the column header ....
Note: here the product.image is stored as byte of arrays in database ....
i dont know how to compare the bytes and sorting like that....
would any one pls help on this one......
many thanks...
MODIFIED CODE:
private void productgridview_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{
DataGridViewColumn newcolumn = productgridview.Columns.GetColumnCount(DataGridViewElementStates.Selected) == 1 ? productgridview.SelectedColumns[0] : null;
DataGridViewColumn oldColumn = productgridview.SortedColumn;
ListSortDirection direction;
if (oldColumn != null)
{
// Sort the same column again, reversing the SortOrder.
if (oldColumn == newcolumn &&
productgridview.SortOrder == SortOrder.Ascending)
{
direction = ListSortDirection.Descending;
}
else
{
// Sort a new column and remove the old SortGlyph.
direction = ListSortDirection.Ascending;
oldColumn.HeaderCell.SortGlyphDirection = SortOrder.None;
}
}
else
{
direction = ListSortDirection.Ascending;
}
productgridview.Sort(newcolumn, direction);
newcolumn.HeaderCell.SortGlyphDirection =
direction == ListSortDirection.Ascending ?
SortOrder.Ascending : SortOrder.Descending;
}
got An error: Argument NUll Exception Was Unhandled ..
Value cannot be null.
Parameter name: dataGridViewColumn
would any one help on this....
I have tried the following code and it works, I don't have images so I used empty column. The code is bit long because I had to implement BindingList<T> to implement sorting. You can read more about the implementation of BindingList<T> in this answer and here. You can find more about AutoPoco here.
using AutoPoco.Engine;
using AutoPoco;
using AutoPoco.DataSources;
namespace GridViewSorting
{
public partial class TestForm : Form
{
public TestForm()
{
InitializeComponent();
}
private void TestForm_Load(object sender, EventArgs e)
{
LoadGridData();
}
private void gv_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{
var newcolumn = gv.Columns[e.ColumnIndex];
var showColumn = newcolumn;
ListSortDirection direction;
var sortedColumn = gv.SortedColumn;
var sd = sortedColumn==null? SortOrder.None:sortedColumn.HeaderCell.SortGlyphDirection;
if (sortedColumn == newcolumn && sd == gv.SortOrder)
return;
if (sd == SortOrder.Descending || sd == SortOrder.None)
{
sd = SortOrder.Ascending;
direction = ListSortDirection.Ascending;
}
else
{
sd = SortOrder.Descending;
direction = ListSortDirection.Descending;
}
//now the fun begins, suppose this is image column and you want to
//sort based on product name when product image column header
//is clicked.
if (newcolumn.HeaderText == "ProductImage")//check if image column
{
newcolumn = gv.Columns["ProductName"];//sort on product names
}
gv.Sort(newcolumn, direction);
newcolumn.HeaderCell.SortGlyphDirection = SortOrder.None;
showColumn.HeaderCell.SortGlyphDirection = sd;//change sort indicator on clicked column
}
private void LoadGridData()
{
IGenerationSessionFactory factory = AutoPocoContainer.Configure(x =>
{
x.Conventions(c => { c.UseDefaultConventions(); });
x.AddFromAssemblyContainingType<SimpleProduct>();
x.Include<SimpleProduct>()
.Setup(c => c.ProductName).Use<FirstNameSource>()
.Setup(c => c.Id).Use<IntegerIdSource>()
.Setup(c => c.ProductDescription).Use<RandomStringSource>(5, 20);
});
var session = factory.CreateSession();
var r = new Random(234234);
var rn = r.Next(5, 100);
IList<SimpleProduct> products = session.List<SimpleProduct>(25)
.Impose(x => x.Price, r.Next() * rn)
.Get();
var bl = new ProductList();
foreach (var i in products)
{
bl.Add(i);
}
gv.DataSource = bl;
}
}
public class ProductList : SortableProductList<SimpleProduct>
{
protected override Comparison<SimpleProduct> GetComparer(PropertyDescriptor prop)
{
Comparison<SimpleProduct> comparer;
switch (prop.Name)
{
case "Id":
comparer = new Comparison<SimpleProduct>(delegate(SimpleProduct x, SimpleProduct y)
{
if (x != null)
if (y != null)
return (x.Id.CompareTo(y.Id));
else
return 1;
else if (y != null)
return -1;
else
return 0;
});
break;
case "ProductName":
comparer = new Comparison<SimpleProduct>(delegate(SimpleProduct x, SimpleProduct y)
{
if (x != null)
if (y != null)
return (x.ProductName.CompareTo(y.ProductName));
else
return 1;
else if (y != null)
return -1;
else
return 0;
});
break;
case "ProductDescription":
comparer = new Comparison<SimpleProduct>(delegate(SimpleProduct x, SimpleProduct y)
{
if (x != null)
if (y != null)
return (x.ProductDescription.CompareTo(y.ProductDescription));
else
return 1;
else if (y != null)
return -1;
else
return 0;
});
break;
case "Price":
comparer = new Comparison<SimpleProduct>(delegate(SimpleProduct x, SimpleProduct y)
{
if (x != null)
if (y != null)
return (x.Price.CompareTo(y.Price));
else
return 1;
else if (y != null)
return -1;
else
return 0;
});
break;
default:
comparer = new Comparison<SimpleProduct>((x, y) =>
{
if (x != null && y != null)
return x.GetHashCode().CompareTo(y.GetHashCode());
return 0;
});
break;
}
return comparer;
}
}
public abstract class SortableProductList<T> : BindingList<T>
{
protected override bool SupportsSortingCore{get{return true;}}
protected override void ApplySortCore(PropertyDescriptor prop, ListSortDirection direction)
{
if (prop.PropertyType.GetInterface("IComparable") == null)return;
var itemsList = (List<T>)this.Items;
Comparison<T> comparer = GetComparer(prop);
itemsList.Sort(comparer);
if (direction == ListSortDirection.Descending) itemsList.Reverse();
}
protected abstract Comparison<T> GetComparer(PropertyDescriptor prop);
}
public class SimpleProduct
{
public int Id { get; set; }
public string ProductName { get; set; }
public decimal Price { get; set; }
public string ProductImage { get; set; }
public string ProductDescription { get; set; }
}
}
You will get your thing in gv_ColumnHeaderMouseClick function.