¿Como eliminar las tablas que no le pertenezcan a una base de datos en un TreeView? c# Windows Forms, Microsoft SQL Server

Resulta que tengo un TreeView que me muestra todas las bases de datos que hay con sus respectivas tablas. El problema como verán es que me aparecen tablas a las que le pertenecen a una base de datos pero que tambien les aparecen en otras, lo cual está mal.

introducir la descripción de la imagen aquí

Y lo que quiero es que me muestren nomas las tablas a las que les pertenecen la base de datos únicamente.

       TreeNode node;     TreeNode hijo;     private void Form1_Load(object sender, EventArgs e)     {         DataTable tabla = new DataTable();         DataTable tablas = new DataTable();          ReglasDeNegocios.OperacionesBD operaciones = new ReglasDeNegocios.OperacionesBD();         if (operaciones.BaseDatos(sUsuario, sPassword, ref tabla))         {               foreach (DataRow dr in tabla.Rows)             {                 node = new TreeNode(dr["name"].ToString());                 string hijos = Convert.ToString(dr["name"].ToString());                 if (operaciones.BaseDatos(sUsuario, sPassword, hijos, ref tablas))                 {                     foreach (DataRow dr2 in tablas.Rows)                     {                          hijo = new TreeNode(dr2["Tabla"].ToString());                         node.Nodes.Add(hijo);                     }                     treeView1.Nodes.Add(node);                 }              }             }         else         {              MessageBox.Show("Ocurrio un error: " + operaciones.sLastError);         }     } 

Asi mando a llamar la BaseDatos:

  public Boolean BaseDatos(String sUsuario, String sPassword, String BD, ref DataTable Tabla)     {         Boolean bAllOk = false;         using (SqlConnection conexion = new SqlConnection())         {             try             {                  conexion.ConnectionString = $  "Server=ROBERTODIAZ; User Id={sUsuario}; Password={sPassword}";                 conexion.Open();                 SqlCommand comando = new SqlCommand($  "use {BD} select sc.name+'.'+tb.name AS Tabla from sys.tables tb inner join sys.schemas sc on tb.schema_id = sc.schema_id order by Tabla ASC", conexion);                 SqlDataAdapter adapter = new SqlDataAdapter(comando);                 adapter.Fill(Tabla);                   bAllOk = true;              }             catch (Exception ex)             {                 sLastError = ex.Message;             }             finally             {                 conexion.Close();             }         }         return bAllOk;     } 

¿Como solucionarían esto?

¿Cómo crear un treeView con boostrap 4?

Hace cuatro horas estoy mirando la forma de crear esto. He encontrado varios ejemplos, pero muchos usan una versión de boostrap vieja y mi sistema está usando la versión 4.

Necesito crear como 5 niveles en una vista de árbol, estaría bueno que tuvieran iconos y enlaces ¿cuál es la forma más fácil de crear esto?. Muchos ejemplos están incompletos, no los puedo hacer andar.

Algunos enlaces que he visto:

Bootstrap Treeview

https://jonmiles.github.io/bootstrap-treeview/

https://www.creative-tim.com/product/black-dashboard?partner=114912

https://www.jqueryscript.net/other/Folding-Tree-Structures-jQuery-fileexplore.html

https://www.webslesson.info/2017/05/make-treeview-using-bootstrap-treeview-ajax-jquery-with-php.html

Treeview using Bootstrap Treeview, PHP and MySQL

Aspiro a conseguir algo similar a lo que se aprecia en esta imagen, pero con color de fondo verde y quizás sin bordes.

imagen

Les agradecería consejos de como hacer esto, por favor.

¿Autodesplazamiento vertical en TreeView con Scrollbar?

¡Buenos días!

He colocado una scrollbar en mi TreeView con tkinter y Python 3.x

¿Es posible hacer que se desplace automáticamente conforme nuevas filas se van generando en el TreeView? ¿O debería ser el TreeView el que deba desplazarse y la Scrollbar limitarse a mostrar la posición?

