Archive

Archive for February, 2010

Use JQuery to Delete from Gridview

February 27, 2010 5 comments

Hi

try this example to JQuery to Delete from Gridview

Step1 :- Go to JQuery site and Download jquery-1.4.min.js from here

Step2 :- Create a new website and add new web page and Web.Config file

Step3 :- in Web page add Gridview and use SQLDataSource control to bind in it

Note : in this example i’m using Northwind Database

So the web page will be :


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!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>GridView and JQuery</title>
    <script src="Script/jquery-1.4.min.js" type="text/javascript"></script>
     <script type="text/javascript">
         $(document).ready(function() {
             $("#.delbutton").click(function() {
                 //Get the Id of the record to delete
                 var record_id = $(this).attr("id");
                 //Get the GridView Row reference
                 var tr_id = $(this).parents("#.record");
                 // Ask user's confirmation before delete records
                 if (confirm("Do you want to delete this record?")) {
                     $.ajax({
                         type: "POST",
                         //GridViewDelete.aspx is the page name and DeleteUser is the server side method to delete records in GridViewDelete.aspx.cs
                         url: "Default.aspx/DeleteCategory",
                         //Pass the selected record id
                         data: "{'args': '" + record_id + "'}",
                         contentType: "application/json; charset=utf-8",
                         dataType: "json",
                         success: function() {
                             // Change the back color of the Row before deleting
                             tr_id.css("background-color", "lightgreen");
                             // Do some animation effect
                             tr_id.fadeOut(500, function() {
                                 //Remove GridView row
                                 tr_id.remove();
                             });
                         }
                     });
                 }
                 return false;
             });
         });
</script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
   
        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
            CellPadding="4" DataKeyNames="CategoryID" DataSourceID="SqlDataSource1"
            ForeColor="#333333">
            <RowStyle BackColor="#EFF3FB" />
            <Columns>
                <asp:BoundField DataField="CategoryID" HeaderText="CategoryID"
                    InsertVisible="False" ReadOnly="True" SortExpression="CategoryID" />
                <asp:BoundField DataField="CategoryName" HeaderText="CategoryName"
                    SortExpression="CategoryName" />
                <asp:TemplateField>
                    <ItemTemplate>
                     <a href="#" id='<%# Eval("CategoryID") %>'> <img  border="0" src="Images/delete.jpg" alt="Delete" /></a>
                  </ItemTemplate>
                </asp:TemplateField>
            </Columns>
            <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
            <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
            <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
            <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
            <EditRowStyle BackColor="#2461BF" />
            <AlternatingRowStyle BackColor="White" />
        </asp:GridView>
        <asp:SqlDataSource ID="SqlDataSource1" runat="server"
            ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>"
            SelectCommand="SELECT [CategoryID], [CategoryName] FROM [Categories]">
        </asp:SqlDataSource>

    </div>
    </form>
</body>
</html>

Step4 :- in code behind add the following code


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;
using System.Data;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    [System.Web.Services.WebMethod]
    public static void DeleteCategory(string args)
    {
        string conString = ConfigurationManager.ConnectionStrings["NorthwindConnectionString"].ConnectionString;
        SqlConnection sqlConn = new SqlConnection(conString);
        try
        {
            SqlCommand sqlCmd = new SqlCommand("Delete from Categories where CategoryID = @CategoryID", sqlConn);
            sqlCmd.CommandType = CommandType.Text;
            sqlCmd.Parameters.AddWithValue("@CategoryID", Convert.ToInt32(args.Trim()));
            sqlConn.Open();
            sqlCmd.ExecuteNonQuery();
        }
        catch
        {
            //Handle Error
        }
        finally
        {
            sqlConn.Close();
        }
    }
}

Step5 :- in Web.Config file add the connection String

<connectionStrings>
    <add name="NorthwindConnectionString" connectionString="Data Source=.;Initial Catalog=Northwind;Integrated Security=True" providerName="System.Data.SqlClient" />
  </connectionStrings>

Hope this helps

Good Luck.

Advertisements
Categories: ASP.Net, Jquery

AJAX Accordion Paging

February 17, 2010 7 comments

