Bind All DropDownLists On A Page Using A Common Method

Open SQL Server and create two tables namely State and City:

Table

Create Procedure name is testSp with the following parameters. Here is the Procedure:

  1. Create PROCEDURE testSp  
  2.     (@Para varchar(30) = '', @Id int = 0)  
  3. AS  
  4. Begin  
  5. If@ Para = 'Add'  
  6. Begin  
  7. Select Id, State from State  
  8. END  
  9. Else If@ Para = 'GetCity'  
  10. Begin  
  11. Select CityId, CityName from City where StateId = @Id  
  12. END  
  13. END  
Now Open visual studio, file, new project and select web in template, then ASP.NET empty web application and give it any name.

Now in the solution explorer right click on the solution and add new project in the templates. Select visual C#, then class library and name it a sqlhelper which is a dll. Add reference of this sqlhelper dll into our project. In the class library there is a class Class1.cs inside it. Write the following code:

SqlHelper Code
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.Data.SqlClient;  
  6. using System.Data;  
  7. using System.Configuration;  
  8. using System.Collections;  
  9. namespace SqlHelper {  
  10.     public class Class1 {#  
  11.         region "Declare Variables"  
  12.         private static SqlConnection m_conn = null;  
  13.         public static SqlTransaction m_transaction;#  
  14.         endregion# region "Attach Parameters"  
  15.         private static void AttachParameters(SqlCommand command, SqlParameter[] commandParameters) {  
  16.             foreach(SqlParameter param in commandParameters) {  
  17.                 if (Convert.ToString(param.Value) == "1/1/1999 12:00:00 AM") {  
  18.                     param.Value = DBNull.Value;  
  19.                 }  
  20.                 command.Parameters.Add(param);  
  21.             }  
  22.         }  
  23.         private static void AssignParameterValues(SqlParameter[] commandParameters, object[] parameterValues) {  
  24.             try {  
  25.                 if ((commandParameters == null) || (parameterValues == null)) {  
  26.                     return;  
  27.                 }  
  28.                 for (int i = 0, j = commandParameters.Length; i < j; i++) {  
  29.                     try {  
  30.                         commandParameters[i].Value = parameterValues[i];  
  31.                     } catch {}  
  32.                 }  
  33.             } catch {}  
  34.         }  
  35.         private static void PrepareCommand(SqlCommand command, SqlConnection connection, SqlTransaction transaction, CommandType commandType, string commandText, SqlParameter[] commandParameters) {  
  36.             command.Connection = connection;  
  37.             command.CommandText = commandText;  
  38.             command.Transaction = transaction;  
  39.             command.CommandType = commandType;  
  40.             if (commandParameters != null) {  
  41.                 AttachParameters(command, commandParameters);  
  42.             }  
  43.             return;  
  44.         }#  
  45.         endregion# region "Execute Non Query"  
  46.         public static int ExecuteNonQuery(SqlConnection connection, SqlTransaction transaction, string spName, params object[] parameterValues) {  
  47.             if ((parameterValues != null) && (parameterValues.Length > 0)) {  
  48.                 SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(connection, transaction, spName);  
  49.                 AssignParameterValues(commandParameters, parameterValues);  
  50.                 return ExecuteNonQuery(connection, transaction, CommandType.StoredProcedure, spName, commandParameters);  
  51.             } else {  
  52.                 return ExecuteNonQuery(connection, transaction, CommandType.StoredProcedure, spName);  
  53.             }  
  54.         }  
  55.         public static int ExecuteNonQuery(SqlConnection connection, SqlTransaction transaction, CommandType commandType, string commandText, params SqlParameter[] commandParameters) {  
  56.             SqlCommand cmdExecute = new SqlCommand();  
  57.             PrepareCommand(cmdExecute, connection, transaction, commandType, commandText, commandParameters);  
  58.             int returnVal = cmdExecute.ExecuteNonQuery();  
  59.             return returnVal;  
  60.         }#  
  61.         endregion# region "Connection String"  
  62.         public static SqlConnection OpenConnection(string DBName) {  
  63.             //string connString = System.Configuration.ConfigurationManager.ConnectionStrings[APPID].ConnectionString;  
  64.             string connstr = ConfigurationSettings.AppSettings["Local"].ToString();  
  65.             m_conn = new SqlConnection(connstr);  
  66.             if ((m_conn.State == ConnectionState.Broken) || (m_conn.State == ConnectionState.Closed)) {  
  67.                 m_conn.Open();  
  68.             }  
  69.             return m_conn;  
  70.         }  
  71.         public static SqlConnection OpenConnection() {  
  72.             //string connstr = ConfigurationSettings.AppSettings["connString"].ToString();  
  73.             string connstr = System.Configuration.ConfigurationManager.ConnectionStrings[ConfigurationSettings.AppSettings["APPID"].ToString()].ToString();  
  74.             m_conn = new SqlConnection(connstr);  
  75.             if ((m_conn.State == ConnectionState.Broken) || (m_conn.State == ConnectionState.Closed)) {  
  76.                 m_conn.Open();  
  77.             }  
  78.             return m_conn;  
  79.         }  
  80.         public static void CloseConnection(Object obj) {  
  81.             m_conn = (SqlConnection) obj;  
  82.             if (m_conn.State == ConnectionState.Open) {  
  83.                 m_conn.Close();  
  84.                 m_conn.Dispose();  
  85.             }  
  86.         }#  
  87.         endregion# region "Transaction"  
  88.         public static void StartTransaction() {  
  89.             m_transaction = m_conn.BeginTransaction();  
  90.         }  
  91.         public static void CommitTransaction() {  
  92.             m_transaction.Commit();  
  93.         }  
  94.         public static void RollBackTransaction() {  
  95.             m_transaction.Rollback();  
  96.         }#  
  97.         endregion# region "Execute Dataset"  
  98.         public static DataSet ExecuteDataset(SqlConnection cn, SqlTransaction t, string spName, params object[] parameterValues) {  
  99.             if ((parameterValues != null) && (parameterValues.Length > 0)) {  
  100.                 SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(cn, t, spName);  
  101.                 AssignParameterValues(commandParameters, parameterValues);  
  102.                 return ExecuteDataset(cn, t, CommandType.StoredProcedure, spName, commandParameters);  
  103.             } else {  
  104.                 return ExecuteDataset(cn, t, CommandType.StoredProcedure, spName);  
  105.             }  
  106.         }  
  107.         public static DataSet ExecuteDataset(SqlConnection connection, SqlTransaction t, CommandType commandType, string commandText, params SqlParameter[] commandParameters) {  
  108.             SqlCommand cmdExecute = new SqlCommand();  
  109.             PrepareCommand(cmdExecute, connection, t, commandType, commandText, commandParameters);  
  110.             SqlDataAdapter daExecute = new SqlDataAdapter(cmdExecute);  
  111.             DataSet dstExecute = new DataSet();  
  112.             daExecute.Fill(dstExecute);  
  113.             cmdExecute.Parameters.Clear();  
  114.             return dstExecute;  
  115.         }  
  116.         public static DataSet ExecuteDataset(SqlConnection connection, SqlTransaction t, CommandType commandType, string commandText, string datatableName, params SqlParameter[] commandParameters) {  
  117.             SqlCommand cmdExecute = new SqlCommand();  
  118.             PrepareCommand(cmdExecute, connection, t, commandType, commandText, commandParameters);  
  119.             SqlDataAdapter daExecute = new SqlDataAdapter(cmdExecute);  
  120.             DataSet dstExecute = new DataSet();  
  121.             daExecute.Fill(dstExecute, datatableName);  
  122.             cmdExecute.Parameters.Clear();  
  123.             return dstExecute;  
  124.         }#  
  125.         endregion# region "Execute Scalar"  
  126.         public static object ExecuteScalar(SqlConnection connection, SqlTransaction transaction, string spName, params object[] parameterValues) {  
  127.             if ((parameterValues != null) && (parameterValues.Length > 0)) {  
  128.                 SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(connection, transaction, spName);  
  129.                 AssignParameterValues(commandParameters, parameterValues);  
  130.                 return ExecuteScalar(connection, transaction, CommandType.StoredProcedure, spName, commandParameters);  
  131.             } else {  
  132.                 return ExecuteScalar(connection, transaction, CommandType.StoredProcedure, spName);  
  133.             }  
  134.         }  
  135.         public static object ExecuteScalar(SqlConnection connection, SqlTransaction transaction, CommandType commandType, string commandText, params SqlParameter[] commandParameters) {  
  136.             SqlCommand cmdExecute = new SqlCommand();  
  137.             PrepareCommand(cmdExecute, connection, transaction, commandType, commandText, commandParameters);  
  138.             object returnVal = cmdExecute.ExecuteScalar();  
  139.             cmdExecute.Parameters.Clear();  
  140.             return returnVal;  
  141.         }#  
  142.         endregion# region "Class SqlHelper"  
  143.         public sealed class SqlHelperParameterCache {  
  144.             private SqlHelperParameterCache() {}  
  145.             private static Hashtable paramCache = Hashtable.Synchronized(new Hashtable());  
  146.             private static SqlParameter[] DiscoverSpParameterSet(SqlConnection connection, SqlTransaction transaction, string spName, bool includeReturnValueParameter) {  
  147.                 SqlCommand cmdExecute = new SqlCommand();  
  148.                 cmdExecute.CommandType = CommandType.StoredProcedure;  
  149.                 cmdExecute.CommandText = spName;  
  150.                 cmdExecute.Connection = connection;  
  151.                 // AlternativeDeriveParameters adParams = new AlternativeDeriveParameters();  
  152.                 //cmdExecute.Transaction=transaction;  
  153.                 SqlCommandBuilder.DeriveParameters(cmdExecute);  
  154.                 if (!includeReturnValueParameter) {  
  155.                     cmdExecute.Parameters.RemoveAt(0);  
  156.                 }  
  157.                 SqlParameter[] discoveredParameters = new SqlParameter[cmdExecute.Parameters.Count];  
  158.                 cmdExecute.Parameters.CopyTo(discoveredParameters, 0);  
  159.                 return discoveredParameters;  
  160.             }  
  161.             private static SqlParameter[] CloneParameters(SqlParameter[] originalParameters) {  
  162.                 SqlParameter[] clonedParameters = new SqlParameter[originalParameters.Length];  
  163.                 for (int i = 0, j = originalParameters.Length; i < j; i++) {  
  164.                     clonedParameters[i] = (SqlParameter)((ICloneable) originalParameters[i]).Clone();  
  165.                 }  
  166.                 return clonedParameters;  
  167.             }  
  168.             public static void CacheParameterSet(string connectionString, string commandText, params SqlParameter[] commandParameters) {  
  169.                 string hashKey = ConfigurationSettings.AppSettings["ConnString"].ToString() + ":" + commandText;  
  170.                 paramCache[hashKey] = commandParameters;  
  171.             }  
  172.             public static SqlParameter[] GetCachedParameterSet(SqlConnection connection, string commandText) {  
  173.                 string hashKey = ConfigurationSettings.AppSettings["ConnString"].ToString() + ":" + commandText;  
  174.                 SqlParameter[] cachedParameters = (SqlParameter[]) paramCache[hashKey];  
  175.                 if (cachedParameters == null) {  
  176.                     return null;  
  177.                 } else {  
  178.                     return CloneParameters(cachedParameters);  
  179.                 }  
  180.             }  
  181.             public static SqlParameter[] GetSpParameterSet(SqlConnection connection, SqlTransaction transaction, string spName) {  
  182.                 return GetSpParameterSet(connection, transaction, spName, false);  
  183.             }  
  184.             public static SqlParameter[] GetSpParameterSet(SqlConnection connection, SqlTransaction transaction, string spName, bool includeReturnValueParameter) {  
  185.                 //string connectionString = "";  
  186.                 string hashKey = connection.ConnectionString + ":" + spName + (includeReturnValueParameter ? ":include ReturnValue Parameter" : "");  
  187.                 SqlParameter[] cachedParameters;  
  188.                 cachedParameters = (SqlParameter[]) paramCache[hashKey];  
  189.                 if (cachedParameters == null) {  
  190.                     cachedParameters = (SqlParameter[])(paramCache[hashKey] = DiscoverSpParameterSet(connection, transaction, spName, includeReturnValueParameter));  
  191.                 }  
  192.                 return CloneParameters(cachedParameters);  
  193.             }  
  194.         }#  
  195.         endregion  
  196.     }  
  197. }  
