如何在数据网格中显示来自连接表和表1的数据,以及两个具有相同名称的列

时间:2016-09-30 18:35:59

标签: c# sql wpf xaml datagrid

我有一个datagrid,我从已连接表的itemsource显示我的数据。 如何在数据网格中为具有相同名称的字段创建列? 我尝试了类似Binding =“{Binding table1.name}”和Binding =“{Binding table2.name}”的内容,但它显示为空白。 这是我的代码的标题: XAML:

 <DataGrid x:Name="dataGrid" HorizontalAlignment="Left" VerticalAlignment="Top" Height="227" Width="1102" Margin="0,202,0,0" 
           ItemsSource="{Binding DataSource}" AutoGenerateColumns="False" IsReadOnly="True">
        <DataGrid.Columns>
            <DataGridTextColumn Header="Name1" Binding="{Binding table1.name}" Width="300" />
            <DataGridTextColumn Header="Name2" Binding="{Binding table2.name}" Width="300"/>                
        </DataGrid.Columns>
    </DataGrid>

我的代码背后:

public void ocitajTabelu()
    {
        using (SqlConnection sc = new SqlConnection(ConString))
        {
            sc.Open();
            string query = "select * from table1 left join table2 on table1.name_id = table2.id where table.order_id=@id";

            SqlCommand com = new SqlCommand(query, sc);
            com.Parameters.Add("@id", SqlDbType.Int).Value = Convert.ToInt32(selectedID);

            using (SqlDataAdapter adapter = new SqlDataAdapter(com))
            {
                DataTable dt = new DataTable();
                adapter.Fill(dt);
                adapter.Update(dt);
                dataGridPretragaObjekta.ItemsSource = dt.DefaultView;
            }
            sc.Close();
        }
    }

1 个答案:

答案 0 :(得分:1)

选择*是一种不好的做法(如果你的表增长到几十列并且你只需要1个怎么办?)。但你可以为列添加别名(select table1.foo foo1,table2.foo foo2 ...)

这应该有效,因为你可以绑定到table1.foo1和table2.foo2 - 它们将是不同的列名。