Hi

In a previous post Paging Dynamic AJAX Acordion Control

now i’m going to show an example to Bind AJAX Accordion for with Dynamic Data for Master and Details with Paging

Note :- In this example i’m using Northwind Database

Step1 :- Create a new website project and add new web page

Step2 :- In a Default.aspx


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!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>Untitled Page</title>
      <style type="text/css">
    body {
    font-family: verdana;
    font-size: 11px;
    }
   
    .header,.selected {
    width: 300px;
    background-color: #c0c0c0;
    margin-bottom:2px;
    padding:2px;
    color:#444444;
    font-weight:bold;
    cursor:pointer;
    }
   
    .content {
    width:300px;
    margin-bottom:2px;
    padding:2px;
    }
   
    .selected,.content {
    border:solid 1px #666666;
    }
    </style>
</head>
<body>
    <form id="form1" runat="server">
         <div>
            <asp:ScriptManager ID="ScriptManager1" runat="server">
            </asp:ScriptManager>
        </div>
        <ajaxToolkit:Accordion ID="Accordion1" runat="server" TransitionDuration="100" FramesPerSecond="200" FadeTransitions="true" RequireOpenedPane="false" OnItemDataBound="Accordion1_ItemDataBound"
            ContentCssClass="content" HeaderCssClass="header" HeaderSelectedCssClass="selected">
            <HeaderTemplate>
                <%#DataBinder.Eval(Container.DataItem,"categoryName") %>
            </HeaderTemplate>
            <ContentTemplate>
                <asp:HiddenField ID="txt_categoryID" runat="server" Value='<%#DataBinder.Eval(Container.DataItem,"categoryID") %>' />
                <asp:GridView ID="GridView1" runat="server" RowStyle-BackColor="#ededed" RowStyle-HorizontalAlign="Left"
                    AutoGenerateColumns="false" GridLines="None" CellPadding="2" CellSpacing="2"
                    Width="300px">
                    <Columns>
                        <asp:TemplateField HeaderStyle-HorizontalAlign="Left" HeaderText="Product Name" HeaderStyle-BackColor="#d1d1d1"
                            HeaderStyle-ForeColor="#777777">
                            <ItemTemplate>
                                <%#DataBinder.Eval(Container.DataItem,"productName") %>
                            </ItemTemplate>
                        </asp:TemplateField>
                    </Columns>
                </asp:GridView>
            </ContentTemplate>
        </ajaxToolkit:Accordion>
        <br />
        <div style="background-color:Silver; height:20px; width:100%; padding:20px; text-align:center; vertical-align:bottom; margin-top: 10px;">
        <table >
            <tr>
                <td>
                    Display <asp:DropDownList ID="ddlPageSize" runat="server" AutoPostBack="True" OnSelectedIndexChanged="ddlPageSize_SelectedIndexChanged">
                        <asp:ListItem>5</asp:ListItem>
                        <asp:ListItem>10</asp:ListItem>
                        <asp:ListItem>15</asp:ListItem>
                    </asp:DropDownList></td>
                <td>
                    <asp:LinkButton ID="lnkbtnPrevious" runat="server" OnClick="lnkbtnPrevious_Click">Prev</asp:LinkButton></td>
                <td>
                <asp:DataList ID="dlPaging" runat="server" OnItemCommand="dlPaging_ItemCommand" OnItemDataBound="dlPaging_ItemDataBound" RepeatDirection="Horizontal">
                    <ItemTemplate>
                      <asp:LinkButton ID="lnkbtnPaging" runat="server" CommandArgument='<%# Eval("PageIndex") %>' CommandName="lnkbtnPaging" Text='<%# Eval("PageText") %>'></asp:LinkButton>
                    </ItemTemplate>
                 </asp:DataList>
                </td>
                <td>
                    <asp:LinkButton ID="lnkbtnNext" runat="server" OnClick="lnkbtnNext_Click">Next</asp:LinkButton></td>
            </tr>
        </table>
        </div>
    </form>
</body>
</html>

Step3 :- In code behind add the following code


using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;

