Thursday, July 10, 2014

Search Gridview Rows Based On Header Text Box Values Using OntextChanged And Like Command


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

<!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="grd" AutoGenerateColumns="False" runat="server" BackColor="#DEBA84"
            BorderColor="#DEBA84" BorderStyle="None" BorderWidth="1px" CellPadding="3" CellSpacing="2">
            <Columns>
                <asp:TemplateField HeaderText="id">
                    <HeaderTemplate>
                        <asp:TextBox ID="txtid" runat="server" OnTextChanged="ontxtid" AutoPostBack="true"></asp:TextBox>
                    </HeaderTemplate>
                    <ItemTemplate>
                        <asp:Label ID="lblid" runat="server" Text='<%#bind("id") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="fname">
                    <HeaderTemplate>
                        <asp:TextBox ID="txtfname" runat="server" OnTextChanged="ontxtfname" AutoPostBack="true"></asp:TextBox>
                    </HeaderTemplate>
                    <ItemTemplate>
                        <asp:Label ID="lblfname" runat="server" Text='<%#bind("fname") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="lname">
                    <HeaderTemplate>
                        <asp:TextBox ID="txtlname" runat="server" OnTextChanged="ontxtlname" AutoPostBack="true"></asp:TextBox>
                    </HeaderTemplate>
                    <ItemTemplate>
                        <asp:Label ID="lblnamel" runat="server" Text='<%#bind("lname") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Description">
                    <HeaderTemplate>
                        <asp:TextBox ID="txtdes" runat="server"></asp:TextBox>
                    </HeaderTemplate>
                    <ItemTemplate>
                        <%# Eval("description").ToString().Replace("&","</br>")%>
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
            <FooterStyle BackColor="#F7DFB5" ForeColor="#8C4510" />
            <HeaderStyle BackColor="#A55129" Font-Bold="True" ForeColor="White" />
            <PagerStyle ForeColor="#8C4510" HorizontalAlign="Center" />
            <RowStyle BackColor="#FFF7E7" ForeColor="#8C4510" />
            <SelectedRowStyle BackColor="#738A9C" Font-Bold="True" ForeColor="White" />
            <SortedAscendingCellStyle BackColor="#FFF1D4" />
            <SortedAscendingHeaderStyle BackColor="#B95C30" />
            <SortedDescendingCellStyle BackColor="#F1E5CE" />
            <SortedDescendingHeaderStyle BackColor="#93451F" />
        </asp:GridView>
    </div>
    </form>
</body>
</html>

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

public partial class grid : System.Web.UI.Page
{
    string xxx = ConfigurationManager.ConnectionStrings["aaa"].ToString();
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            SqlConnection con = new SqlConnection(xxx);
            SqlCommand cmd = new SqlCommand("select * from Des");
            cmd.Connection = con;
            SqlDataAdapter dap = new SqlDataAdapter(cmd);
            DataSet ds = new DataSet();
            dap.Fill(ds);
            grd.DataSource = ds;
            grd.DataBind();
            //return ds;
           
        }
    }
    protected void ontxtid(object sender, EventArgs e)
    {

        if (grd.HeaderRow != null)
        {
            TextBox txti = (TextBox)grd.HeaderRow.FindControl("txtid");
            SqlConnection con = new SqlConnection(xxx);
            SqlCommand cmd = new SqlCommand("select * from des where id like '" + txti.Text + "%'");
            cmd.Connection = con;
            SqlDataAdapter dap = new SqlDataAdapter(cmd);
            DataSet ds = new DataSet();
            dap.Fill(ds);
            grd.DataSource = ds;
            grd.DataBind();

        }
    }
    protected void ontxtfname(object sender, EventArgs e)
    {

        if (grd.HeaderRow != null)
        {
            TextBox txtf = (TextBox)grd.HeaderRow.FindControl("txtfname");
            //TextBox txti = (TextBox)grd.HeaderRow.FindControl("txtid");
            SqlConnection con = new SqlConnection(xxx);
            SqlCommand cmd = new SqlCommand("select * from des where fname like '" + txtf.Text + "%'");
            cmd.Connection = con;
            SqlDataAdapter dap = new SqlDataAdapter(cmd);
            DataSet ds = new DataSet();
            dap.Fill(ds);
            grd.DataSource = ds;
            grd.DataBind();
        }
    }
    protected void ontxtlname(object sender, EventArgs e)
    {

        if (grd.HeaderRow != null)
        {
            TextBox txtl = (TextBox)grd.HeaderRow.FindControl("txtlname");
            //TextBox txti = (TextBox)grd.HeaderRow.FindControl("txtid");
            SqlConnection con = new SqlConnection(xxx);
            SqlCommand cmd = new SqlCommand("select * from des where lname like '" + txtl.Text + "%'");
            cmd.Connection = con;
            SqlDataAdapter dap = new SqlDataAdapter(cmd);
            DataSet ds = new DataSet();
            dap.Fill(ds);
            grd.DataSource = ds;
            grd.DataBind();
        }
    }

 
}
 ----------------------------------------------------------------------------------
