Category Archives: Linq
Inserting Data and Updating GridView Without Full page Postback
Aspx Code:
This example shows how we can Insert data in a database table and show that data in a GridView without full page update.
To do that I will create a Web Form with a Some Text box, a button and GirdView.
What we want is when a user Click on the Button after giving input, the gridview should show the data without full postback. To do that we will add the gridview inside an UpdaterPanel and set the Button to do Asynchronous Trigger to the UpdaterPanel.
ASPX CODE:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="GridViewAjaxSample.aspx.cs" Inherits="MCTSASP3._5.Chapter6Ajax.GridViewAjaxSample" %> <%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="cc1" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> <style type="text/css"> .style1 { width: 100%; } .style2 { height: 26px; } .style3 { height: 26px; width: 123px; } .style4 { width: 123px; } </style> </head> <body> <form id="form1" runat="server"> <asp:ScriptManager ID="ScriptManager1" runat="server"> </asp:ScriptManager> <div> <h1> <asp:Label ID="lblExample" runat="server" Text="Ajax Grid View Example"></asp:Label> <cc1:AlwaysVisibleControlExtender ID="lblExample_AlwaysVisibleControlExtender" runat="server" Enabled="True" TargetControlID="lblExample"> </cc1:AlwaysVisibleControlExtender> </h1> </div> <br /> <div> <table style="border: 1px ridge #CC6600; font-family: calibri; font-size: small;"> <tr> <td class="style3"> Company Name: </td> <td class="style2"> <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox> </td> </tr> <tr> <td class="style4"> Contact Name: </td> <td> <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox> </td> </tr> <tr> <td class="style4"> Contact Title: </td> <td> <asp:TextBox ID="TextBox3" runat="server"></asp:TextBox> </td> </tr> <tr> <td class="style4"> City: </td> <td> <asp:TextBox ID="TextBox4" runat="server"></asp:TextBox> </td> </tr> <tr> <td class="style4"> Region: </td> <td> <asp:TextBox ID="TextBox5" runat="server"></asp:TextBox> </td> </tr> <tr> <td class="style4"> Postal Code: </td> <td> <asp:TextBox ID="TextBox6" runat="server"></asp:TextBox> </td> </tr> <tr> <td class="style4"> Country: </td> <td> <asp:TextBox ID="TextBox7" runat="server"></asp:TextBox> </td> </tr> <tr> <td class="style4"> Phone: </td> <td> <asp:TextBox ID="TextBox8" runat="server"></asp:TextBox> </td> </tr> <tr> <td class="style4"> Fax: </td> <td> <asp:TextBox ID="TextBox9" runat="server"></asp:TextBox> </td> </tr> <tr> <td class="style4"> Home Page: </td> <td> <asp:TextBox ID="TextBox10" runat="server"></asp:TextBox> </td> </tr> <tr> <td class="style4"> <asp:Button ID="btnAdd" runat="server" Text="Add Supplier" Font-Size="Small" Font-Bold="True" AccessKey="A" BorderWidth="1" BorderColor="Gray" OnClick="btnAdd_Click" /> </td> </tr> </table> <div style="border: 0px solid #C0C0C0; position: relative; float: left; top: -291px; left: 340px; background-color: #FFFFFF; visibility: collapse; height: 106px; width: 85px;"> <asp:UpdatePanel ID="Up2" runat="server"> <ContentTemplate> <asp:Image ID="Image1" runat="server" ImageUrl="~/Chapter6Ajax/Image/15_75.png" Height="75px" Width="82px" ToolTip="Advertisement" ImageAlign="Middle" /> <asp:Timer ID="Timer1" runat="server" Interval="2000" OnTick="Timer1_Tick"> </asp:Timer> </ContentTemplate> </asp:UpdatePanel> </div> </div> <br /> <asp:UpdatePanel ID="UpdatePanel1" runat="server"> <Triggers> <asp:AsyncPostBackTrigger ControlID="btnAdd" EventName="Click" /> </Triggers> <ContentTemplate> <asp:UpdateProgress ID="up1" runat="server"> <ProgressTemplate> <div> Processing, Please wait... </div> </ProgressTemplate> </asp:UpdateProgress> <div> <asp:GridView ID="gvSupplier" runat="server" Font-Size="Small" AllowPaging="True" AutoGenerateColumns="False" DataKeyNames="SupplierID" DataSourceID="SqlDataSource1" Width="100%" BackColor="White" BorderColor="#DEDFDE" BorderWidth="1px" CellPadding="4" ForeColor="Black" GridLines="Vertical" Height="160px" PageSize="5" BorderStyle="None"> <RowStyle BackColor="#F7F7DE" /> <Columns> <asp:BoundField DataField="CompanyName" HeaderText="CompanyName" SortExpression="CompanyName" /> <asp:BoundField DataField="ContactName" HeaderText="ContactName" SortExpression="ContactName" /> <asp:BoundField DataField="ContactTitle" HeaderText="ContactTitle" SortExpression="ContactTitle" /> <asp:BoundField DataField="Address" HeaderText="Address" SortExpression="Address" /> <asp:BoundField DataField="City" HeaderText="City" SortExpression="City" /> <asp:BoundField DataField="Region" HeaderText="Region" SortExpression="Region" /> <asp:BoundField DataField="PostalCode" HeaderText="PostalCode" SortExpression="PostalCode" /> <asp:BoundField DataField="Country" HeaderText="Country" SortExpression="Country" /> <asp:BoundField DataField="Phone" HeaderText="Phone" SortExpression="Phone" /> <asp:BoundField DataField="Fax" HeaderText="Fax" SortExpression="Fax" /> </Columns> <FooterStyle BackColor="#CCCC99" /> <PagerStyle BackColor="#F7F7DE" ForeColor="Black" HorizontalAlign="Right" /> <SelectedRowStyle BackColor="#CE5D5A" ForeColor="White" Font-Bold="True" /> <HeaderStyle BackColor="#6B696B" Font-Bold="True" ForeColor="White" /> <AlternatingRowStyle BackColor="White" /> </asp:GridView> <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:NORTHWINDConnectionString %>" SelectCommand="SELECT * FROM [Suppliers]"></asp:SqlDataSource> </div> </ContentTemplate> </asp:UpdatePanel> </form> </body> </html>
Code BEHIND:
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace MCTSASP3._5.Chapter6Ajax { public partial class GridViewAjaxSample : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { // gvSupplier.DataSource = NorthwindDAO.GetAllSuppliers(); //gvSupplier.DataBind(); } protected void btnAdd_Click(object sender, EventArgs e) { //Sleep Used so that it shows the UpdaterContro, You could do this by DelayAfter property. System.Threading.Thread.Sleep(2000); Supplier supplier = new Supplier(); supplier.CompanyName = TextBox1.Text; supplier.ContactName = TextBox2.Text; supplier.ContactTitle = TextBox3.Text; supplier.City = TextBox4.Text; supplier.Region = TextBox5.Text; supplier.PostalCode = TextBox5.Text; supplier.Country = TextBox6.Text; supplier.Phone = TextBox7.Text; supplier.Fax = TextBox8.Text; supplier.HomePage = TextBox9.Text; NorthwindDAO.InsertSupplier(supplier); gvSupplier.DataBind(); } protected void Timer1_Tick(object sender, EventArgs e) { if( Image1.ImageUrl.Contains("15_75.png")) Image1.ImageUrl="~/Chapter6Ajax/Image/16_75.png"; else if (Image1.ImageUrl.Contains("16_75.png")) Image1.ImageUrl = "~/Chapter6Ajax/Image/17_75.png"; else if (Image1.ImageUrl.Contains("17_75.png")) Image1.ImageUrl = "~/Chapter6Ajax/Image/15_75.png"; } } }
DAO Method Used:
Here I used Linq and Used Northwind Sample Database.
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace MCTSASP3._5.Chapter6Ajax { public class NorthwindDAO { public static NorthwindDataContext GetDataContext() { NorthwindDataContext northwindDataContex = new NorthwindDataContext(); return northwindDataContex; } public static List<Supplier> GetAllSuppliers() { List<Supplier> listOfAllSuppliers = (from supplier in GetDataContext().Suppliers select supplier ).ToList<Supplier>(); return listOfAllSuppliers; } public static void InsertSupplier(Supplier supplier) { string message = " Inserted Successfully"; NorthwindDataContext northwindDataContex = new NorthwindDataContext(); try { northwindDataContex.Suppliers.InsertOnSubmit(supplier); northwindDataContex.SubmitChanges(); } catch (Exception ex) { message = ex.Message; } } } }
Solution Structure:
OUTPUT:
Grid View Client Side Paging Using Linq:
The Aspx page Code:
I am defining the images as Image button in the GridView pagerTemplate
<%@ Page Language=”C#” AutoEventWireup=”true” CodeBehind=”Default.aspx.cs” Inherits=”GridViewServerSidePaging._Default” EnableEventValidation=”false” %>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
<html xmlns=”http://www.w3.org/1999/xhtml”>
<head runat=”server”> <title></title></head>
<body>
<form id=”form1″ runat=”server”>
<div>
<asp:GridView ID=”gvUser” runat=”server” AllowPaging=”True” OnDataBound=”gvUser_DataBound” PageSize=”2″ BorderStyle=”None”
BackColor=”White” BorderColor=”#CC9966″ BorderWidth=”1px” CellPadding=”4″ Height=”16px” Width=”16px”>
<RowStyle BackColor=”White” ForeColor=”#330099″ />
<FooterStyle BackColor=”#FFFFCC” ForeColor=”#330099″ />
<PagerTemplate>
<asp:ImageButton ID=”imgBtnFirst” runat=”server” ImageUrl=”~/Images/first.gif” CommandArgument=”First”
CommandName=”Page” OnCommand=”Paginate” />
<asp:ImageButton ID=”imgBtnPrevious” runat=”server” ImageUrl=”~/Images/previous.gif” CommandArgument=”Prev”
CommandName=”Page” OnCommand=”Paginate” />
<asp:ImageButton ID=”imgBtnNext” runat=”server” ImageUrl=”~/Images/next.gif” CommandArgument=”Next”
CommandName=”Page” OnCommand=”Paginate” />
<asp:ImageButton ID=”imgBtnLast” runat=”server” ImageUrl=”~/Images/last.gif” CommandArgument=”Last”
CommandName=”Page” OnCommand=”Paginate” />
</PagerTemplate>
<PagerStyle BackColor=”#FFFFCC” ForeColor=”#330099″ HorizontalAlign=”Center” />
<SelectedRowStyle BackColor=”#FFCC66″ Font-Bold=”True” ForeColor=”#663399″ />
<HeaderStyle BackColor=”#990000″ Font-Bold=”True” ForeColor=”#FFFFCC” />
</asp:GridView>
</div>
</form>
</body>
</html>
Code Behind:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using GridViewServerSidePaging.DAO;
namespace GridViewServerSidePaging
{
public
partial
class
_Default : System.Web.UI.Page
{
protected
void Page_Load(object sender, EventArgs e)
{
// gvUser.Visible = true;
PopulateGridView(gvUser.PageIndex);
}
protected
void gvUser_DataBound(object sender, EventArgs e)
{
GridViewRow gvPager = gvUser.BottomPagerRow;
if (gvPager == null)
{
return;
}
else
gvPager.Visible = true;
DropDownList ddlPages = (DropDownList)gvPager.Cells[0].FindControl(“ddlPages”);
Label lblPageCount = (Label)gvPager.Cells[0].FindControl(“lblPageCount”);
if (ddlPages != null)
PopulatePager(ddlPages);
if (lblPageCount != null)
lblPageCount.Text = gvUser.PageCount.ToString();
}
private
void PopulateGridView(int pageIndex)
{
gvUser.DataSource = GridDAO.GetAllUser();
gvUser.DataBind();
}
protected
void PopulatePager(DropDownList ddlPages)
{
for (int i = 0; i < gvUser.PageCount; i++)
{
ListItem lstItem = new
ListItem((i + 1).ToString());
if (i == gvUser.PageIndex)
lstItem.Selected = true;
ddlPages.Items.Add(lstItem);
}
}
protected
void Paginate(object sender, CommandEventArgs e)
{
// get the current page selected
int intCurIndex = gvUser.PageIndex;
switch (e.CommandArgument.ToString().ToLower())
{
case
“first”:
gvUser.PageIndex = 0;
break;
case
“prev”:
if (gvUser.PageIndex > 0)
gvUser.PageIndex = intCurIndex – 1;
break;
case
“next”:
gvUser.PageIndex = intCurIndex + 1;
break;
case
“last”:
gvUser.PageIndex = gvUser.PageCount – 1;
break;
}
Response.Write(“” + gvUser.PageIndex);
// popultate the gridview control
PopulateGridView(gvUser.PageIndex);
}
}
}
GridViewBD.dbml

GridViewDAO.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace GridViewServerSidePaging.DAO
{
public
class
GridDAO
{
public
static
GridDBDataContext GetDBContex()
{
GridDBDataContext gridDBContext = new
GridDBDataContext();
return gridDBContext;
}
public
static
List<User> GetAllUser()
{
List<User> userList = (from
User
in GetDBContex().Users select User).ToList<User>();
return userList;
}
public
static
List<User> GetPagedUser(int pageIndex)
{
IEnumerable<User> enumUser;
int skip = pageIndex * 2;
enumUser = GetAllUser().Skip(skip).Take(2);
List<User> userPageList = enumUser.ToList<User>();
return userPageList;
}
}
}
Solution Structure:

Output Image:
