Tuesday, November 18, 2014

Asp.net Binding


Asp.net Data binding that provides much easy way to manipulate data to the control eg.gridview,dropdownlist etc
I’ve notice when we are binding there are some unnecessary codes
 Dropdownlist1.DataTextField = "JObName";
 Dropdownlist1.DataValueField = "JobID"
 Dropdownlist1.DataSource = lstJobs;
 Dropdownlist1.DataBind();
We’re calling DataBind() method to asking to binding.totaly 4 lines of codes is required to bind dropdownlist.what is if we have common method to call to binding.
to find a way to overcome this issue in mind, I thought to create common method to bind it .oh no situation getting will be worsen , have to be specified to each of the  control to bind. Generic is there to solve my issue.
I wrote generic extension method to bind all controls…..
Here is the code…
    public static class EasyBinds
    {
        public static void EasyBind<T>(this Control ct, T t,   string ValueMember = "", string DisplayMember = "")
        {
            Utility<T>.CustomBind(ct, t,  ValueMember, DisplayMember);
        }
    }

    public static class Utility <T2>
    {
        public static void CustomBind(Control gv, T2 lst, string display = null, string value = null)
        {
            if (gv is GridView)
            {
                ((GridView)gv).DataSource = lst;
                ((GridView)gv).DataBind();
            }
            else if (gv is DropDownList)
            {
                ((DropDownList)gv).DataTextField = display;
                ((DropDownList)gv).DataValueField = value;
                ((DropDownList)gv).DataSource = lst;
                ((DropDownList)gv).DataBind();
            }
            else if(gv is ListBox)
            {
                ((ListBox)gv).DataTextField = display;
                ((ListBox)gv).DataValueField = value;
                ((ListBox)gv).DataSource = lst;
                ((ListBox)gv).DataBind();
            }
            else
            {
                throw new Exception("Invalid control to bind");
            }
        }
    }

Calling to method
GridView1.EasyBind<List<Employee>>(lst);
DropDownList2.EasyBind<List<Job>>(lstJobs, "JObName", "JobID");
ListBox1.EasyBind<List<Job>>(lstJobs, "JObName", "JobID");

Happy coding...

No comments:

Post a Comment