Asp.net GridView Update Delete Insert - CRUD

 


 <asp:Label ID="lblMessage" runat="server" Text="" ForeColor="Red"></asp:Label>
    <asp:GridView ID="gridSample" runat="server" AutoGenerateColumns="False" ShowFooter="True"
                        CssClass="grid" OnRowCommand="gridSample_RowCommand"
        DataKeyNames="Aid" CellPadding="4" ForeColor="#333333"
                        GridLines="None" OnRowCancelingEdit="gridSample_RowCancelingEdit"
                        OnRowEditing="gridSample_RowEditing"
        OnRowUpdating="gridSample_RowUpdating"
        onrowdatabound="gridSample_RowDataBound"
        onrowdeleting="gridSample_RowDeleting">
                        <AlternatingRowStyle BackColor="White" />
                        <Columns>
                            <asp:TemplateField HeaderText="">
                                <ItemTemplate>
                                    <asp:LinkButton ID="lnkEdit" runat="server" Text=""  CommandName="Edit" ToolTip="Edit"
                                        CommandArgument=''><img src="../Images/show.png" /></asp:LinkButton>
                                    <asp:LinkButton ID="lnkDelete" runat="server" Text="Delete" CommandName="Delete"
                                        ToolTip="Delete" OnClientClick='return confirm("Are you sure you want to delete this entry?");'
                                        CommandArgument=''><img src="../Images/icon_delete.png" /></asp:LinkButton>
                                </ItemTemplate>
                                <EditItemTemplate>
                                    <asp:LinkButton ID="lnkInsert" runat="server" Text="" ValidationGroup="editGrp" CommandName="Update" ToolTip="Save"
                                        CommandArgument=''><img src="../Images/icon_save.png" /></asp:LinkButton>
                                    <asp:LinkButton ID="lnkCancel" runat="server" Text="" CommandName="Cancel" ToolTip="Cancel"
                                        CommandArgument=''><img src="../Images/refresh.png" /></asp:LinkButton>
                                </EditItemTemplate>
                                <FooterTemplate>
                                    <asp:LinkButton ID="lnkInsert" runat="server" Text=""  ValidationGroup="newGrp" CommandName="InsertNew" ToolTip="Add New Entry"
                                        CommandArgument=''><img src="../Images/icon_new.png" /></asp:LinkButton>
                                    <asp:LinkButton ID="lnkCancel" runat="server" Text="" CommandName="CancelNew" ToolTip="Cancel"
                                        CommandArgument=''><img src="../Images/refresh.png" /></asp:LinkButton>
                                </FooterTemplate>
                            </asp:TemplateField>
                            <asp:TemplateField HeaderText="Area Name">
                                <EditItemTemplate>
                                    <asp:TextBox ID="txtAreaName" runat="server" Text='<%# Bind("AreaName") %>' CssClass="" MaxLength="30"></asp:TextBox>
                                    <asp:RequiredFieldValidator ID="valFirstName" runat="server" ControlToValidate="txtAreaName"
                                    Display="Dynamic" ErrorMessage="Area Name is required." ForeColor="Red" SetFocusOnError="True"
                                   ValidationGroup="editGrp">*</asp:RequiredFieldValidator>
                                </EditItemTemplate>
                                <ItemTemplate>
                                    <asp:Label ID="lblAreaName" runat="server" Text='<%# Bind("AreaName") %>'></asp:Label>
                                </ItemTemplate>
                                <FooterTemplate>
                                   <asp:TextBox ID="txtAreaNameNew" runat="server" CssClass=""  MaxLength="30"></asp:TextBox>
                                   <asp:RequiredFieldValidator ID="valFirstNameNew" runat="server" ControlToValidate="txtAreaNameNew"
                                    Display="Dynamic" ErrorMessage="Area Name is required." ForeColor="Red" SetFocusOnError="True"
                                   ValidationGroup="newGrp">*</asp:RequiredFieldValidator>
                                </FooterTemplate>
                            </asp:TemplateField>    
                         
                             <asp:TemplateField HeaderText="Category">
                                <EditItemTemplate>
                                    <asp:DropDownList ID="ddlCategory" runat="server">
                                    </asp:DropDownList>
                                    <asp:RequiredFieldValidator ID="valCategory" runat="server" ControlToValidate="ddlCategory"
                                    Display="Dynamic" ErrorMessage="Category is required." ForeColor="Red" SetFocusOnError="True"
                                   ValidationGroup="editGrp">*</asp:RequiredFieldValidator>
                                </EditItemTemplate>
                                <ItemTemplate>
                                    <asp:Label ID="lblCategory" runat="server" Text='<%# Bind("tbl_AreaGroup.AreaGroupName") %>'></asp:Label>
                                </ItemTemplate>
                                <FooterTemplate>
                                  <asp:DropDownList ID="ddlCategoryNew" runat="server">
                                  </asp:DropDownList>
                                   <asp:RequiredFieldValidator ID="valCategoryNew" runat="server" ControlToValidate="ddlCategoryNew"
                                    Display="Dynamic" ErrorMessage="Category is required." ForeColor="Red" SetFocusOnError="True"
                                   ValidationGroup="newGrp">*</asp:RequiredFieldValidator>
                                </FooterTemplate>
                            </asp:TemplateField>                          
                        </Columns>
                        <EditRowStyle BackColor="#2461BF" />
                        <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
                        <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
                        <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
                        <RowStyle BackColor="#EFF3FB" />
                        <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
                        <SortedAscendingCellStyle BackColor="#F5F7FB" />
                        <SortedAscendingHeaderStyle BackColor="#6D95E1" />
                        <SortedDescendingCellStyle BackColor="#E9EBEF" />
                        <SortedDescendingHeaderStyle BackColor="#4870BE" />
