Sunday, 2 December 2012

Binding FormView with Datatable, using ObjectDataSource C#

How to Bind FormView with Datatable using ObjectDataSource C#




Step 1) Create a class name it as DATATABLECRUD.cs
  •  Add 4 methods
  1. GetStudentDetails
  2. DeleteStudentInfo
  3. UpdateStudentInfo
  4. AddStudentInfo


  5. Add One more class called StudentInfo
  • It has 3 public properties
  1. SerialNo   int
  2. StudentName  String
  3. Course   String

  4. U can add as many fields u want,because this is a demo ,Explains how to use Databinding in FormView using DataTable as DataSource,CRUD operations managed by ObjectDataSource.

  5. //You can add DataAnnotations using System.ComponentModel.DataAnnotations; otherwise remove
  6.  public class StudentInfo
  7.     {
  8.         [Key]
  9.         public Int32 SerialNo { get; set; }
  10.         [Required(ErrorMessage="Student Name Required")]
  11.         public String StudentName { set; get; }
  12.         [Required]
  13.         public String Course { get; set; }
  14.     }


  15.   public class DATATABLECRUD
  16.     {
  17.         private DataTable brandsTable = new DataTable();

  18.         //This explains how to access & use Session object in Class Library or Class.

  19.         HttpContext context = HttpContext.Current;
  20.         System.Web.SessionState.HttpSessionState session = null;
  21.         
  22.         public DATATABLECRUD()
  23.         {
  24.             AddDataTableColumns();
  25.             AddDataTableRows();

  26.             session=context.Session;
  27.             if (session["tbl"] == null)
  28.             {
  29.                 session["tbl"] = brandsTable;
  30.             }
  31.             else brandsTable = (DataTable)session["tbl"];

  32.         }
  33.         //Add same number of columns/names specified by StudentInfo class.
  34.         void AddDataTableColumns()
  35.         {
  36.             DataColumn ID = new DataColumn("SerialNo", typeof(System.Int32));
  37.             ID.AutoIncrement = true;
  38.             ID.AutoIncrementSeed = 1000;
  39.             ID.AutoIncrementStep = 16;

  40.             DataColumn BrandName = new DataColumn("StudentName", typeof(System.String));
  41.             BrandName.MaxLength = 100;

  42.             DataColumn BrandImage = new DataColumn("Course");
  43.             BrandImage.DataType = typeof(String);
  44.             brandsTable.Columns.Add(ID); brandsTable.Columns.Add(BrandName); brandsTable.Columns.Add(BrandImage);
  45.             
  46.         }
  47.         //Add sample data for display  
  48.         void AddDataTableRows()
  49.         {
  50.             DataRow row1 = brandsTable.NewRow();
  51.             row1[1] = "Beta";
  52.             row1[2] = "C#"; brandsTable.Rows.Add(row1);
  53.             row1 = brandsTable.NewRow();
  54.             row1[1] = "'Brands";
  55.             row1[2] = "ASP.NET"; brandsTable.Rows.Add(row1);
  56.             row1 = brandsTable.NewRow();
  57.             row1[1] = "MODULES";
  58.             row1[2] = "JAVA"; brandsTable.Rows.Add(row1);

  59.         }
  60.         //FormView GET        
  61.         public List<StudentInfo> GetStudentTable()
  62.         {
  63.             var studentquery = from st in brandsTable.AsEnumerable()
  64.                                select new StudentInfo
  65.                                {
  66.                                    SerialNo = st.Field<System.Int32>(0),
  67.                                    StudentName = st.Field<String>(1),
  68.                                    Course = st.Field<String>(2)
  69.                                };
  70.             return studentquery.ToList();
  71.         }
  72.       //FormView Insert
  73.         public bool AddRows(StudentInfo sInfo)
  74.         {
  75.             
  76.            
  77.             brandsTable = (DataTable)session["tbl"];
  78.             //brandsTable = (DataTable)HttpContext.Current.Session["tbl"];
  79.             DataRow row =brandsTable.NewRow();
  80.             row[1] = sInfo.StudentName;
  81.             row[2] = sInfo.Course;
  82.             brandsTable.Rows.Add(row);
  83.             HttpContext.Current.Session.Add("tbl", brandsTable);
  84.             return true;
  85.         }
  86.                 //FormView Update
  87.         public bool UpdateRows(StudentInfo sInfo)
  88.         {
  89.             bool bRet = false;
  90.             brandsTable = (DataTable)session["tbl"];
  91.             DataRow row = brandsTable.AsEnumerable().SingleOrDefault(s => s.Field<Int32>(0) == sInfo.SerialNo);
  92.             if (row != null)
  93.             {
  94.                 row[1] = sInfo.StudentName;
  95.                 row[2] = sInfo.Course;
  96.                 bRet = true;
  97.                 session["tbl"] = brandsTable;
  98.             }
  99.             return bRet;
  100.         }
  101.         //FormView Delete
  102.         public bool DeleteRows(StudentInfo sInfo)
  103.         {
  104.             bool bRet = false;
  105.             brandsTable = (DataTable)session["tbl"];
  106.             DataRow row = brandsTable.AsEnumerable().SingleOrDefault(s => s.Field<Int32>(0) == sInfo.SerialNo);
  107.             if (row != null)
  108.             {
  109.                 brandsTable.Rows.Remove(row);
  110.                 session["tbl"] = brandsTable;
  111.                 bRet = true;
  112.             }
  113.             return bRet;
  114.         }
  115.     
  116.     }

  117. Adding ObjectDataSoure to aspx page as shown below


    Goto  View --> Toolbox
   In Toolbox Under data category  select ObjectDataSource , just drag/double click into aspx
  as shown below





