создать вид дерева без использования контроллера вида дерева - PullRequest
1 голос
/ 11 апреля 2019

Я хочу отобразить древовидное представление из базы данных.Я сделал с помощью контроллера TreeView asp.net.Но я не могу позволить себе контроллер TreeView в моем проекте.Поэтому я пытаюсь создать древовидное представление динамически.

Код

  using (SqlConnection Conn = new SqlConnection(connection))
                {
                    string State = "Select * from IN_State";
                    string City = "Select * from IN_City";

                    string Treeview = State + ";" + City;

                    DataSet ds = new DataSet();
                    SqlDataAdapter da = new SqlDataAdapter(Treeview, Conn);
                    da.Fill(ds);
                    ds.Tables[0].TableName = "IN_State";
                    ds.Tables[1].TableName = "IN_City";

                    DataRelation dr = new DataRelation("StateCity", ds.Tables["IN_State"].Columns["S_Id"], ds.Tables["IN_City"].Columns["S_Id"]);
                    ds.Relations.Add(dr);

                    foreach (DataRow drState in ds.Tables["IN_State"].Rows)
                    {
                        TreeNode NDState = new TreeNode();
                        NDState.Text = drState["S_Name"].ToString();
                        NDState.Value = drState["S_Id"].ToString();
                        tview.Nodes.Add(NDState);

                        foreach (DataRow drCity in drState.GetChildRows("StateCity"))
                        {
                            TreeNode NDCity = new TreeNode();
                            NDCity.Text = drCity["C_Name"].ToString();
                            NDCity.Value = drCity["C_Id"].ToString();
                            NDState.ChildNodes.Add(NDCity);
                        }
                    }
                }

Также пробовал использовать System.Web.UI.WebControls.TreeView

Ответы [ 2 ]

1 голос
/ 15 апреля 2019

Я думаю, вы ищете конструктор TreeView

<%@ Page Language="C#" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">

  void Page_Load(Object sender, EventArgs e)
  {

    // Create a new TreeView control.
    TreeView NewTree = new TreeView();

    // Set the properties of the TreeView control.
    NewTree.ID = "BookTreeView";
    NewTree.DataSourceID = "BookXmlDataSource";

    // Create the tree node binding relationship.

    // Create the root node binding.
    TreeNodeBinding RootBinding = new TreeNodeBinding();
    RootBinding.DataMember = "Book";
    RootBinding.TextField = "Title";

    // Create the parent node binding.
    TreeNodeBinding ParentBinding = new TreeNodeBinding();
    ParentBinding.DataMember = "Chapter";
    ParentBinding.TextField = "Heading";

    // Create the leaf node binding.
    TreeNodeBinding LeafBinding = new TreeNodeBinding();
    LeafBinding.DataMember = "Section";
    LeafBinding.TextField = "Heading";

    // Add bindings to the DataBindings collection.
    NewTree.DataBindings.Add(RootBinding);
    NewTree.DataBindings.Add(ParentBinding); 
    NewTree.DataBindings.Add(LeafBinding);

    // Manually register the event handler for the SelectedNodeChanged event.
    NewTree.SelectedNodeChanged += new EventHandler(this.Node_Change);

    // Add the TreeView control to the Controls collection of the PlaceHolder control.
    ControlPlaceHolder.Controls.Add(NewTree);

  }

  void Node_Change(Object sender, EventArgs e)
  {

    // Retrieve the TreeView control from the Controls collection of the PlaceHolder control.
    TreeView LocalTree = (TreeView)ControlPlaceHolder.FindControl("BookTreeView");

    // Display the selected node.
    Message.Text = "You selected: " + LocalTree.SelectedNode.Text;

  }

</script>

<html xmlns="http://www.w3.org/1999/xhtml" >
  <head runat="server">
    <title>States</title>
</head>
<body>
    <form id="form1" runat="server">

      <h3>TreeView Constructor Example</h3>

      <asp:PlaceHolder id="ControlPlaceHolder" runat="server">
      </asp:PlaceHolder>

      <asp:XmlDataSource id="BookXmlDataSource"  
        DataFile="Book.xml"
        runat="server">
      </asp:XmlDataSource>

      <br /><br />

      <asp:Label id="Message" runat="server"/>

    </form>
  </body>
</html>

см. Также https://docs.microsoft.com/en-us/dotnet/api/system.web.ui.webcontrols.treeview.-ctor?view=netframework-4.7.2

1 голос
/ 11 апреля 2019

Создать простую структуру объекта. Список государств, например. Сам класс State, содержащий свойства State и список объектов города.

Затем используйте его с веб-компонентом, отображающим список для каждого элемента списка, внутренний подробный список. Вы можете найти его или создать самостоятельно, поскольку ваша иерархия имеет только один уровень.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...