5

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?)

Binary Worrier
  • 50,774
  • 20
  • 136
  • 184
Jack McG
  • 595
  • 2
  • 6
  • 5

3 Answers3

2

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

SearchText =  (sender as TextBox).Text;
Henrik Söderlund
  • 4,286
  • 3
  • 26
  • 26
  • @JackMcG - 9 years later I feel the same way. The problem is a bit different, but the solution is quite the same :D – Vityata Apr 09 '19 at 16:28
0

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 */
Lord of Scripts
  • 3,579
  • 5
  • 41
  • 62
0

You need to cast sender to a TextBox:

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

Hope it helps

Klaus Byskov Pedersen
  • 117,245
  • 29
  • 183
  • 222