public partial class Default : System.Web.UI.Page
{
    string conString = System.Configuration.ConfigurationManager.ConnectionStrings["SqlConnectionString"].ToString();

    PagedDataSource pds = new PagedDataSource();

    public int CurrentPage
    {
        get
        {
            if (this.ViewState["CurrentPage"] == null)
            {
                return 0;
            }
            else
            {
                return Convert.ToInt16(this.ViewState["CurrentPage"].ToString());
            }
        }
        set
        {
            this.ViewState["CurrentPage"] = value;
        }
    }

    private void doPaging()
    {
        DataTable dt = new DataTable();
        dt.Columns.Add("PageIndex");
        dt.Columns.Add("PageText");
        for (int i = 0; i < pds.PageCount; i++)
        {
            DataRow dr = dt.NewRow();
            dr[0] = i;
            dr[1] = i + 1;
            dt.Rows.Add(dr);
        }
        dlPaging.DataSource = dt;
        dlPaging.DataBind();
    }

    public void getCategories()
    {
        SqlConnection sqlConn = new SqlConnection(conString);
        sqlConn.Open();
        SqlCommand sqlSelect = new SqlCommand("SELECT * FROM Categories", sqlConn);
        sqlSelect.CommandType = System.Data.CommandType.Text;
        SqlDataAdapter sqlAdapter = new SqlDataAdapter(sqlSelect);
        DataTable dt = new DataTable();
        sqlAdapter.Fill(dt);
        pds.DataSource = dt.DefaultView;
        pds.AllowPaging = true;
        pds.PageSize = Convert.ToInt16(ddlPageSize.SelectedValue);
        pds.CurrentPageIndex = CurrentPage;
        lnkbtnNext.Enabled = !pds.IsLastPage;
        lnkbtnPrevious.Enabled = !pds.IsFirstPage;
        Accordion1.DataSource = pds;
        Accordion1.DataBind();
        doPaging();
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            getCategories();
        }
    }

    protected void Accordion1_ItemDataBound(object sender, AjaxControlToolkit.AccordionItemEventArgs e)
    {
        if (e.ItemType == AjaxControlToolkit.AccordionItemType.Content)
        {
            SqlConnection sqlConn = new SqlConnection(conString);
           
            SqlCommand sqlSelect = new SqlCommand("SELECT productName FROM Products where categoryID = '" + ((HiddenField)e.AccordionItem.FindControl("txt_categoryID")).Value + "'", sqlConn);
            sqlSelect.CommandType = System.Data.CommandType.Text;
            SqlDataAdapter sqlAdapter = new SqlDataAdapter(sqlSelect);
            DataSet myDataset = new DataSet();
            sqlAdapter.Fill(myDataset);

            GridView grd = new GridView();

            grd = (GridView)e.AccordionItem.FindControl("GridView1");
            grd.DataSource = myDataset;
            grd.DataBind();
        }
    }

    protected void dlPaging_ItemCommand(object source, DataListCommandEventArgs e)
    {
        if (e.CommandName.Equals("lnkbtnPaging"))
        {
            CurrentPage = Convert.ToInt16(e.CommandArgument.ToString());
            getCategories();
        }
    }

    protected void dlPaging_ItemDataBound(object sender, DataListItemEventArgs e)
    {
        LinkButton lnkbtnPage = (LinkButton)e.Item.FindControl("lnkbtnPaging");
        if (lnkbtnPage.CommandArgument.ToString() == CurrentPage.ToString())
        {
            lnkbtnPage.Enabled = false;
            lnkbtnPage.Font.Bold = true;
        }
    }

    protected void lnkbtnPrevious_Click(object sender, EventArgs e)
    {
        CurrentPage -= 1;
        getCategories();
    }

    protected void lnkbtnNext_Click(object sender, EventArgs e)
    {
        CurrentPage += 1;
        getCategories();
    }

    protected void ddlPageSize_SelectedIndexChanged(object sender, EventArgs e)
    {
        CurrentPage = 0;
        getCategories();
    }
}

Step4 :- In Web.Config file add the ConnectionString of your Database

<connectionStrings>
  <add name="SqlConnectionString" connectionString="Data Source=.;Initial Catalog=Northwind;Integrated Security=True"/>
 </connectionStrings>

