Selectively bind the column of the datatable to the gridview

Source: Internet
Author: User
--

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 ();

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.