<connectionStrings>
              <add name="aaa" connectionString="Data Source=KCLINK-45-PC\SQLEXPRESS;Initial Catalog=naresh;Integrated Security=True" providerName="System.Data.SqlClient"/>
       </connectionStrings>
       <system.web>
<connectionStrings>

----------------------------------------------------------------------------
CREATE TABLE [dbo].[des](
      [id] [int] IDENTITY(1,1) NOT NULL,
      [fname] [varchar](50) NULL,
      [lname] [varchar](50) NULL,
      [description] [varchar](200) NULL,
 CONSTRAINT [PK_des] PRIMARY KEY CLUSTERED
(
      [id] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

SET ANSI_PADDING OFF
GO


Wednesday, July 9, 2014

Create DataTable dynamically and bind to GridView in ASP.Net

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

<!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="GridView1" HeaderStyle-BackColor="#3AC0F2" HeaderStyle-ForeColor="White"
    runat="server" AutoGenerateColumns="false">
    <Columns>
        <asp:BoundField DataField="Id" HeaderText="Id" ItemStyle-Width="30" />
        <asp:BoundField DataField="Name" HeaderText="Name" ItemStyle-Width="150" />
        <asp:BoundField DataField="Country" HeaderText="Country" ItemStyle-Width="150" />
    </Columns>
</asp:GridView>
    </div>
    </form>
</body>
</html>

 ---------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;

public partial class grdview : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!this.IsPostBack)
        {
            DataTable dt = new DataTable();
            dt.Columns.AddRange(new DataColumn[3] { new DataColumn("Id", typeof(int)),
                            new DataColumn("Name", typeof(string)),
                            new DataColumn("Country",typeof(string)) });
            dt.Rows.Add(1, "Naresh", "India");
            dt.Rows.Add(2, "XXX", "India");
            dt.Rows.Add(3, "AAAA", "France");
            dt.Rows.Add(4, "MMMMM", "Russia");
            GridView1.DataSource = dt;
            GridView1.DataBind();
        }
    }
 
}


Displaying Column Data in Gridview With new line Separated By Symbol like ., @,&,#


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

<!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="grd" AutoGenerateColumns="false" runat="server" 
            DataKeyNames="description"
            onrowdatabound="Unnamed1_RowDataBound">
            <Columns>
                <asp:TemplateField HeaderText="id">
                    <ItemTemplate>
                        <asp:Label ID="lbl" runat="server" Text='<%#bind("id") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="fname">
                    <ItemTemplate>
                        <asp:Label ID="lbl" runat="server" Text='<%#bind("fname") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="lname">
                    <ItemTemplate>
                        <asp:Label ID="lbl" runat="server" Text='<%#bind("lname") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Description">
                    <ItemTemplate>
                        <%# Eval("description").ToString().Replace("&","</br>")%>
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
        </asp:GridView>
    </div>
    </form>
</body>
</html>
 -----------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;

public partial class grid : System.Web.UI.Page
{
    string xxx = ConfigurationManager.ConnectionStrings["aaa"].ToString();
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            SqlConnection con = new SqlConnection(xxx);
            SqlCommand cmd = new SqlCommand("select * from Des");
            cmd.Connection = con;
            SqlDataAdapter dap = new SqlDataAdapter(cmd);
            DataSet ds = new DataSet();
            dap.Fill(ds);
            grd.DataSource = ds;
            grd.DataBind();
            //return ds;
           
        }
    }

 
}



ADO.NET Data Containers

DataAdapter
In ADO.NET, the data adapter object acts as a two-way bridge between a data source and the DataSet object. 
The DataSet is a disconnected container of data, and the adapter takes care of filling it and submitting its data back to a particular data source. 
From an abstract point of view, a data adapter is similar to a command and represents another way of executing a command against the data source. 
The big difference between commands and data adapters is just in the way each one returns the retrieved data. A query command returns a read-only, forward-only cursor—the data reader. The data adapter performs its data access, grabs all the data, and packs it into an in-memory  container—the DataSet or DataTable. 
DataSet
The dataset is a disconnected, in-memory representation of data. It can be considered as a local copy of the relevant portions of the database. The DataSet is persisted in memory and the data in it can be manipulated and updated independent of the database. When the use of this DataSet is finished, changes can be made back to the central database for updating. The data in DataSet can be loaded from any valid data source like Microsoft SQL server database, an Oracle database or from a Microsoft Access database.
Inside a DataSet, much like in a database, there are tables, columns, relationships, constraints, views, and so forth.
The ADO.NET DataSet is the core component of the disconnected architecture of ADO.NET. The DataSet is explicitly designed for data access independent of any data source. As a result it can be used with multiple and differing data sources, used with XML data, or used to manage data local to the application. The DataSet contains a collection of one or more DataTable objects made up of rows and columns of data, as well as primary key, foreign key, constraint, and relation information about the data in the DataTable objects.

