从ListView获取多个选定列数据的值

时间:2017-10-25 13:25:12

标签: c# sql wpf listview

我正在编写一个简单的wpf窗口,它将sql数据绑定到ListView个表。在代码上解释这个更容易,所以这是我的XAML:

<ListView Name="listViewItem" ClipToBounds="True" VerticalContentAlignment="Stretch" HorizontalContentAlignment="Stretch" SizeChanged="ListView_SizeChanged" Loaded="ListView_Loaded" TextOptions.TextHintingMode="Animated" Margin="0,0,83,0">
    <ListView.View>
        <GridView AllowsColumnReorder="False">
            <GridViewColumn Header="Company Name" Width="150">
                <GridViewColumn.CellTemplate>
                    <DataTemplate>
                        <TextBlock Text="{Binding CompanyName}" TextWrapping="Wrap" />
                    </DataTemplate>
                </GridViewColumn.CellTemplate>
            </GridViewColumn>
            <GridViewColumn Header="Company Address" Width="350">
                <GridViewColumn.CellTemplate>
                    <DataTemplate>
                        <TextBlock Text="{Binding CompanyAddress}" TextWrapping="Wrap" />
                    </DataTemplate>
                </GridViewColumn.CellTemplate>
            </GridViewColumn>
        </GridView>
    </ListView.View>
</ListView>

Companyname和CompanyAddress绑定在代码后面完成:

private void ListView_Loaded(object sender, RoutedEventArgs e)
{
    string connectionString = ConfigurationManager.ConnectionStrings["DB"].ConnectionString;
    using (SqlConnection connection = new SqlConnection(connectionString))
    {
        SqlCommand command = new SqlCommand("SELECT CompanyName, CompanyAddress FROM Groups", connection);
        SqlDataAdapter adapter = new SqlDataAdapter(command);
        DataTable dt = new DataTable("Groups");
        adapter.Fill(dt);
        listViewItem.ItemsSource = dt.DefaultView;
    }
}

我的目标是从特定的选定列中获取数据,到目前为止我已经达到了这个目标:

var selectedItem = listViewItem.SelectedItem as DataRowView;
if(selectedItem != null)
{
    string name = selectedItem["CompanyName"].ToString();
    ...
}

在mm8的帮助下。但是现在,这只允许我从一个选定的行中获取一个值。如果我想遍历所有选定的列,该怎么办?我尝试将listViewItem.SelectedItems用作DataRowView,但我无法同时指定列名和当前迭代ID。

1 个答案:

答案 0 :(得分:0)

试试这个:

foreach(var selectedItem in listViewItem.SelectedItems.OfType<DataRowView>())
{
    string name = selectedItem["CompanyName"].ToString();
}