Step 2)  Goto  design view of aspx page click on object data source




Step 3) Choose a Business Object  i.e  CRUD operations class in our case it is DATATABLECRUD.cs ==> webApplication1.DATATABLECRUD


Step 4)  Use SelectMethod  as GetStudentTable
               as shown below



Step 5) Use UpdateMethod as UpdateRows
 Step 6) InsertMethod as AddRows
 Step 6) UpdateMethod as UpdateRows
 These steps configures ObjectDataSource  for CRUD Operations , here we choose DataTable as Data Source. In same way u can configure for MS-ACCESS/SQL-Server/MYSQL/ORACLE.

Step 4)  Now add FormView to aspx page  and select  datasource (i.e created just now objectdatasourceid1)

 as shown below

        <asp:FormView ID="FormView1" Caption="<h1>FormView Data Operations/CRUD operations/Insert,Update,Delete Operations<h1>" DataKeyNames="SerialNo" runat="server"   EmptyDataText="no data found"  DataSourceID="ObjectDataSource1" GridLines="Both" AllowPaging="True" Width="295px"  >
                    <ItemTemplate>
                        SerialNo:
                <asp:Label ID="SerialNoLabel" runat="server" Text='<%# Bind("SerialNo") %>'></asp:Label><br />
                        StudentName:
                <asp:Label ID="StudentNameLabel" runat="server" Text='<%# Bind("StudentName") %>'></asp:Label><br />
                        Course:
                 <asp:Label ID="CourseLabel" runat="server" Text='<%# Bind("Course") %>'></asp:Label><br />
                        <asp:LinkButton ID="EditButton" runat="server" CausesValidation="False" CommandName="Edit" Text="Edit" />
                        &nbsp;<asp:LinkButton ID="DeleteButton" runat="server" CausesValidation="False" CommandName="Delete" Text="Delete" />
                        &nbsp;<asp:LinkButton ID="NewButton" runat="server" CausesValidation="False" CommandName="New" Text="New" />
            </ItemTemplate>
                    <EditItemTemplate>
                        SerialNo:
                        <asp:TextBox ID="SerialNoTextBox" runat="server" Text='<%# Bind("SerialNo") %>'  />
                        <br />
                        StudentName:
                        <asp:TextBox ID="StudentNameTextBox" runat="server" Text='<%# Bind("StudentName") %>' />
                        <br />
                        Course:
                        <asp:TextBox ID="CourseTextBox" runat="server" Text='<%# Bind("Course") %>' />
                        <br />
                        <asp:LinkButton ID="UpdateButton" runat="server" CausesValidation="True" CommandName="Update" Text="Update" />
                        &nbsp;<asp:LinkButton ID="UpdateCancelButton" runat="server" CausesValidation="False" CommandName="Cancel" Text="Cancel" />
                    </EditItemTemplate>
            <InsertItemTemplate>
                SerialNo:
                <asp:TextBox runat="server"  ID="SerialNoTextBox" Text='<%# Bind("SerialNo") %>'></asp:TextBox> <br />
                StudentName:
                <asp:TextBox runat="server" Text='<%# Bind("StudentName") %>' ID="StudentNameTextBox"></asp:TextBox>
                <br />
                Course:
                <asp:TextBox ID="CourseTextBox" runat="server" Text='<%# Bind("Course") %>'  />
                <br />
                <asp:LinkButton ID="InsertButton" runat="server" CausesValidation="True" CommandName="Insert" Text="Insert" />
                &nbsp;<asp:LinkButton ID="InsertCancelButton" runat="server" CausesValidation="False" CommandName="Cancel" Text="Cancel" />
                </InsertItemTemplate>

        </asp:FormView>

Step 5)  Above step will automatically generate ItemTemplate, EditTemplates,InsertTemplate in FormView.

FormView SelectMethod OUTPUT
FormView Insert Operation Output
FormView Update Operation Output
FormView Delete Operation




Above article explains databind to FormView in ASP.NET USING c#, Object data Source used for Data Source Navigator. This process Simplifies coding . Makes easier to maintain.