Hope this helps

Good Luck.

Bind DropdownList with Installed Fonts using Linq

February 16, 2010 Leave a comment

Hi all,

try this example to Bind DropdownList with Installed Fonts using Linq

Step1 :- create new website and add new web page and drag dropdownlist control from Toolbox

<asp:DropDownList ID="DropDownList1" runat="server" AppendDataBoundItems="true">
    <asp:ListItem>--- Please select font ---</asp:ListItem>
</asp:DropDownList>

Step2 :- In code behind of you .aspx page add the following code:-

protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            InstalledFontCollection instedFontColl = new InstalledFontCollection();
            DropDownList1.DataSource = from font in instedFontColl.Families
                                       select font.Name;
            DropDownList1.DataBind();
        }
    }

Dont Forget to use namesapce

using System.Drawing.Text;

after that run your website

Hope this helps 🙂

Good Luck

Categories: ASP.Net, Linq Tags:

Display Image from Database as Image Type using Linq

February 15, 2010 3 comments

Hi

try this example to Display Image from Database as Image Type using Linq

Step1 :- Open MS VS2008 and create a new website

Step2 :- In solution Explorer right cleck and select add new item and add LINQ to SQL classes and name it to “Northwind.dbml”

Step3 :- Open Northwind.dbml and Add Categories Table in Northwind Database and the Save

Step4:- Right click on solution Explorer and add new Generic Handler and name it “ImageHandler.ashx”


<%@ WebHandler Language="C#" %>

using System;
using System.Web;
using System.IO;
using System.Drawing.Imaging;
using System.Collections.Generic;
using System.Linq;

public class ImageHandler : IHttpHandler {
   
    public void ProcessRequest (HttpContext context)
    {
        HttpRequest req = context.Request;          
        // string categoryID = "1";          
        string categoryID = req.QueryString["CategoryID"].ToString();          
        // Get information about the specified category          
        NorthwindDataContext db = new NorthwindDataContext();          
        var category = from c in db.Categories                         
                       where Convert.ToInt32(c.CategoryID) == Convert.ToInt32(categoryID)
                       select c.Picture;          
        int len = category.First().Length;          
        // Output the binary data          
        // But first we need to strip out the OLE header          
        int OleHeaderLength = 78;          
        int strippedImageLength = len - OleHeaderLength;          
        byte[] imagdata = new byte[strippedImageLength];          
        Array.Copy(category.First().ToArray(), OleHeaderLength, imagdata, 0, strippedImageLength);          
        if ((imagdata) != null)          
        {              
            MemoryStream m = new MemoryStream(imagdata);              
            System.Drawing.Image image = System.Drawing.Image.FromStream(m);              
            image.Save(context.Response.OutputStream, ImageFormat.Jpeg);          
        }
    }
 
    public bool IsReusable {
        get {
            return false;
        }
    }
}

Step5 :- In Default.aspx page add new Gridview control and bind it using SQLDatasource control

<div>
   
        <asp:GridView ID="GridView1" runat="server" AllowPaging="True"
            AutoGenerateColumns="False" DataKeyNames="CategoryID"
            DataSourceID="SqlDataSource1" CellPadding="4" ForeColor="#333333"
            GridLines="None">
            <RowStyle BackColor="#EFF3FB" />
            <Columns>
                <asp:BoundField DataField="CategoryID" HeaderText="CategoryID"
                    InsertVisible="False" ReadOnly="True" SortExpression="CategoryID" />
                <asp:BoundField DataField="CategoryName" HeaderText="CategoryName"
                    SortExpression="CategoryName" />
                <asp:BoundField DataField="Description" HeaderText="Description"
                    SortExpression="Description" />
                <asp:TemplateField HeaderText="Picture" SortExpression="Picture">
                    <EditItemTemplate>
                        <asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("Picture") %>'></asp:TextBox>
                    </EditItemTemplate>
                    <ItemTemplate>
                        <asp:Image ID="Image1" runat="server" ImageUrl='<%#"ImageHandler.ashx?CategoryID="+ Eval("CategoryID")  %>'/>
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
            <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
            <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
            <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
            <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
            <EditRowStyle BackColor="#2461BF" />
            <AlternatingRowStyle BackColor="White" />
        </asp:GridView>
        <asp:SqlDataSource ID="SqlDataSource1" runat="server"
            ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>"
            SelectCommand="SELECT * FROM [Categories]"></asp:SqlDataSource>
   
    </div>