Right click on web application in solution explorer and add new web form on the aspx page; include two dropdown lists one for state as ddlState and other for city as ddlCity. Here is the aspx page code:
  1. <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication12.WebForm1" %>  
  2.     <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
  3.     <html xmlns="http://www.w3.org/1999/xhtml">  
  4.   
  5.     <head runat="server">  
  6.         <title></title>  
  7.     </head>  
  8.   
  9.     <body>  
  10.         <form id="form1" runat="server">  
  11.             <div>  
  12.                 <table>  
  13.                     <tr>  
  14.                         <td>  
  15.                             Select State  
  16.                         </td>  
  17.                         <td>  
  18.                             <asp:DropDownList ID="ddlState" runat="server" onselectedindexchanged="ddlState_SelectedIndexChanged" AutoPostBack="true">  
  19.                             </asp:DropDownList>  
  20.                         </td>  
  21.                     </tr>  
  22.                     <tr>  
  23.                         <td>  
  24.                             Select City  
  25.                         </td>  
  26.                         <td>  
  27.                             <asp:DropDownList ID="ddlCity" runat="server">  
  28.                                 <asp:ListItem Value="0" Selected="True" Text="Select"></asp:ListItem>  
  29.                             </asp:DropDownList>  
  30.                         </td>  
  31.                     </tr>  
  32.                 </table>  
  33.             </div>  
  34.         </form>  
  35.     </body>  
  36.   
  37.     </html>  
Now on the cs side write the following code:
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.UI;  
  6. using System.Web.UI.WebControls;  
  7. using System.Data.SqlClient;  
  8. using System.Configuration;  
  9. using System.Data;  
  10. using SqlHelper;  
  11. namespace WebApplication12 {  
  12.     public partial class WebForm1: System.Web.UI.Page {  
  13.         SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Local"].ToString());  
  14.         SqlParameter[] param;  
  15.         DataSet ds = null;  
  16.         protected void Page_Load(object sender, EventArgs e) {  
  17.             if (!Page.IsPostBack)  
  18.                 BindState();  
  19.         }  
  20.         public void BindALLDDL(ref DropDownList ddl, DataSet ds, string textField, string valueField) {  
  21.             try {  
  22.                 ddl.DataSource = ds;  
  23.                 ddl.DataValueField = ds.Tables[0].Columns[valueField].ToString();  
  24.                 ddl.DataTextField = ds.Tables[0].Columns[textField].ToString();  
  25.                 ddl.DataBind();  
  26.                 ddl.Items.Insert(0, "Select");  
  27.             } catch (Exception ex) {  
  28.                 throw ex;  
  29.             }  
  30.         }  
  31.         private void BindState() {  
  32.             try {  
  33.                 param = new SqlParameter[1];  
  34.                 param[0] = new SqlParameter("@Para", SqlDbType.VarChar);  
  35.                 param[0].Value = "Add";  
  36.                 ds = Class1.ExecuteDataset(con, null, CommandType.StoredProcedure, "testSp", param);  
  37.                 BindALLDDL(ref ddlState, ds, "State""Id");  
  38.             } catch (Exception ex) {  
  39.                 throw ex;  
  40.             }  
  41.         }  
  42.         protected void ddlState_SelectedIndexChanged(object sender, EventArgs e) {  
  43.             try {  
  44.                 if (ddlState.SelectedIndex > 0) {  
  45.                     BindCity();  
  46.                 }  
  47.             } catch (Exception ex) {  
  48.                 throw ex;  
  49.             }  
  50.         }  
  51.         private void BindCity() {  
  52.             try {  
  53.                 param = new SqlParameter[2];  
  54.                 param[0] = new SqlParameter("@Para", SqlDbType.VarChar);  
  55.                 param[0].Value = "GetCity";  
  56.                 param[1] = new SqlParameter("@Id", SqlDbType.Int);  
  57.                 param[1].Value = Convert.ToInt32(ddlState.SelectedItem.Value);  
  58.                 ds = Class1.ExecuteDataset(con, null, CommandType.StoredProcedure, "testSp", param);  
  59.                 BindALLDDL(ref ddlCity, ds, "CityName""CityId");  
  60.             } catch (Exception ex) {  
  61.                 throw ex;  
  62.             }  
  63.         }  
  64.     }  
  65. }  