Command Builder & DataTable

The ADO.NET object model not only allows you to define your own updating logic, but it also provides a dynamic updating logic generation similar to that of the ADO cursor engine, using the CommandBuilder object.  If you instantiate a CommandBuilder object and associate it with a DataAdapter object, the CommandBuilder will attempt to generate updating logic based on the query contained in the DataAdapter object’s SelectCommand.
The CommandBuilder can generate updating logic if all the following are true:
·          Your query returns data from only one table
·          That table has a primary key
·          The primary key is included in the results of your query
The disadvantages with using the CommandBuilder are: 
 ·          It doesn’t offer the best possible run-time performance.
·          You can supply your own updating logic in code in less time than it takes the CommandBuilder to request and process the metadata required to generate similar updating logic.
·          The CommandBuilder doesn’t offer options to let you control the updating logic that is generated.
·          You can’t specify the type of optimistic concurrency you want to use. 
A CommandBuilder will not help you submit updates using stored procedures.

Command Builder Example:
public static DataSet SelectSqlRows(string connectionString,
    string queryString, string tableName)
{
    using (SqlConnection connection = new SqlConnection(connectionString))
    {
        SqlDataAdapter adapter = new SqlDataAdapter();
        adapter.SelectCommand = new SqlCommand(queryString, connection);
        SqlCommandBuilder builder = new SqlCommandBuilder(adapter);

        connection.Open();

        DataSet dataSet = new DataSet();
        adapter.Fill(dataSet, tableName);

        //code to modify data in DataSet here

        builder.GetUpdateCommand();

        //Without the SqlCommandBuilder this line would fail
        adapter.Update(dataSet, tableName);

        return dataSet;
    }
}

A DataSet object is made up of a collection of tables, relationships, and constraints.  In ADO.NET, DataTable objects are used to represent the tables in a DataSet object.  A DataTable object represents one table of in-memory relational data.  The data is local to the .NET application in which it resides, however, can be populated from a data source such as SQL Server or VFP using a DataAdapter.
You can create and use a DataTable independently or as a member of a DataSet object.  DataTable objects can then be used by other .NET Framework objects, including the DataView object.  Access the collection of tables in a DataSet object through the DataSet object’s Tables property.
The schema, or structure, of a table is represented by columns and constraints.  Define the schema of a DataTable object using DataColumn objects, as well as ForeignKeyConstraint and UniqueConstraint objects.  The columns in a table can map to columns in a data source, contain calculated values from expressions, automatically increment their values, or contain primary key values.
If you populate a DataTable object from a database, it will inherit the constraints from the database so you do not have to do all of the work manually.  A DataTable object must also have rows in which to contain and order the data.  The DataRow class represents the actual data contained in the table.  As you access and change the data within a row, the DataRow object maintains both its current and original state.
You can create parent/child relationships between tables within a database, like SQL Server and VFP, using one or more related columns in the tables.  You can create a relationship between DataTable objects using a DataRelation object, which may then be used to return a row’s related child or parent rows.
DataTable Example:
  // Create a DataTable with 5 columns.
    //
    DataTable table = new DataTable();
    table.Columns.Add("Weight", typeof(int));
    table.Columns.Add("Name", typeof(string));
    table.Columns.Add("Breed", typeof(string));
    table.Columns.Add("Size", typeof(char));
    table.Columns.Add("Date", typeof(DateTime));

    //
    // Add data to the DataTable. [This will be dyanmically generated from your app.]
    //
    AddDogRow(table, 57, "Koko", "Shar Pei");
    AddDogRow(table, 130, "Fido", "Bullmastiff");
    AddDogRow(table, 92, "Alex", "Anatolian Shepherd Dog");
    AddDogRow(table, 25, "Charles", "Cavalier King Charles Spaniel");
    AddDogRow(table, 7, "Candy", "Yorkshire Terrier");
/// <summary>
/// Add dog data to the DataTable.
/// </summary>
static DataRow AddDogRow(DataTable table, int weight, string name, string breed)
{
    //
    // This method uses custom code to generate the size type.
    //
    return table.Rows.Add(weight, name, breed, GetSizeChar(weight), DateTime.Now);
}

/// <summary>
/// Get size code for dogs by weight.
/// </summary>
static char GetSizeChar(int weight)
{
    //
    // Custom method for getting size code.
    //
    if (weight > 100)
    {
       return 'B';
    }
    else if (weight > 50)
    {
       return 'M';
    }
    else
    {
       return 'S';
    }
}