Thursday, February 3, 2011

How to create a basic ASP.NET GridView manually–Basic DataBinding


As I am working on some legacy systems and use to give support for them, where one cannot find predefined drag and drop controls, and somewhat have to tailor one for themselves.

Today I will share the experience of such practice with all of you (actually it is called manual data binding with a table using a Dataset object)

below is the code of an page


A simple page with only one table control as an example:

<asp:Table ID="tblPayment" runat="server" 
Font-Names="arial, helvetica, sans-serif">

Now the code behind to bind a DataSet object might look alike below:


 trow = new TableRow();
            tcell = new TableCell();
            tcell.Width = 150;
            lblUserName = new Label();
            lblUserName.Text = "Name ";
            // first cell finished
            // second cell
            tcell = new TableCell();
            tcell.Width = 5;
            lblColn = new Label();
            lblColn.Text = ":";
            // second cell finished
            // third cell
            tcell = new TableCell();
            lblName = new Label();
            userName = dsPaymentReceive.Tables[0].Rows[0]["username"].ToString();
            dsMember = new DataSet();
            gClsUserAdmin = new WSUserAdmin.WSUserAdmin();
            gClsGeneralFunction.SetUserAdminWebServiceUrl("WSUserAdmin.asmx", gClsUserAdmin);
            //string name = "";
            fName = dsPaymentReceive.Tables[0].Rows[0]["fname"].ToString();
            sName = dsPaymentReceive.Tables[0].Rows[0]["surname"].ToString();
            name = fName + " " + sName;
            lblName.Text = name.ToString();
            // End of Adding by ARYA 
            //third cell


As above shows that we requested a DataSet Obj from a Service call, and then dynamically making new rows and cells, adding rows in the table defined in the aspx file.


We can do that in a for loop too  if the number of rows are greater than1.