Fremus.co.za

Demistifying Life and Web Development

Re-usable code for a Gridview and DropdownList

Both the GridView and DropdownList server controls provided in ASP.NET have DataSource and DataBind methods. This means that you could write the same code to populate both controls with data from a database. So first you would create a method for a class like this:

public DataTable GetData()
{
string strSQL = "select * from tblTest";
using(SqlConnection myConn = new SqlConnection(ConfigurationManager.ConnectionStrings["MyDB"].ToString()))
{
    using(SqlCommand myCmd = new SqlCommand(strSQL, myConn))
    {
           myConn.Open();
           using(SqlDataReader myReader = myCmd.ExecuteReader())
           {
                 DataTable myTable = new DataTable();
                 myTable.Load(myTable);
                 myConn.Close();
                 return myTable;
           }
    }
}
}

And then in the codebehind for the page that contains the GridView or DropDownList controls you create a new instance of the class you created above and set the DataSource property for the control. So if you created a class called myClass your code for the Gridview would look like this:

        myTestClass myClass = new myTestClass();
        gvMyGrid.DataSource = myClass.GetData();
        gvMyGrid.DataBind();

The only difference for the DropDownList would be setting the DataTextField and the DataValueField.

  • Share/Bookmark
posted by fr3dr1k in ASP.NET,C#,Web Development,Web Technologies and have No Comments

Place your comment

Please fill your data and comment below.
Name
Email
Website
Your comment
Get Adobe Flash playerPlugin by wpburn.com wordpress themes