【问题标题】:Extract the data from a SelectedItem event from a LINQ filled DataGrid从 LINQ 填充的 DataGrid 中提取 SelectedItem 事件中的数据
【发布时间】:2018-05-13 05:22:33
【问题描述】:

我在数据库中有一个“卡片”表,其中包含“卡片”和“客户”表。 Cards 包含 CustomerID、Number 和 Ammount。之后我用ADO.NET来利用DataGridTextBox等。

我删除了 DataGridTextBox 作为搜索条件。当按下按钮时,DataGrid 会加载 LINQ:

string searchString = this.CustomerIDTextBox.Text();
using (var ctx = new bdCustomerEntities()){
    var result = from t in ctx.Cards
                 join t_customer in ctx.Customer on t.CustomerID equals t_customer.id
                 where t.CustomerID == searchString
                 select new
                 {
                     number = t.number,
                     ammount = t.ammount,
                     CustomerID = t.Customer.id
                 };
    /*Fill datagrid*/
    this.CardsDataGrid.ItemsSource = result.ToList();
}

当我在CardsDataGrid 中创建MouseDoubleClick 事件来选择行并填充两个TextBoxes 时,问题就出现了,一个是Ammount 数据,另一个是Number。

我尝试了这段代码,但无法在TextBoxes 中显示数据:

Cards selected = this.cardsDataGrid.SelectedItem as Cards;
this.numberTextBox.Text = selected.Number.ToString();
this.ammountTextBox.Text = seleccionado.Ammount.ToString();

我在Cards selected = ... 行之后创建了MessageBox.Show 以查看SelectedItem 上的内容,它显示如下:

{number = 13, ammount = 3500 , CustomerID = 1456 }

我的问题是,我无法“提取”SelectedItem,因为创建的格式可能是 LINQ? - 并将其放入TextBoxes。

当我对上述代码进行此更改时,我注意到了一点:

Cards selected = (Cards) this.cardsDataGrid.SelectedItem ;

它显示:

System.InvalidCastException:无法转换类型的对象 '[System.Int32,System.Int32,System.String]' 输入 'bdCustomer.Cards'。

【问题讨论】:

    标签: c# .net linq datagrid textbox


    【解决方案1】:

    您的 LINK 返回一个匿名类型而不是 Cards 类型,并且在匿名类型和 Cards 类型之间没有可用的转换,这就是错误告诉您的内容。

    将您的 LINQ 更改为:

    var result = from t in ctx.Cards
                 join t_customer in ctx.Customer on t.CustomerID equals t_customer.id
                 where t.CustomerID == searchString
                 select t;
    

    【讨论】:

    • 非常感谢!你是对的!我解决了这个问题。现在我可以继续这个项目了。
    【解决方案2】:

    在您的查询结果中,您返回一个匿名类型而不是 Cards 类型,这就是您收到 InvalidCastException 的原因。
    您可以从 DBSet 返回 Cards 类型:

    from t in ctx.Cards
    join t_customer in ctx.Customer on t.CustomerID equals t_customer.id
    where t.CustomerID == searchString
    select t;
    

    【讨论】:

    • 为什么我们需要创建一个新对象并为其分配与当前对象完全相同的值?只需选择当前对象本身。否则一个很好的答案。
    • 是的,我的错,我没有注意到他或她查询 Cards 表。
    • 也感谢您的帮助!我能够修复它。
    猜你喜欢
    • 2020-10-27
    • 2014-03-03
    • 2013-10-08
    • 2016-07-07
    • 1970-01-01
    • 2012-12-09
    • 1970-01-01
    • 2011-09-09
    • 1970-01-01
    相关资源
    最近更新 更多