</asp:GridView>






 protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                BindGrid();
            }
            lblMessage.Text = "";
        }

        void BindGrid()
        {
            using (SmartmaidappEntities context = new SmartmaidappEntities())
            {
                if (context.tbl_Area.Count() > 0)
                {
                    gridSample.DataSource = context.tbl_Area.ToList();
                    gridSample.DataBind();
                }
                else
                {
                    var obj = new List<tbl_Area>();
                    obj.Add(new tbl_Area());
                    // Bind the DataTable which contain a blank row to the GridView
                    gridSample.DataSource = obj;
                    gridSample.DataBind();
                    int columnsCount = gridSample.Columns.Count;
                    gridSample.Rows[0].Cells.Clear();// clear all the cells in the row
                    gridSample.Rows[0].Cells.Add(new TableCell()); //add a new blank cell
                    gridSample.Rows[0].Cells[0].ColumnSpan = columnsCount; //set the column span to the new added cell

                    //You can set the styles here
                    gridSample.Rows[0].Cells[0].HorizontalAlign = HorizontalAlign.Center;
                    gridSample.Rows[0].Cells[0].ForeColor = System.Drawing.Color.Red;
                    gridSample.Rows[0].Cells[0].Font.Bold = true;
                    //set No Results found to the new added cell
                    gridSample.Rows[0].Cells[0].Text = "NO RESULT FOUND!";
                }
            }
        }

        protected void gridSample_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "InsertNew")
            {
                GridViewRow row = gridSample.FooterRow;
                TextBox txtAreaName = row.FindControl("txtAreaNameNew") as TextBox;            
                DropDownList ddlCategory = row.FindControl("ddlCategoryNew") as DropDownList;
                if (txtAreaName != null && ddlCategory != null)
                {
                    using (SmartmaidappEntities context = new SmartmaidappEntities())
                    {
                        tbl_Area obj = new tbl_Area();
                        obj.AreaName = txtAreaName.Text;                    
                        obj.AGID = Convert.ToInt32(ddlCategory.SelectedValue);
                        context.tbl_Area.Add(obj);
                        context.SaveChanges();
                        lblMessage.Text = "Added successfully.";
                        BindGrid();
                    }
                }
            }
        }

        protected void gridSample_RowEditing(object sender, GridViewEditEventArgs e)
        {
            gridSample.EditIndex = e.NewEditIndex;
            BindGrid();
        }
        protected void gridSample_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            gridSample.EditIndex = -1;
            BindGrid();
        }

        protected void gridSample_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            int Aid = Convert.ToInt32(gridSample.DataKeys[e.RowIndex].Value);
            using (SmartmaidappEntities context = new SmartmaidappEntities())
            {
                tbl_Area obj = context.tbl_Area.First(x => x.Aid == Aid);
                context.tbl_Area.Remove(obj);
                context.SaveChanges();
                BindGrid();
                lblMessage.Text = "Deleted successfully.";
            }
        }
        protected void gridSample_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            GridViewRow row = gridSample.Rows[e.RowIndex];
            TextBox txtAreaName = row.FindControl("txtAreaName") as TextBox;        
            DropDownList ddlCategory = row.FindControl("ddlCategory") as DropDownList;
            if (txtAreaName != null && ddlCategory != null)
            {
                using (SmartmaidappEntities context = new SmartmaidappEntities())
                {
                    int Aid = Convert.ToInt32(gridSample.DataKeys[e.RowIndex].Value);
                    tbl_Area obj = context.tbl_Area.First(x => x.Aid == Aid);
                    obj.AreaName = txtAreaName.Text;
               
                    obj.AGID = Convert.ToInt32(ddlCategory.SelectedValue);
                    context.SaveChanges();
                    lblMessage.Text = "Saved successfully.";
                    gridSample.EditIndex = -1;
                    BindGrid();
                }
            }
        }
        protected void gridSample_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            DropDownList ddl = null;
            if (e.Row.RowType == DataControlRowType.Footer)
            {
                ddl = e.Row.FindControl("ddlCategoryNew") as DropDownList;
            }
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                ddl = e.Row.FindControl("ddlCategory") as DropDownList;
            }
            if (ddl != null)
            {
                using (SmartmaidappEntities context = new SmartmaidappEntities())
                {
                    ddl.DataSource = context.tbl_AreaGroup.ToList();
                    ddl.DataTextField = "AreaGroupName";
                    ddl.DataValueField = "AGID";
                    ddl.DataBind();
                    ddl.Items.Insert(0, new ListItem(""));
                }
                if (e.Row.RowType == DataControlRowType.DataRow)
                {
                    ddl.SelectedValue = ((tbl_Area)(e.Row.DataItem)).AGID.ToString();
                }
            }
        }

