我有一个已经绑定(bind)到数据库的数据网格。 单击按钮时如何在数据网格上显示数据?
这是我尝试过的...
private void button1_Click(object sender, RoutedEventArgs e)
{
SqlDataAdapter da = null;
DataSet ds = null;
try
{
da = new SqlDataAdapter("select * from Major", @"Data Source=Student;Initial Catalog=StudDB;Integrated Security=true;Persist Security Info=True;");
da.SelectCommand.CommandTimeout = 100000;
ds = new DataSet();
da.Fill(ds);
dataGrid1.ItemsSource = ds.Tables[0].DefaultView;
}
catch (SqlException ex)
{
throw ex;
}
}
最佳答案
这是解决方案。感谢其他回复的人!
SqlConnection con;
public MainWindow()
{
InitializeComponent();
try
{
con = new SqlConnection("Data Source=ComputerName;Initial Catalog=YourDBName;Persist Security Info=True;");
con.Open();
}
catch (Exception ex)
{
throw ex;
}
}
private void button1_Click(object sender, RoutedEventArgs e)
{
SqlDataAdapter da = null;
DataSet ds = null;
try
{
da = new SqlDataAdapter("select * from YourTableName",con);
da.SelectCommand.CommandTimeout = 100000;
ds = new DataSet();
da.Fill(ds);
dataGrid1.ItemsSource = ds.Tables[0].DefaultView;
}
catch (SqlException ex)
{
throw ex;
}
并在 Xaml 中设置 Itemsource 和 AutoGenerateColumns
<DataGrid ItemsSource="{Binding YourTableName}" AutoGenerateColumns="True" Grid.Column="1" Height="423" HorizontalAlignment="Left" Margin="22,24,0,0" Name="dataGrid1" VerticalAlignment="Top" Width="591" />
关于c# - 单击按钮时显示数据网格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13857241/