wpf displays the data from the table to the datagrid example

  • 2020-06-12 10:30:20
  • OfStack

a. Drag an datagrid into the.xaml file and add the column name, using Binding="{column name} in the Binding database ", as follows:


<DataGrid AutoGenerateColumns="False" Height="438"HorizontalAlignment="Left" Margin="23,278,0,0" Name="dataGrid1"  VerticalAlignment="Top" Width="1249">            
    <DataGrid.Columns>                
    <DataGridTextColumn Width="100" FontSize="15" Header=" Serial number " Binding="{Binding id}"/>                           
    <DataGridTextColumn Width="140" Header=" The name of the " FontSize="15"  Binding="{Binding name}"/>                
     </DataGrid.Columns>        
</DataGrid>

b. First query the data to display and put it into datatable


public DataTable Show() 
{            
DataTable dt = new DataTable();            
try            
{
if (DBHelper.connection.State == ConnectionState.Closed)                    
DBHelper.connection.Open();                
string sql = " The query ";                
DataSet ds = new DataSet();                
SqlDataAdapter sda = new SqlDataAdapter(sql,DBHelper.connection);                
sda.Fill(ds, " Virtual table name ");                
dt= ds.Tables[" Virtual table name "];            
}            
catch (Exception ex)            
{                
MessageBox.Show(ex.Message);            
}            
return dt;        
}
// Note: The virtual table name in this method is 1 Table names defined by themselves 
c. Then in the background code edit area will datatable Data in datagrid The binding   
dataGrid1.ItemsSource = Show().DefaultView;


Related articles: