【问题标题】:How to get all the row values corresponding to a column value without adding the DataGrid to XAML?如何在不将 DataGrid 添加到 XAML 的情况下获取与列值对应的所有行值?
【发布时间】:2018-06-23 07:22:21
【问题描述】:

我是 C# 新手。我正在尝试构建一个 WPF 应用程序,它从 Excel 工作表中获取数据并插入到DataTable 中。

窗口将有多个带有搜索按钮的文本框。单击搜索按钮时,程序应ID 列中搜索与TextBox 中的文本相等的值,然后返回所有相应的行值显示在每个特定的不可编辑的TextBox

由于我不想在 UI 中添加实际的 DataGrid,因此我只创建了一个 DataGrid 对象并加载了所有数据。在我使用here的以下代码后:

for (int i = 0; i < dataGrid.Items.Count; i++)
{
    DataGridRow row = (DataGridRow)dataGrid.ItemContainerGenerator.ContainerFromIndex(i);
    TextBlock cellContent = dataGrid.Columns[0].GetCellContent(row) as TextBlock;
    if (cellContent != null && cellContent.Text.Equals(textBox1.Text))
    {
        object item = dataGrid.Items[i];
        dataGrid.SelectedItem = item;
        dataGrid.ScrollIntoView(item);
        row.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
        break;
    }
}

但除非我将DataGrid 添加到 XAML 并填写它,否则上述代码不起作用。我发现的大多数解决方案都要求我将其添加到 XAML。想把它作为一个新问题发布。请帮助我。

PS:我已经在 VB.NET 中构建了这个应用程序(这并不难)现在我想转向 C#。

【问题讨论】:

  • 如果您根本不需要 GUI 部分,请使用 DataTableDataSet。这不需要在 XAML 中做任何事情。
  • 是的,我知道。我确实有一个 DataTable,但找不到可以执行此类任务的代码。你能帮帮我吗?
  • 您可以简单地迭代DataTable.Rows,它的类型为DataRow,就像您已经在做的那样。您可以使用DataRow.ItemArray 遍历列,它们是该行中的所有列。找到匹配项后,您已经拥有该行。
  • 你可以给它贴一个代码吗?帮助我开始。

标签: c# wpf datagrid


【解决方案1】:

假设您有一个名为myDataDataTable。这将仅在名为“ID”的列中搜索匹配项。

DataRow match = null;
foreach (DataRow row in myData.Rows)
{
    object cell = row["ID"];
    if (cell != null && cell.ToString() == textBox1.Text)
    {
        match = row;
        break;
    }
}
if (match != null)
{
    //You have found a row that contains the search text
    //Do whatever you want with it here
}
else
    //No match found

或者你可以使用 LINQ:

DataRow match = myData.AsEnumerable().FirstOrDefault(x => x["ID"] == textBox1.Text);
if (match != null)
    //Here's your row
else
    //No match found

【讨论】:

  • 谢谢。我会试一试的。
  • 它工作得很好。非常感谢 :) 但似乎它正在整个 DataGrid 中搜索(因为行)。无论如何只在“ID”列中搜索,因为它可以更快。
  • @Dante123 我的答案已更新为仅搜索“ID”列
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-11-15
  • 2011-04-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多