【问题标题】:how to display data in data grid that is from joined tables and table 1 and two have columns with the same name如何在数据网格中显示来自连接表和表 1 和两个具有相同名称的列的数据
【发布时间】:2017-02-09 09:57:49
【问题描述】:

我有一个数据网格,我在其中显示来自已连接表的 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();
        }
    }

【问题讨论】:

  • select * 是一种不好的做法(如果您的表增长到几十列而您只需要 1 列怎么办?)。但是你应该给列取别名(select table1.foo foo1, table2.foo foo2...)
  • @KevinRaffay 您应该将其发布为答案
  • 是的,但这不是问题。或者你是在告诉我,如果我选择了 select * 我有 select table1.name ,select table2.name 它会起作用吗?
  • 这应该是因为你可以绑定到 table1.foo1 和 table2.foo2 -- 它们将是不同的列名。

标签: c# sql wpf xaml datagrid


【解决方案1】:

select * 是一种不好的做法(如果您的表增长到几十列而您只需要 1 列怎么办?)。但是你可以给列取别名(select table1.foo foo1, table2.foo foo2...)

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

【讨论】:

    猜你喜欢
    • 2012-04-27
    • 1970-01-01
    • 2012-09-21
    • 2023-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多