Skip to main content
 首页 » 编程设计

c#之对象引用未设置为对象的实例 (CacheRequest)(UI)

2024年02月13日14落叶无声

<分区>

您好,我正在使用这段代码来读取 datagridview 单元格。它工作正常,直到

       var myString = targetText.Cached.Name; 

目标文本为空

代码:

       LogMessage("Getting RootElement..."); 
        AutomationElement rootElement = AutomationElement.RootElement; 
        if (rootElement != null) 
        { 
            LogMessage("OK." + Environment.NewLine); 
 
            Automation.Condition condition = new PropertyCondition(AutomationElement.NameProperty, "Form1"); 
 
            LogMessage("Searching for Test Window..."); 
            AutomationElement appElement = rootElement.FindFirst(TreeScope.Children, condition); 
 
            if (appElement != null) 
            { 
                LogMessage("OK " + Environment.NewLine); 
                LogMessage("Searching for Gridview control..."); 
                AutomationElement txtElementA = GetTextElement(appElement, "dg"); 
                var rows = txtElementA.FindAll(TreeScope.Children, PropertyCondition.TrueCondition); 
                foreach (AutomationElement loginLine in rows) 
                { 
                    var loginLinesDetails = loginLine.FindAll(TreeScope.Children, new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Custom)); 
 
                    for (var i = 0; i < loginLinesDetails.Count; i++) 
                    { 
                        var cacheRequest = new CacheRequest 
                        { 
                            AutomationElementMode = AutomationElementMode.None, 
                            TreeFilter = System.Windows.Automation.Automation.RawViewCondition 
                        }; 
 
                        cacheRequest.Add(AutomationElement.NameProperty); 
                        cacheRequest.Add(AutomationElement.AutomationIdProperty); 
 
                        cacheRequest.Push(); 
 
                        var targetText = loginLinesDetails[i].FindFirst(TreeScope.Children, new PropertyCondition(AutomationElement.ClassNameProperty, "TextBlock"));// targettext is null 
 
                        cacheRequest.Pop(); 
 
                        var myString = targetText.Cached.Name;//Object reference not set ///to instance of an object error 
                    } 
 
                } 
 
            } 
            else 
            { 
                WriteLogError(); 
            } 
        } 

这是我目前正在尝试阅读的示例表单的图像。如果它适用于这个小应用程序,它肯定适用于大型应用程序。

我只想读取 datagridview 的单元格。我不知道我做的对不对,谁能帮我解决这个问题。 如果有人能帮助我,我将不胜感激