【发布时间】: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 -- 它们将是不同的列名。