after that run your website

Hope this helps

Good Luck.

Categories: ASP.Net, Linq

Gridview Paging with Linq

February 11, 2010 9 comments

Hi

try this example for Gridview Paging using Linq to SQL

Step1 :- Open MS VS2008 and create a new website

Step2 :- In solution Explorer right cleck and select add new item and add LINQ to SQL classes and name it to “Northwind.dbml”

Step3 :- Open Northwind.dbml and Add Employees Table in Northwind Database and the Save

Step4 :- Right click on solution Explorer and add new class and name it “EmployeeDAL.cs”


using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Collections.Generic;

/// <summary>
/// Summary description for EmployeeDAL
/// </summary>
public class EmployeeDAL
{
 public EmployeeDAL()
 {
  //
  // TODO: Add constructor logic here
  //
 }

    public int GetRowsCount()
    {
        NorthwindDataContext db = new NorthwindDataContext();
        try
        {
            return db.Employees.Count();
        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message);
        }
    }

    public List<Employee> SelectAll()
    {
        NorthwindDataContext db = new NorthwindDataContext();
        try
        {
            return db.Employees.ToList<Employee>();
        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message);
        }
    }

    public List<Employee> GetDataPaging(int startRows, int maxRows)
    {
        NorthwindDataContext db = new NorthwindDataContext();
        try
        {
            return db.Employees.Skip(startRows).Take(maxRows).ToList<Employee>();
        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message);
        }
    }

    public System.Web.UI.WebControls.ObjectDataSource GetData()
    {
        try
        {
            ObjectDataSource obds = new ObjectDataSource();
            obds.TypeName = "EmployeeDAL";
            obds.SelectMethod = "GetDataPaging";
            obds.MaximumRowsParameterName = "maxRows";
            obds.StartRowIndexParameterName = "startRows";
            obds.SelectCountMethod = "GetRowsCount";
            obds.EnablePaging = true;
            return obds;
        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message);
        }
    }
}

Step5 :- In Default.aspx page add new Gridview control

    <div>
        <asp:GridView ID="GridView1" runat="server" AllowPaging="True" PageSize="5"
            AutoGenerateColumns="False" CellPadding="4" DataKeyNames="EmployeeID"
            ForeColor="#333333" GridLines="None"
            onpageindexchanging="GridView1_PageIndexChanging">
            <RowStyle BackColor="#EFF3FB" />
            <Columns>
                <asp:BoundField DataField="EmployeeID" HeaderText="EmployeeID"
                    InsertVisible="False" ReadOnly="True" SortExpression="EmployeeID" />
                <asp:BoundField DataField="FirstName" HeaderText="FirstName"
                    SortExpression="FirstName" />
                <asp:BoundField DataField="LastName" HeaderText="LastName"
                    SortExpression="LastName" />
            </Columns>
            <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
            <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
            <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
            <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
            <EditRowStyle BackColor="#2461BF" />
            <AlternatingRowStyle BackColor="White" />
        </asp:GridView>
    </div>

Step6 :- in code behind of Default.aspx.cs add the following code


using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

public partial class Default5 : System.Web.UI.Page
{
    EmployeeDAL emp = new EmployeeDAL();

    public void FillGrid()
    {
        GridView1.DataSource = emp.GetData();
        GridView1.DataBind();
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            FillGrid();
        }
    }

    protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        GridView1.PageIndex = e.NewPageIndex;
        FillGrid();
    }
}

the run your website

Hope this helps

Good Luck.

Categories: ASP.Net, Linq Tags: ,

AJAX AutoComplete with XML file

February 10, 2010 1 comment

Hi

try this example to use AJAX AutoComplete with XML file

Step1 :- Craete new AJAX Website

Step2 :- Add XML file called “countries.xml”

