Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

wpf - How to remove extra column Datagrid

i have binded itemsource to Datatable for Datagrid . it shows extra columns how to remove it

My code :

<DataGrid Name="dataGrid"  IsReadOnly="True"  VerticalAlignment="Top"
          ItemsSource="{Binding Cus}" AutoGenerateColumns="True"/>

it show extra columns How to remove it ?

Screen shot : enter image description here

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Solution 1 :

Set AutoGenerateColumns="False" and Width="*" for all Columns

 <DataGrid x:Name="dataGrid" IsReadOnly="True" AutoGenerateColumns="False">
    <DataGrid.Columns>
       <DataGridTextColumn Binding="{Binding OrderId}" Header="OrderId" Width="*"/>
       <DataGridTextColumn Binding="{Binding ProductId}" Width="*" Header="ProductId"/>
       <DataGridTextColumn Binding="{Binding UnitPrice}" Width="*" Header="UnitPrice"/>
       <DataGridTextColumn Binding="{Binding Quantity}" Width="*" Header="Quantity"/>
       <DataGridTextColumn Binding="{Binding Discount}" Header="Discount"
                           Width="*"/>
    </DataGrid.Columns>
</DataGrid>

Solution 2 : You can set like this to achieve your requirement

<DataGrid HorizontalAlignment="Left" Margin="50,0,0,0" Width="500"
          Name="dataGrid"  IsReadOnly="True"  VerticalAlignment="Top"
          ItemsSource="{Binding Cus}" AutoGenerateColumns="True"/>


 this.dataGrid.AutoGeneratingColumn += dataGrid_AutoGeneratingColumn;

 void dataGrid_AutoGeneratingColumn(object sender, 
                                    DataGridAutoGeneratingColumnEventArgs e)
 {
     e.Column.Width = new DataGridLength(1, DataGridLengthUnitType.Star);
 }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...