Os dejo la porción de código donde creo la Scrollbar. (Se que no sigo las convenciones, poco a poco, acabo de leerlas, y ya tenia mucho escrito).

        self.chat = ttk.Treeview(             frame,             height=10,             columns=("#1", "#2", "#3"),             selectmode="none",             show="headings"             )         self.chat.heading('#1', text='Hora', anchor=tk.CENTER)         self.chat.heading("#2", text="Usuario", anchor=tk.CENTER)         self.chat.heading("#3", text="Mensaje", anchor=tk.W)         self.chat.column("#1", stretch=False, width=50)         self.chat.column("#2", stretch=False, width=80)         self.chat.column("#3", stretch=False, width=400)         self.chat.grid(row=0, column=0, columnspan=2, padx=10, pady=10, sticky="nsew")          Scrollbar = ttk.Scrollbar(frame, orient=tk.VERTICAL, command=self.chat.yview)         Scrollbar.grid(row=0, column=3, sticky="nse")         self.chat.configure(yscrollcommand=Scrollbar.set) 

Os muestro una imagen de la aplicación introducir la descripción de la imagen aquí

Debería bajar, pero permanece ahí. Muchas Gracias por su ayuda.

¿Porque tengo una columna adicional con Treeview en Tkinter? Python3

¡Buenas!

Estoy creando una interfaz gráfica para una aplicación de chat (Que funciona por consola actualmente).

El problema que tengo es que al usar la función de treeview y crear 3 columnas, me aparecen 4, y una de ellas vacía (la ultima). Os dejo una captura de pantalla y el código. ¿Como podría eliminar esa “Columna vacia” de mi TreeView?

introducir la descripción de la imagen aquí

Aquí os dejo el código:

def GUI():     root = Tk()     root.title("Chat - RuDaHee")       frame = Frame(root).grid(row=0, column=0, padx=5, pady=5)      chat = ttk.Treeview(frame, height=10, columns=("#0","#1", "#2"), selectmode="extended")     chat.heading('#0', text='Hora', anchor=CENTER)     chat.heading("#1", text="Usuario", anchor=CENTER)     chat.heading("#2", text="Mensaje", anchor=W)     chat.column("#0", stretch=NO, width=80)     chat.column("#1", stretch=NO, width=80)     chat.column("#2", stretch=NO, width=380)      chat.grid(row=0, column=0, columnspan=2, padx=10, pady=10, sticky="nsew")       escribirMensaje = Entry(frame, width=87).grid(row=1, column=0, sticky="w", padx=10, pady=10)     enviarMensaje = Button(frame, text="Enviar").grid(row=1, column=1, sticky="e", padx=10, pady=10)     root.mainloop()   GUI() 

Unsubscribe from AfterCheck in Custom TreeView

I’m creating a custom TreeView in C# inherited from a regular Forms.TreeView, and I need the checkbox to change when clicking the text of the node. That is done. However, the triggered AfterCheck event, sends it’s EventArgs Action as unknown instead as by Mouse.

To solve this. I tried to change the Node, then create a new TreeViewEventArgs with the correct TreeViewAction, and firing AfterCheck.

#region Override OnNodeMouseClick         /// <summary> Allows the node to change when it's name is clicked </summary>         /// <param name="e"></param>         protected override void OnNodeMouseClick(TreeNodeMouseClickEventArgs e)         {             base.OnNodeMouseClick(e);              #region Get in which pixel the name begins             TreeNode node = e.Node; //Stores the node             int i = 0;              //Counter of how many parent nodes the node has              #region Counts how many parent nodes the clicked node has             while(node.Parent != null)             { node = node.Parent; i++; }             #endregion              int margin = 40 + 20 * i; //Defines the pixel on which the name in the node starts             #endregion              if (e.X >= margin)             {                 e.Node.Checked = !e.Node.Checked; //Changes th                 MouseClickEventArgs = new TreeViewEventArgs(e.Node, TreeViewAction.ByMouse);                  OnAfterCheck(MouseClickEventArgs);             }         }         #endregion 

However, this obviously causes the event to fire twice. Once with an unknown action and another with a ByMouse action.

The differentiation between the type of Action is needed for another part of the code and also is the reason the event shouldn’t fire twice.

Thanks for your help

Выделение всей строки узла TreeView в WF C#

Помогите пожалуйста разобраться.

В общем, имею TreeView дерево узлов с подзулами. Проблема в том, что красится лишь только текст, а мне нужно покрасить всю строку (как на скрине ниже). введите сюда описание изображения

Например, я выбираю узел TreeView и у меня вся строка красится в синий цвет. Я выбираю подузел и строка красится в желтый цвет. У самого TreeView же без выделений должны быть узлы закрашены в разные цвета (как на правой части рисунка (где надпись ПОСЛЕ)). Возможно ли это реализовать без “самотворчества”? Если нет, то что можно придумать?

p.s.: про treeView1.ShowLines = false; treeView1.FullRowSelect=true; знаю, это немножко не то. В этом случае пропадают линии иерархии слева от дерева.

Заранее, всем спасибо за помощь!

Problem with 3 or more level of tree-view UI on Mobile

I had come with a problem with review/summary screen on phone that requires the information to have 3-5 level of tree-view. Generally on mobile phone UI, nested information will be shown on another screen but because this is a review/summary screen that user will be able to review without any information hidden on another screen (user might miss it)

Any good suggestion for a design pattern for this? I find accordion gets too complicated and traditional tree view indentation limits horizontal space.

.NET Custom hierarchical expression to treeview data structure


I’m not good at English. It’s gonna be hard to read. I apologize in advance.

I need expression parser for draw diagram(fault tree). In order to do that I have to create data structure from custom expression

( (123-A1) AND (123-A2) AND (123-A3) OR (123-A4 AND (123-A5 OR 123-A6)) ) 

The above example was written roughly as I thought.

  1. In some cases, parentheses are used for each variable for readability.
  2. Read in order within the same parentheses.
  3. Read in order if there are no parentheses.
  4. Parentheses around the expression can be attached without meaning.
  5. Operators use only AND, OR parentheses use only (, ).
  6. I don’t know which is the best way string to data structure.
  7. The depth and order of parentheses and.. anything are all important because eventually I need to draw Diagram.
           _________OR___________           |                      |           |                 ____AND____           |                |           |            ______AND______         |       ___OR___    |       |       |        |      |        | 123-A1  123-A2  123-A3  123-A4  123-A5  123-A6 

Expression to Token

