帮助错误“'对象'不包含'文本'的定义”

时间:2010-01-20 12:15:05

标签: c# linq-to-sql event-handling

问题在于:

这适用于使用C#和LINQ to SQL的WPF应用程序。

当用户想要查看客户列表时,他/她开始在文本框中输入名称。 textchanged事件使用输入文本来定义过滤列表的LINQ语句的where子句。

我目前有两个这样的文本框,它们运行的​​代码基本相同,但是我无法将代码减少到单个函数 - 我将在更多地方使用客户列表。

以下是一些代码:

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

                           };

粗体斜体线是问题所在。我无法弄清楚如何获取发送器的文本值以在StartsWith函数中使用。错误消息是:

错误1“对象”不包含“文本”的定义,也没有扩展方法“文本”接受类型为“对象”的第一个参数(您是否缺少using指令或程序集引用?)

3 个答案:

答案 0 :(得分:2)

您必须将“sender”变量强制转换为TextBox:

SearchText =  (sender as TextBox).Text;

答案 1 :(得分:0)

您需要将sender投射到TextBox

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

希望有所帮助

答案 2 :(得分:0)

事件将发件人装箱作为对象,因此除非将其转换为正确的类型,否则您不知道对象的外观。在这种情况下,它是一个TextBox控件。我在事件处理程序中的常用模式是:

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 */