Help with Error “ 'object' does not contain a definition for 'Text' ”

匆匆过客 提交于 2019-12-23 15:18:27

问题


Here's the problem:

This is for a WPF app that uses C# and LINQ to SQL.

When a user wants to look at a list of customers, he/she begins entering the name in a textbox. The textchanged event uses the input text to define the where clause of a LINQ statement that filters the list.

I currently have two such text boxes that run essentially the same code, but I cannot reduce that code to a single function - I'll be using customer lists in a bunch more places.

Here's a bit of the code:

private void CustomerListFiller(object sender, TextChangedEventArgs e)

    {

        string SearchText;

        FrameworkElement feSource = e.Source as FrameworkElement;

        ***SearchText =  sender.Text;*** 

        var fillCustList = from c in dbC.Customers

                           where c.CustomerName.StartsWith(SearchText)

                           orderby c.CustomerName

                           select new

                           {

                               c.CustomerID,

                               c.CustomerName

                           };

The bold, italicized line is the problem. I can't figure out how get at the text value of the sender to use in the StartsWith function. The error message is:

Error 1 'object' does not contain a definition for 'Text' and no extension method 'Text' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?)


回答1:


You have to cast the "sender" variable to TextBox:

SearchText =  (sender as TextBox).Text;



回答2:


You need to cast sender to a TextBox:

var textBox = sender as TextBox;
SearchText = textBox.Text;

Hope it helps




回答3:


The events get the sender boxed as an object and as such you don't know what the object looks like unless you cast it to the proper type. In this case it is a TextBox control. My usual pattern in event handlers is this:

TextBox tb = sender as TextBox;
tb.Enabled = false;    /* Prevent new triggers while you are processing it (usually) */
string searchText = tb.Text; /* or why not, use tb.Text directly */
   :
tb.Enabled = true; /* just prior to exiting the event handler */


来源:https://stackoverflow.com/questions/2101203/help-with-error-object-does-not-contain-a-definition-for-text

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!