As you can see BindAllDDL is the common method for binding all drop down list. Its parameters are the following: first is drop down list name, second is dataset, third is text field for drop down list, fourth is value field.

Now see the method bindState I have called it on page load to bind state from state table to drop down ddlState. In the method you can see I have created a SqlParameter array to pass the parameters to StoredProcedure, then I have filled dataset using ExecuteDataset method which is in our SqlHelper class.

Parameters pass to this method are Sqlconnection object, transaction is null, commandtype which is StoredProcedure, then the sp name which is testSp and last is parameter array which passes parameters to StoredProcedure. Then I have called BindALLDLL method and in that I have passed dropdownlist name which is ddlState, then the dataset ds, then textfield name which is State and value field name which is Id.

On similar basis I have bind City dropdown; bindCity is the method for it.

Do not forget to add connection string in the web.config file; here it is:
  1. <connectionStrings>  
  2.    <add name="Local"  
  3. connectionString="Data Source=livingroom\SQLEXPRESS;Integrated Security=true;Initial Catalog=practisedatabase"/>  
  4. </connectionStrings>  
Add this inside configuration section.

Therefore we can bind all drop down list on page using a common method, so in each we do not have to write dropdownlist name. datasource, ddl, datavaluefield, ddlname.datatextfield and ddlname.databind. I will come with more simple solution for the above in the next article.

 

Up Next
    Ebook Download
    View all
    Learn
    View all