Making ASP.NET GridView Responsive With jQuery FooTable



1. Download and add FooTable js, css and image files in the project and reference in the page.


1
2
3
4
<meta name="viewport" content = "width = device-width, initial-scale = 1.0, minimum-scale = 1.0, maximum-scale = 1.0, user-scalable = no" />
<link href="Styles/footable-0.1.css" rel="stylesheet" type="text/css" />
<script src="Scripts/1.8.2/jquery.min.js" type="text/javascript"></script>
<script src="Scripts/footable-0.1.js" type="text/javascript"></script>


<asp:GridView ID="GridView1" CssClass="footable" runat="server"
           AutoGenerateColumns="False">
       <Columns>
           <asp:BoundField DataField="FirstName" HeaderText="First Name"   />
           <asp:BoundField DataField="LastName" HeaderText="Last Name" />
           <asp:BoundField DataField="Email" HeaderText="Email" />
           <asp:TemplateField HeaderText="Address">               
               <ItemTemplate>
                   <asp:Label ID="Label1" runat="server" Text='<%# Bind("Address") %>'></asp:Label>
               </ItemTemplate>
           </asp:TemplateField>
           <asp:BoundField DataField="Contact" HeaderText="Contact" />
       </Columns>
   </asp:GridView>

<script>
$(function () {
        $('#<%=GridView1.ClientID %>').footable({
            breakpoints: {
                phone: 480,
                tablet: 1024
            }
        });
    });

</script>
To bind gridview:



GridView1.DataSource = GetDataTable();
GridView1.DataBind();  


GetDataTable method returns data for gridview. You can implement it to get data from database and returns datatable or list.
By default asp.net gridview header row is generated in tbody tag, to generate in thead tag:

1
2
GridView1.UseAccessibleHeader = true;
GridView1.HeaderRow.TableSection = TableRowSection.TableHeader;
To define data-* attribute in header cells, put following code after binding:

1
2
3
4
5
TableCellCollection cells = GridView1.HeaderRow.Cells;
cells[0].Attributes.Add("data-class", "expand");
cells[2].Attributes.Add("data-hide", "phone,tablet");
cells[3].Attributes.Add("data-hide", "phone,tablet");
cells[4].Attributes.Add("data-hide", "phone");   
We define data-hide attribute to hide the column for different dimensions. Email and Address will be hidden in tablet view and Email,Address, Contact will be hidden in phone view. On expanding, the hidden data are displayed in row by row.

Jquery Print option

//Jquery


(function($) {
    var opt;

    $.fn.jqprint = function (options) {
        opt = $.extend({}, $.fn.jqprint.defaults, options);

        var $element = (this instanceof jQuery) ? this : $(this);
       
        if (opt.operaSupport && $.browser.opera)
        {
            var tab = window.open("","jqPrint-preview");
            tab.document.open();

            var doc = tab.document;
        }
        else
        {
            var $iframe = $("<iframe  />");
       
            if (!opt.debug) { $iframe.css({ position: "absolute", width: "0px", height: "0px", left: "-600px", top: "-600px" }); }

            $iframe.appendTo("body");
            var doc = $iframe[0].contentWindow.document;
        }
       
        if (opt.importCSS)
        {
            if ($("link[media=print]").length > 0)
            {
                $("link[media=print]").each( function() {
                    doc.write("<link type='text/css' rel='stylesheet' href='" + $(this).attr("href") + "' media='print' />");
                });
            }
            else
            {
                $("link").each( function() {
                    doc.write("<link type='text/css' rel='stylesheet' href='" + $(this).attr("href") + "' />");
                });
            }
        }
       
        if (opt.printContainer) { doc.write($element.outer()); }
        else { $element.each( function() { doc.write($(this).html()); }); }
       
        doc.close();
       
        (opt.operaSupport && $.browser.opera ? tab : $iframe[0].contentWindow).focus();
        setTimeout( function() { (opt.operaSupport && $.browser.opera ? tab : $iframe[0].contentWindow).print(); if (tab) { tab.close(); } }, 1000);
    }
   
    $.fn.jqprint.defaults = {
debug: false,
importCSS: true,
printContainer: true,
operaSupport: true
};

    // Thanks to 9__, found at http://users.livejournal.com/9__/380664.html
    jQuery.fn.outer = function() {
      return $($('<div></div>').html(this.clone())).html();
    }
})(jQuery);



////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////


 <button class="print-link" style="position: relative;top: -95px;left: 145px;" onclick="jQuery('#Retain').jqprint({ operaSupport: true });">
                Print
            </button>

LINQ querys

Simple Where Clause


using (ServiceContext svcContext = new ServiceContext(_serviceProxy))
{
 var query_where1 = from a in svcContext.AccountSet
                    where a.Name.Contains("Contoso")
                    select a;
 foreach (var a in query_where1)
 {
  System.Console.WriteLine(a.Name + " " + a.Address1_City);
 }
}

Join and Simple Where Clause

using (ServiceContext svcContext = new ServiceContext(_serviceProxy))
{
 var query_where3 = from c in svcContext.ContactSet
                    join a in svcContext.AccountSet
                    on c.ContactId equals a.PrimaryContactId.Id
                    where a.Name.Contains("Contoso")
                    where c.LastName.Contains("Smith")
                    select new
                    {
                     account_name = a.Name,
                     contact_name = c.LastName
                    };

 foreach (var c in query_where3)
 {
  System.Console.WriteLine("acct: " +
   c.account_name +
   "\t\t\t" +
   "contact: " +
   c.contact_name);
 }
}

Use the Distinct Operator

using (ServiceContext svcContext = new ServiceContext(_serviceProxy))
{
 var query_distinct = (from c in svcContext.ContactSet
                       select c.LastName).Distinct();
 foreach (var c in query_distinct)
 {
  System.Console.WriteLine(c);
 }
}

Simple Inner Join

using (ServiceContext svcContext = new ServiceContext(_serviceProxy))
{
 var query_join1 = from c in svcContext.ContactSet
                   join a in svcContext.AccountSet
                  on c.ContactId equals a.PrimaryContactId.Id
                   select new
                   {
                    c.FullName,
                    c.Address1_City,
                    a.Name,
                    a.Address1_Name
                   };
 foreach (var c in query_join1)
 {
  System.Console.WriteLine("acct: " +
   c.Name +
   "\t\t\t" +
   "contact: " +
   c.FullName);
 }
}

Self Join

using (ServiceContext svcContext = new ServiceContext(_serviceProxy))
{
 var query_join5 = from a in svcContext.AccountSet
                   join a2 in svcContext.AccountSet
                   on a.ParentAccountId.Id equals a2.AccountId

                   select new
                   {
                    account_name = a.Name,
                    account_city = a.Address1_City
                   };
 foreach (var c in query_join5)
 {
  System.Console.WriteLine(c.account_name + "  " + c.account_city);
 }
}

Double and Multiple Joins

using (ServiceContext svcContext = new ServiceContext(_serviceProxy))
{
 var query_join4 = from a in svcContext.AccountSet
                   join c in svcContext.ContactSet
                   on a.PrimaryContactId.Id equals c.ContactId
                   join l in svcContext.LeadSet
                   on a.OriginatingLeadId.Id equals l.LeadId
                   select new
                   {
                    contact_name = c.FullName,
                    account_name = a.Name,
                    lead_name = l.FullName
                   };
 foreach (var c in query_join4)
 {
  System.Console.WriteLine(c.contact_name +
   "  " +
   c.account_name +
   "  " +
   c.lead_name);
 }
}

Join Using Entity Fields

using (ServiceContext svcContext = new ServiceContext(_serviceProxy))
{
 var list_join = (from a in svcContext.AccountSet
                  join c in svcContext.ContactSet
                  on a.PrimaryContactId.Id equals c.ContactId
                  where a.Name == "Contoso Ltd" &&
                  a.Address1_Name == "Contoso Pharmaceuticals"
                  select a).ToList();
 foreach (var c in list_join)
 {
  System.Console.WriteLine("Account " + list_join[0].Name
      + " and it's primary contact "
      + list_join[0].PrimaryContactId.Id);
 }
}

Late-Binding Left Join

using (ServiceContext svcContext = new ServiceContext(_serviceProxy))
{
 var query_join8 = from a in svcContext.AccountSet
                   join c in svcContext.ContactSet
                   on a.PrimaryContactId.Id equals c.ContactId
                   into gr
                   from c_joined in gr.DefaultIfEmpty()
                   select new
                   {
                    contact_name = c_joined.FullName,
                    account_name = a.Name
                   };
 foreach (var c in query_join8)
 {
  System.Console.WriteLine(c.contact_name + "  " + c.account_name);
 }
}

Use the Equals Operator

using (ServiceContext svcContext = new ServiceContext(_serviceProxy))
{
 var query_equals1 = from c in svcContext.ContactSet
                     where c.FirstName.Equals("Colin")
                     select new
                     {
                      c.FirstName,
                      c.LastName,
                      c.Address1_City
                     };
 foreach (var c in query_equals1)
 {
  System.Console.WriteLine(c.FirstName +
   " " + c.LastName +
   " " + c.Address1_City);
 }
}

Use the Not Equals Operator

using (ServiceContext svcContext = new ServiceContext(_serviceProxy))
{
 var query_ne1 = from c in svcContext.ContactSet
                 where c.Address1_City != "Redmond"
                 select new
                 {
                  c.FirstName,
                  c.LastName,
                  c.Address1_City
                 };
 foreach (var c in query_ne1)
 {
  System.Console.WriteLine(c.FirstName + " " +
   c.LastName + " " + c.Address1_City);
 }
}

Use a Method-Based LINQ Query with a Where Clause

using (ServiceContext svcContext = new ServiceContext(_serviceProxy))
{
 var methodResults = svcContext.ContactSet
  .Where(a => a.LastName == "Smith");
 var methodResults2 = svcContext.ContactSet
  .Where(a => a.LastName.StartsWith("Smi"));
 Console.WriteLine();
 Console.WriteLine("Method query using Lambda expression");
 Console.WriteLine("---------------------------------------");
 foreach (var a in methodResults)
 {
  Console.WriteLine("Name: " + a.FirstName + " " + a.LastName);
 }
 Console.WriteLine("---------------------------------------");
 Console.WriteLine("Method query 2 using Lambda expression");
 Console.WriteLine("---------------------------------------");
 foreach (var a in methodResults2)
 {
  Console.WriteLine("Name: " + a.Attributes["firstname"] +
   " " + a.Attributes["lastname"]);
 }
}

Use the Greater Than Operator

using (ServiceContext svcContext = new ServiceContext(_serviceProxy))
{
 var query_gt1 = from c in svcContext.ContactSet
                 where c.Anniversary > new DateTime(2010, 2, 5)
                 select new
                 {
                  c.FirstName,
                  c.LastName,
                  c.Address1_City
                 };

 foreach (var c in query_gt1)
 {
  System.Console.WriteLine(c.FirstName + " " +
   c.LastName + " " + c.Address1_City);
 }
}

Use the Greater Than or Equals and Less Than or Equals Operators

using (ServiceContext svcContext = new ServiceContext(_serviceProxy))
{
 var query_gele1 = from c in svcContext.ContactSet
                   where c.CreditLimit.Value >= 200 &&
                   c.CreditLimit.Value <= 400
                   select new
                   {
                    c.FirstName,
                    c.LastName
                   };
 foreach (var c in query_gele1)
 {
  System.Console.WriteLine(c.FirstName + " " + c.LastName);
 }
}

Use the Contains Operator

using (ServiceContext svcContext = new ServiceContext(_serviceProxy))
{
 var query_contains1 = from c in svcContext.ContactSet
                       where c.Description.Contains("Alpine")
                       select new
                       {
                        c.FirstName,
                        c.LastName
                       };
 foreach (var c in query_contains1)
 {
  System.Console.WriteLine(c.FirstName + " " + c.LastName);
 }
}

Use the Does Not Contain Operator

using (ServiceContext svcContext = new ServiceContext(_serviceProxy))
{
 var query_contains2 = from c in svcContext.ContactSet
                       where !c.Description.Contains("Coho")
                       select new
                       {
                        c.FirstName,
                        c.LastName
                       };
 foreach (var c in query_contains2)
 {
  System.Console.WriteLine(c.FirstName + " " + c.LastName);
 }
}

Use the And and Or Operators

using (ServiceContext svcContext = new ServiceContext(_serviceProxy))
{
 var query_andor1 = from c in svcContext.ContactSet
                    where ((c.Address1_City == "Redmond" ||
                    c.Address1_City == "Bellevue") &&
                    (c.CreditLimit.Value != null &&
                    c.CreditLimit.Value >= 200))
                    select c;

 foreach (var c in query_andor1)
 {
  System.Console.WriteLine(c.LastName + ", " + c.FirstName + " " +
   c.Address1_City + " " + c.CreditLimit.Value);
 }
}

