Generally, Web controls that support data binding, such as the dorpdownlist control and checkboxlist control, all contain five attributes: datasource, datamember, datatextfield, datavaluefield, and datatextformatstring. Datasource is used to obtain the data source, that is, to obtain the set containing data. The other four attributes are used to obtain a field value in the data source. However, generally, you want to bind multiple field values in these data sources to one of the attributes, which cannot be directly implemented.
The preceding restriction is that you cannot bind multiple field values to one of the four attributes, but SQL statements do not. Therefore, the first method is to use an SQL statement to bind two or more Field Values in the source table and use the as clause to pass the as to another field, in this way, a field contains multiple field values. Since a field contains values of multiple fields, we do not need to consider the four attributes assigned to the web control. We can refer to the following statements to see the advantages of this method:
Strcmd ="Select employeeid, lastname + ',' + firstname as 'ployeename' from employees";
This method is very concise and the most direct method. However, there is a problem of low efficiency, and duplicate data may be generated. Next we will introduce another method. We can populate the source table withDatasetDataset, and then place the data of the dataset toData TableDatatable, and then create a new column for the table. The column consists of two or more fields in the source table, so that we can bind multiple field values:
DT. Columns. Add ("employeename", typeof (string), "lastname + ',' + firstname ");
The disadvantage of the latter method is the overhead of creating new columns. However, this method is clear and does not produce duplicate data. We recommend that you use this method.
To illustrate the two methods, the followingCodePut the two methods together for implementation:
// Place user code here to initialize the page String Strconn, strcmd; strconn = " Database = northwind; server = localhost; uid = sa; Pwd = 99133009; " ; // If you need to bind firstname and lastname, and use them separately, the following statement will generate duplicate data. Strcmd = " Select employeeid, firstname, lastname, lastname + ',' + firstname as 'ployeename' from employees " ; Sqldataadapter dsda = New Sqldataadapter (strcmd, strconn); dataset DS = New Dataset (); dsda. Fill (DS, " Employeelist " ); Datatable dt = Ds. Tables [ " Employeelist " ]; // Method 1 // Ddl1 is a dropdownlist control. Ddl1.datasource = DT. defaultview; ddl1.datatextfield = " Employeename " ; Ddl1.datavaluefield = " Employeeid " ; Ddl1.databind (); /* The second method is DT. columns. add ("employeename", typeod (string), "lastname + ',' + firstname"); ddl1.datatextfield = "employeename"; ddl1.databind ();*/