During the development of a page you may need to populate a number of controls from DB. In that case you have to write a number of functions to populate different controls. In this tip I am going to show you a way to do all these operations in a single function.
Step 1:
– Write the different queries for getting the data from the DB for different controls in a single string variable by separating them with semicolon.
Ex –
//Create the SQL query. string selectQueryForControlPopulation = "SELECT COL1,COL2,... FROM TABLE_NAME1 WHERE CONDITION; SELECT COL1,COL2,..FROM TABLE_NAME2 WHERE CONDITION; ......";
Step 2:
– Create the DataAdapter, DataSet object. Execute the query and fill the DataSet object.
Ex –
//Create the Connection object. OleDbConnection oConnection = new OleDbConnection(ConfigurationSettings.AppSettings["SQLConnectionString"]); //Create the Command object. OleDbCommand oCommand = new OleDbCommand(selectQueryForControlPopulation , oConnection ); //Create the DataAdapter object and set its property. OleDbDataAdapter oAdapter = new OleDbDataAdapter(); oAdapter .SelectCommand = oCommandPopulateOrganizations; // Create a DataSet object. DataSet oDataSet = new DataSet(); //Filling the DataSet object. oAdapter .Fill(oDataSet);
(**) The DataSet object contain the result of different queries as different tables. We can access those table to fill our controls.
Step 3:
Then set the datasource property of the controls to the individual table of the DataSet object as per the requirement.
Ex –
controlId1.DataSource = oDataSet.Tables[0]; controlId1.DataTextField = "COL1"; //You can set it to the desired columns controlId1.DataValueField = "COL2"; //You can set it to the desired columns controlId1.DataBind(); controlId2.DataSource = oDataSet.Tables[1]; controlId2.DataTextField = "COL1"; //You can set it to the desired columns controlId2.DataValueField = "COL2"; //You can set it to the desired columns controlId2.DataBind(); . . .
Or
You can set the DataMember property of the control to the respective table name.
Ex –
controlId1.DataSource = oDataSet; controlId1.DataTextField = "COL1"; //You can set it to the desired columns controlId1.DataValueField = "COL2"; //You can set it to the desired columns controlId1.DataMember = "Table"; //The table names are as Table, Table1.... controlId1.DataBind(); controlId2.DataSource = oDataSet; controlId2.DataTextField = "COL1"; //You can set it to the desired columns controlId2.DataValueField = "COL2"; //You can set it to the desired columns controlId1.DataMember = "Table1"; controlId2.DataBind(); . . .
(All these code are present in a single function. By following this approach you can save few lines of code and few object initialization and extra overheads.)
Hope you find it interesting.