Use the OrderBy Operator

using (ServiceContext svcContext = new ServiceContext(_serviceProxy))
{
 var query_orderby1 = from c in svcContext.ContactSet
                      where !c.CreditLimit.Equals(null)
                      orderby c.CreditLimit descending
                      select new
                      {
                       limit = c.CreditLimit,
                       first = c.FirstName,
                       last = c.LastName
                      };
 foreach (var c in query_orderby1)
 {
  System.Console.WriteLine(c.limit.Value + " " +
   c.last + ", " + c.first);
 }
}

Use the First and Single Operators

using (ServiceContext svcContext = new ServiceContext(_serviceProxy))
{
 Contact firstcontact = svcContext.ContactSet.First();

 Contact singlecontact = svcContext.ContactSet.Single(c => c.ContactId == _contactId1);
 System.Console.WriteLine(firstcontact.LastName + ", " +
  firstcontact.FirstName + " is the first contact");
 System.Console.WriteLine("==========================");
 System.Console.WriteLine(singlecontact.LastName + ", " +
  singlecontact.FirstName + " is the single contact");
}

Retrieving Formatted Values

using (ServiceContext svcContext = new ServiceContext(_serviceProxy))
{
 var list_retrieve1 = from c in svcContext.ContactSet
                      where c.ContactId == _contactId1
                      select new { StatusReason = c.FormattedValues["statuscode"] };
 foreach (var c in list_retrieve1)
 {
  System.Console.WriteLine("Status: " + c.StatusReason);
 }
}

Use the Skip and Take Operators without Paging

using (ServiceContext svcContext = new ServiceContext(_serviceProxy))
{

 var query_skip = (from c in svcContext.ContactSet
                   where c.LastName != "Parker"
                   orderby c.FirstName
                   select new
                       {
                        last = c.LastName,
                        first = c.FirstName
                       }).Skip(2).Take(2);
 foreach (var c in query_skip)
 {
  System.Console.WriteLine(c.first + " " + c.last);
 }
}


Use a Paging Sort

using (ServiceContext svcContext = new ServiceContext(_serviceProxy))
{
 var query_pagingsort1 = (from c in svcContext.ContactSet
                          where c.LastName != "Parker"
                          orderby c.LastName ascending,
                          c.FirstName descending
                          select new { c.FirstName, c.LastName })
                          .Skip(2).Take(2);
 foreach (var c in query_pagingsort1)
 {
  System.Console.WriteLine(c.FirstName + " " + c.LastName);
 }
}

Use .Value to Retrieve the Value of an Attribute

using (ServiceContext svcContext = new ServiceContext(_serviceProxy))
{

 var query_value = from c in svcContext.ContactSet
                   where c.ContactId != _contactId2
                   select new
                   {
                    ContactId = c.ContactId != null ?
                     c.ContactId.Value : Guid.Empty,
                    NumberOfChildren = c.NumberOfChildren != null ?
                     c.NumberOfChildren.Value : default(int),
                    CreditOnHold = c.CreditOnHold != null ?
                     c.CreditOnHold.Value : default(bool),
                    Anniversary = c.Anniversary != null ?
                     c.Anniversary.Value : default(DateTime)
                   };

 foreach (var c in query_value)
 {
  System.Console.WriteLine(c.ContactId + " " + c.NumberOfChildren + 
   " " + c.CreditOnHold + " " + c.Anniversary);
 }
}

Use the GetAttributeValue Method