<?xml version="1.0" encoding="utf-8" ?>
<Items>
  <Item>Argentina</Item>
  <Item>Australia</Item>
  <Item>Austria</Item>
  <Item>Germany</Item>
  <Item>Egypt</Item>
  <Item>India</Item>
  <Item>Italy</Item>
  <Item>United States of America</Item>
</Items>

Step3 :- Add new Webservice with the following code


using System;
using System.Web;
using System.Collections;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Web.Script.Services;
using System.Collections.Generic;
using System.Xml;
using System.Data.SqlClient;
using System.Configuration;
using System.Data;

/// <summary>
/// Summary description for WebService
/// </summary>
[WebService(Namespace = "<a href="http://tempuri.org/">http://tempuri.org/</a>")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ScriptService]

public class WebService : System.Web.Services.WebService
{
    [WebMethod]
    public string[] GetItemsList(string prefixText, int count)
    {
        List<string> suggestions = new List<string>();
        using (XmlTextReader reader = new XmlTextReader(HttpContext.Current.Server.MapPath("~/Countries.xml")))
        {
            while (reader.Read())
            {
                if (reader.NodeType == XmlNodeType.Element && reader.Name == "Item")
                {
                    string itemName = reader.ReadInnerXml();
                    if (itemName.StartsWith(prefixText,StringComparison.InvariantCultureIgnoreCase))
                    {
                        suggestions.Add(itemName);

                        if (suggestions.Count == count) break;
                    }
                }
            }
        }
        return suggestions.ToArray();
    }
}

Step4 :- Add new web page and drag Script Manager , TextBox , and AJAX Autocomplete controls on the page

  <asp:ScriptManager ID="ScriptManager1" runat="server">
        </asp:ScriptManager>
        <br />
        Select Country :-<asp:TextBox ID="txt_Items" runat="server"></asp:TextBox>
        <cc1:AutoCompleteExtender ID="AutoCompleteExtender1" runat="server" TargetControlID="txt_Items"
        ServiceMethod="GetItemsList" MinimumPrefixLength="1" CompletionSetCount="10" EnableCaching="true"
        ServicePath="WebService.asmx">
        </cc1:AutoCompleteExtender>

Hope this helps

Good Luck.

Categories: AJAX, ASP.Net

Change GridView Cell Color According to Condition

February 6, 2010 Leave a comment

Hi

try this example to Change GridView Cell Color According to Condition

Step1 : Create Database which contains a table called “Projects” with the following schema

  • Id –> int (Primary Key)
  • Name –> nvarchar
  • Status –> nvarchar (Can be Open or Closed)

Step2 :- Create a new website and add new web page and drag SQLDataSource and Gridview Control

        <asp:GridView ID="GridView1" runat="server" AllowPaging="True" AutoGenerateColumns="False"
            CellPadding="4" DataKeyNames="Id" DataSourceID="SqlDataSource1" ForeColor="#333333"
            OnRowDataBound="GridView1_RowDataBound">
            <RowStyle BackColor="#EFF3FB" />
            <Columns>
                <asp:BoundField DataField="Id" HeaderText="Id" InsertVisible="False" ReadOnly="True"
                    SortExpression="Id" />
                <asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" />
                <asp:BoundField DataField="Status" HeaderText="Status" SortExpression="Status" />
            </Columns>
            <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
            <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
            <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
            <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
            <EditRowStyle BackColor="#2461BF" />
            <AlternatingRowStyle BackColor="White" />
        </asp:GridView>
        <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
            SelectCommand="SELECT * FROM [Projects]"></asp:SqlDataSource>

and in code behind :

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            if (e.Row.Cells[2].Text == "Open")
            {
                //e.Row.BackColor = System.Drawing.Color.Red;
                e.Row.Cells[2].BackColor = System.Drawing.Color.Red;
            }
            if (e.Row.Cells[2].Text == "Closed")
            {
                //e.Row.BackColor = System.Drawing.Color.Green;
                e.Row.Cells[2].BackColor = System.Drawing.Color.Green;
            }
        }
    }

Hope this helps

Good Luck

Categories: ASP.Net