8,734
社区成员
发帖
与我相关
我的任务
分享
<ListBox Margin="5" Name="listBox1" ItemsSource="{Binding}" SelectionChanged="listBox1_SelectionChanged">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Name}"></TextBlock>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<DataGrid Margin="5" HorizontalContentAlignment="Stretch"
Grid.Column="1" ItemsSource="{Binding Mode=OneWay}" Name="dataGrid1" Grid.RowSpan="2">
</DataGrid>
<Button Grid.Row="1" Margin="5" Content="清空" Click="Button_Click"></Button>
private void listBox1_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (listBox1.SelectedIndex > -1)
{
DeleteCurrentTable();
DataRowView dr = listBox1.SelectedItem as DataRowView;
string tableName = string.Format("[{0}]", dr["Name"].ToString()) ;
string commandString = "SELECT * FROM " +tableName;
using (connection = new SqlConnection(connectionString))
{
command = new SqlCommand(commandString, connection);
SqlDataAdapter adapter = new SqlDataAdapter();
connection.Open();
adapter.SelectCommand = command;
adapter.Fill(dataTableCurrent);
dataGrid1.DataContext = dataTableCurrent;
}
}
}
dataTableCurrent.Clear();
while (dataTableCurrent.Columns.Count > 0)
dataTableCurrent.Columns.RemoveAt(0);
private void listBox1_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (listBox1.SelectedIndex > -1)
{
dataGrid1.AutoGenerateColumns = false; //.......
dataTableCurrent.Clear();
while (dataTableCurrent.Columns.Count > 0)
dataTableCurrent.Columns.RemoveAt(0);
dataGrid1.AutoGenerateColumns = true; //如果一直为True,dataTableCurrent不能正常更新列
DataRowView dr = listBox1.SelectedItem as DataRowView;
string tableName = string.Format("[{0}]", dr["Name"].ToString()) ;
string commandString = "SELECT * FROM " +tableName;
using (connection = new SqlConnection(connectionString))
{
command = new SqlCommand(commandString, connection);
SqlDataAdapter adapter = new SqlDataAdapter();
connection.Open();
adapter.SelectCommand = command;
adapter.Fill(dataTableCurrent);
}
}
}
不知道怎么可以直接用xaml绑定就能够把数据库的各个表能够正常显示出来的方法,希望有高手能指点下。