using (ServiceContext svcContext = new ServiceContext(_serviceProxy))
{
 var query_getattrib = from c in svcContext.ContactSet
                       where c.GetAttributeValue<Guid>("contactid") != _contactId1
                       select new
                       {
                        ContactId = c.GetAttributeValue<Guid?>("contactid"),
                        NumberOfChildren = c.GetAttributeValue<int?>("numberofchildren"),
                        CreditOnHold = c.GetAttributeValue<bool?>("creditonhold"),
                        Anniversary = c.GetAttributeValue<DateTime?>("anniversary"),
                       };

 foreach (var c in query_getattrib)
 {
  System.Console.WriteLine(c.ContactId + " " + c.NumberOfChildren + 
   " " + c.CreditOnHold + " " + c.Anniversary);
 }
}

Use Math Methods

using (ServiceContext svcContext = new ServiceContext(_serviceProxy))
{
 var query_math = from c in svcContext.ContactSet
                  where c.ContactId != _contactId2
                  && c.Address1_Latitude != null && 
                  c.Address1_Longitude != null
                  select new
                  {
                   Round = Math.Round(c.Address1_Latitude.Value),
                   Floor = Math.Floor(c.Address1_Latitude.Value),
                   Ceiling = Math.Ceiling(c.Address1_Latitude.Value),
                   Abs = Math.Abs(c.Address1_Latitude.Value),
                  };
 foreach (var c in query_math)
 {
  System.Console.WriteLine(c.Round + " " + c.Floor + 
   " " + c.Ceiling + " " + c.Abs);
 }
}

Use Multiple Select and Where Clauses

using (ServiceContext svcContext = new ServiceContext(_serviceProxy))
{
 var query_multiselect = svcContext.IncidentSet
                        .Where(i => i.IncidentId != _incidentId1)
                        .Select(i => i.incident_customer_accounts)
                        .Where(a => a.AccountId != _accountId2)
                        .Select(a => a.account_primary_contact)
                        .OrderBy(c => c.FirstName)
                        .Select(c => c.ContactId);
 foreach (var c in query_multiselect)
 {
  System.Console.WriteLine(c.GetValueOrDefault());
 }
}

Use SelectMany

using (ServiceContext svcContext = new ServiceContext(_serviceProxy))
{
 var query_selectmany = svcContext.ContactSet
                        .Where(c => c.ContactId != _contactId2)
                        .SelectMany(c => c.account_primary_contact)
                        .OrderBy(a => a.Name);
 foreach (var c in query_selectmany)
 {
  System.Console.WriteLine(c.AccountId + " " + c.Name);
 }
}


Use String Operations

using (ServiceContext svcContext = new ServiceContext(_serviceProxy))
{
 var query_string = from c in svcContext.ContactSet
                    where c.ContactId == _contactId2
                    select new
                    {
                     IndexOf = c.FirstName.IndexOf("contact"),
                     Insert = c.FirstName.Insert(1, "Insert"),
                     Remove = c.FirstName.Remove(1, 1),
                     Substring = c.FirstName.Substring(1, 1),
                     ToUpper = c.FirstName.ToUpper(),
                     ToLower = c.FirstName.ToLower(),
                     TrimStart = c.FirstName.TrimStart(),
                     TrimEnd = c.FirstName.TrimEnd(),
                    };

 foreach (var c in query_string)
 {
  System.Console.WriteLine(c.IndexOf + "\n" + c.Insert + "\n" + 
   c.Remove + "\n" + c.Substring + "\n"
                           + c.ToUpper + "\n" + c.ToLower + 
                           "\n" + c.TrimStart + " " + c.TrimEnd);
 }
}


How to get all Dates given “Day Name” Between 2 Dates in c#

 var firstDate = new DateTime(2011, 1, 1);
 var lastDate = new DateTime(2011, 1, 20);

 var result = (from el in Enumerable.Range(0, (lastDate - firstDate).Days)
                      let date = firstDate.AddDays(el)
                      where date.DayOfWeek == DayOfWeek.Sunday
                      select date).ToArray();

Search This Blog

Arsip Blog

Powered by Blogger.

Recent

Comment

Author Info

Like This Theme

Popular Posts

Video Of Day

jishnukanat@gmail.com

Sponsor

Most Popular