--
Code
1 // Bind all columns
2 String Connstr = @" Data Source = 192.168.1.2 \ sqlexpress; initial catalog = schoolmis1forbs; user id = sa; Password = SA1 " ;
3 Sqlconnection Conn = New Sqlconnection (connstr );
4 Sqlcommand cmd = Conn. createcommand ();
5 Cmd. commandtext = " Select top 10 * From sysobjects " ;
6 Sqldataadapter SDA = New Sqldataadapter (CMD );
7 Datatable dt = New Datatable ();
8 SDA. Fill (DT );
9 Gridview1.datasource = DT;
10 Gridview1.databind ();
11
12
13 // Bind specified column 1
14 String Columns = " , Name, ID, xtype, " ;
15 For ( Int I = 0 ; I < DT. Columns. Count; I ++ )
16 {
17 If (Columns. Contains ( " , " + DT. Columns [I]. columnname + " , " ))
18 Continue ;
19 DT. Columns. Remove (Dt. Columns [I]. columnname );
20 I = 0 ; // This sentence is crucial because DT. Columns. Count changes after removal (the loop control variable is changed), resulting in fewer cycles. Therefore, you need to reset the loop variable to restart the loop.
21 }
22 Gridview1.databind ();
23 Return ;
24
25
26 // Bind specified column 2
27 Columns = " , Name, ID, xtype, " ;
28 String [] Arr = New String [DT. Columns. Count];
29 // First, read the cycle-Dependent Factors (cycle conditions) into an array. Future operations will be based on this data.
30 For ( Int I = 0 ; I < DT. Columns. Count; I ++ )
31 {
32 Arr [I] = DT. Columns [I]. columnname;
33 }
34 // Use the data just now for Loop Control
35 For ( Int I = 0 ; I < Arr. length; I ++ )
36 {
37 If (Columns. Contains ( " , " + Arr [I] + " , " )) // When DT. columns is changed, the cycle condition is not affected.
38 Continue ; // Here, the else structure can be used instead of the continue, but the efficiency is slightly lower.
39 DT. Columns. Remove (ARR [I]);
40 }
41 gridview1.databind ();