public class Token {     public TokenType Type;  // Operator, Parenthesis, Variable      public string Label;     public int Depth;     public int Group;      public Token(string label)     {         Label = label.Trim();          if (ExpressionParser.SupportedOperatorHashSet.Contains(label.ToUpper()))         {             Type = TokenType.Operator;         }         else if (ExpressionParser.SupportedParenthesesHashSet.Contains(label))         {             Type = TokenType.Parenthesis;         }         else         {             Type = TokenType.Variable;         }     } }  public enum TokenType {     Variable,     Operator,     Parenthesis }  public static class ExpressionParser {     private static Regex TokenRegex = new Regex(@"[\(\)]|[\d\w-]+");      internal static readonly HashSet<string> SupportedOperatorHashSet = new HashSet<string>() { AndGate, OrGate };     internal static readonly HashSet<string> SupportedParenthesesHashSet = new HashSet<string>() { OpenParenthesis, CloseParenthesis };     private static readonly List<Token> TokenList = new List<Token>();      internal const string AndGate = "AND";     internal const string OrGate = "OR";     internal const string OpenParenthesis = "(";     internal const string CloseParenthesis = ")";      public static List<Token> Parse(string expression)     {         try         {             // Get '(' ')' '123-A1' 'AND' 'OR'             MatchCollection matches = TokenRegex.Matches(expression); // @"[\(\)]|[\d\w-]+"             int depth = 0;              foreach (Match match in matches)             {                 Token token = new Token(match.Value);                 TokenList.Add(token);                  // Increase depth when token is open parenthesis                  if (token.Type == TokenType.Parenthesis && token.Label == OpenParenthesis)                 {                     depth += 1;                 }                  token.Depth = depth;                  // Set group                 if (TokenList.Count > 1)                 {                     Token prevToken = TokenList[TokenList.Count - 2];                     if (prevToken.Depth == token.Depth)                     {                         token.Group = prevToken.Group;                     }                     else                     {                         token.Group = prevToken.Group + 1;                     }                 }                  // Decrease depth after token is close parenthesis                  if (token.Type == TokenType.Parenthesis && token.Label == CloseParenthesis)                 {                     depth -= 1;                 }             }              // Remove parenthesis  [ex. (123-ab)]             for (int i = 0; i < TokenList.Count; i++)             {                 if (i + 2 < TokenList.Count &&                     TokenList[i].Type == TokenType.Parenthesis && TokenList[i].Label == OpenParenthesis &&                     TokenList[i + 2].Type == TokenType.Parenthesis && TokenList[i].Label == CloseParenthesis)                 {                     TokenList.RemoveAt(i + 2);                     TokenList.RemoveAt(i);                 }             }              return new List<Token>(TokenList);         }         finally         {             TokenList.Clear();         }     } } 

Run

ExpressionParser.Parse("( (123-A1) AND (123-A2) AND (123-A3) OR (123-A4 AND (123-A5 OR 123-A6)) )"); 

Result

OR  ├ AND  │  ├ 123-A1  │  ├ 123-A2  │  └ 123-A3  └ AND     ├ 123-A4     └ OR       ├ 123-A5       └ 123-A6 

How to write MySQL query for TreeView or Python Hard coding

enter image description here

I want to get childern of Parent with step count not all childs with SQL query. Or how can I write algorithm for this one.

Getting all child list:::

select  id,     address,     recommendor_id from (select * from gecAccount_gecaccount      order by recommendor_id, id) gecaccount ,     (select @pv := '131') initialisation where  find_in_set(recommendor_id, @pv) > 0 and @pv := concat(@pv, ',', id); 

Не понятно поведение treeCell в treeView

Ниже немного модифицированный код из мануала Oracle https://docs.oracle.com/javafx/2/ui_controls/tree-view.htm

Суть задачи: к узлу с названием “Projects” добавить одно контекстное меню, а к узлу “Screens” другое. Меню создаются, но появляются и в неожиданных местах. Непонятно, чем это вызвано и как с этим можно бороться.

Это правильно:

введите сюда описание изображения

И это правильно:

введите сюда описание изображения

А вот здесь непонятно. Как меню “прицепилось” к некой Emma Jones? введите сюда описание изображения package sample;

import javafx.application.Application; import javafx.beans.property.SimpleStringProperty; import javafx.scene.Scene; import javafx.scene.control.*; import javafx.scene.input.KeyCode; import javafx.scene.layout.VBox; import javafx.scene.paint.Color; import javafx.stage.Stage; import javafx.util.Callback;  import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map;  public class TreeViewSample extends Application {       private enum menuType     {         PROJECTS, ONE_PROJECT,         SCREENS, ONE_SCREEN,         TAGS, ONE_TAG     }      private final String PROJECTS  = "Projects";     private final String SCREENS  = "Screens";        List<Employee> employees = Arrays.<Employee>asList(             new Employee("Ethan Williams", PROJECTS),             new Employee("Emma Jones", "Sales Department"),             new Employee("Anna Black", "Sales Department"),             new Employee("Michael Brown", "Sales Department"),              new Employee("Rodger York", SCREENS),             new Employee("Susan Collins", "Sales Department"),             new Employee("Gregory Smith", "IT Support"),             new Employee("Mike Graham", "IT Support"),             new Employee("Judy Mayer", "IT Support"),              new Employee("Jacob Smith", "Accounts Department"),             new Employee("Isabella Johnson", "Accounts Department"));     TreeItem<String> rootNode =             new TreeItem<String>("MyCompany Human Resources");       Map<menuType, ContextMenu> menuMap = new HashMap<menuType, ContextMenu>();      TreeView<String> treeView;      private void fillMenuMap()     {         menuMap.put(menuType.PROJECTS, new ContextMenu());         menuMap.put(menuType.ONE_PROJECT, new ContextMenu());         menuMap.put(menuType.SCREENS, new ContextMenu());         menuMap.put(menuType.ONE_SCREEN, new ContextMenu());         menuMap.put(menuType.TAGS, new ContextMenu());         menuMap.put(menuType.ONE_TAG, new ContextMenu());          setMenuEventHandlers();     }      private void setMenuEventHandlers()     {         // region PROJECTS         MenuItem addProjectMI= new MenuItem("Add project");         addProjectMI.setOnAction(                 t->{                     TreeItem newProject =  new TreeItem<String>("New Project");                     treeView.getSelectionModel().getSelectedItem().getChildren().add(newProject);                 }         );         menuMap.get(menuType.PROJECTS).getItems().add(addProjectMI);         // endregion PROJECTS          // region SCREENS         MenuItem addScreenMI= new MenuItem("Add screen");         addScreenMI.setOnAction(                 t->{                     TreeItem newProject =  new TreeItem<String>("New Screen");                     treeView.getSelectionModel().getSelectedItem().getChildren().add(newProject);                 }         );         menuMap.get(menuType.SCREENS).getItems().add(addScreenMI);         // endregion PROJECTS     }         public static void main(String[] args) {         Application.launch(args);     }      @Override     public void start(Stage stage) {         rootNode.setExpanded(true);         for (Employee employee : employees) {             TreeItem<String> empLeaf = new TreeItem<String>(employee.getName());             boolean found = false;             for (TreeItem<String> depNode : rootNode.getChildren()) {                 if (depNode.getValue().contentEquals(employee.getDepartment())){                     depNode.getChildren().add(empLeaf);                     found = true;                     break;                 }             }             if (!found) {                 TreeItem depNode = new TreeItem(employee.getDepartment());                 rootNode.getChildren().add(depNode);                 depNode.getChildren().add(empLeaf);             }         }          stage.setTitle("Tree View Sample");         VBox box = new VBox();         final Scene scene = new Scene(box, 400, 300);         scene.setFill(Color.LIGHTGRAY);          treeView = new TreeView<String>(rootNode);         treeView.setEditable(true);         treeView.setCellFactory(new Callback<TreeView<String>,TreeCell<String>>(){             @Override             public TreeCell<String> call(TreeView<String> p) {                 return new TextFieldTreeCellImpl();             }         });          box.getChildren().add(treeView);         stage.setScene(scene);         stage.show();     }      private final class TextFieldTreeCellImpl extends TreeCell<String> {          private TextField textField;             public TextFieldTreeCellImpl()         {             fillMenuMap();         }          @Override         public void startEdit() {             super.startEdit();              if (textField == null) {                 createTextField();             }             setText(null);             setGraphic(textField);             textField.selectAll();         }          @Override         public void cancelEdit() {             super.cancelEdit();              setText((String) getItem());             textField.setText((String) getItem());             setGraphic(getTreeItem().getGraphic());          }          @Override         public void updateItem(String item, boolean empty) {             super.updateItem(item, empty);               TreeItem  thisTreeItem = getTreeItem();              if ( thisTreeItem!=null)             {                 switch ((String)thisTreeItem.getValue() )                 {                     case PROJECTS: setContextMenu(menuMap.get(menuType.PROJECTS)); break;                     case SCREENS: setContextMenu(menuMap.get(menuType.SCREENS)); break;                 }             }              if (empty)             {                 setText(null);                 setGraphic(null);             }             else             {                 if (isEditing())                 {                     if (textField != null)                     {                         textField.setText(getString());                     }                     setText(null);                     setGraphic(textField);                 }                 else                 {                     setText(getString());                     setGraphic(getTreeItem().getGraphic());                 }             }         }          private void createTextField() {             textField = new TextField(getString());             textField.setOnKeyReleased(                     t->{                         if (t.getCode() == KeyCode.ENTER) {                             commitEdit(textField.getText());                         } else if (t.getCode() == KeyCode.ESCAPE) {                             cancelEdit();                         }                     }             );         }          private String getString() {             return getItem() == null ? "" : getItem().toString();         }     }      public static class Employee {          private final SimpleStringProperty name;         private final SimpleStringProperty department;          private Employee(String name, String department) {             this.name = new SimpleStringProperty(name);             this.department = new SimpleStringProperty(department);         }          public String getName() {             return name.get();         }          public void setName(String fName) {             name.set(fName);         }          public String getDepartment() {             return department.get();         }          public void setDepartment(String fName) {             department.set(fName);         }     } }