Adsence750x90

Sunday, September 19, 2010

Delete Data in GridView Using Template Button

This article explain how to delete data from GridView using Template Buttons

Now we look how to add template button in GridView.
first select Edit Columns in GridView.



2nd add template column in GridView.



Now configuring template column, Click Edit Template. Place a LinkButton on Template field. Click Edit Databindings , then select CommandArgument , after that set field binding, bound to "ID" field, this ID field is used to delete data in server side code. Then press ok button.






Now we can configure LinkButton [ Delete button ].
Select Property of Link button. set CommandName and Text as Delete.
We can access this CommandName in GridView1_RowCommand event. After this add GridView events GridView1_RowCommand and GridView1_RowDeleted






The RowDeleted event is raised whenever a Delete button associated with an item in the GridView control is clicked, but after the GridView control deletes the record.

This allows you to provide an event-handling method that performs a custom routine, such as checking the results of a delete operation, whenever this event occurs. To avoid errors we add one custom code in GridView1_RowDeleted event

//handling gridview delete excetion
        e.ExceptionHandled = true;



Now the server side part.


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

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

    }
    protected void GridView1_RowDeleted(object sender, GridViewDeletedEventArgs e)
    {
        //handling gridview delete excetion
        e.ExceptionHandled = true;
    }
    protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "dele")
        {
            //database Helper
            DBHelper objDBHelper = new DBHelper();
            //sql command to delete data from database
            string sqlCmdText = string.Format("DELETE FROM Table WHERE ID='{0}'", e.CommandArgument.ToString());
            //Executeing sql command
            objDBHelper.ExecuteScalar(sqlCmdText);
            //refresh gridview
            GridView1.DataBind();

        }
    }
}



ASPX Page



<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default3.aspx.cs" Inherits="Default3" %>
<!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" runat="server" AutoGenerateColumns="False"
            DataSourceID="SqlDataSource1" onrowcommand="GridView1_RowCommand"
            onrowdeleted="GridView1_RowDeleted">
            <Columns>
                <asp:BoundField DataField="biInvitationId" HeaderText="biInvitationId"
                    InsertVisible="False" ReadOnly="True" SortExpression="biInvitationId" />
                <asp:BoundField DataField="biEventName" HeaderText="biEventName"
                    SortExpression="biEventName" />
                <asp:BoundField DataField="biHostName" HeaderText="biHostName"
                    SortExpression="biHostName" />
                <asp:BoundField DataField="biTelephone" HeaderText="biTelephone"
                    SortExpression="biTelephone" />
                <asp:TemplateField>
                    <ItemTemplate>
                        <asp:LinkButton ID="LinkButton1" runat="server"
                            CommandArgument='<%# Eval("biInvitationId") %>' CommandName="dele">Delete</asp:LinkButton>
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
        </asp:GridView>
        <asp:SqlDataSource ID="SqlDataSource1" runat="server">
        </asp:SqlDataSource>
    </div>
    </form>
</body>
</html>

Thank you,

Feel free to comment.



.

Saturday, September 4, 2010

Select GridView Row without using Select button

This code snippet Illustrate How to Select GridView Row without using Select Command button.
I think code can do better idea than description. check the snippet.


protected void Button1_Click(object sender, EventArgs e)
    {
        //identifying button
        Button gridBtn = (Button)sender;
       //selecting grid row
        GridViewRow gridRow = (GridViewRow)gridBtn.NamingContainer;
       //setting Index
        int selectedIndex = gridRow.DataItemIndex;
       // Setting Selected Index of GridView1
         GridView1.SelectedIndex = selectedIndex;
        //firing selected Index changed if you need
        //here I used to change color of selected rows
         GridView1_SelectedIndexChanged(GridView1, EventArgs.Empty);
        if (gridBtn != null)
        {
           //changing button text[/color]
            if (gridBtn.Text == "DeSelect")
            { gridBtn.Text = "Select"; }
            else
            { gridBtn.Text = "DeSelect"; }
        }

    }
    protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
    {
        int sIndex = GridView1.SelectedIndex;
        if (GridView1.Rows[sIndex].BackColor == System.Drawing.Color.Red)
        {
            GridView1.Rows[sIndex].BackColor = System.Drawing.Color.White;
        }
        else
        {
            GridView1.Rows[sIndex].BackColor = System.Drawing.Color.Red;
        }

    }


ASPX section

I add One Button field as Template field. and add Button text as "Select". when you click on select button in GridView, the selected Row become Red color.

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
            DataSourceID="SqlDataSource1">
            <columns>
                <asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" />
                <asp:BoundField DataField="Category" HeaderText="Category"
                    SortExpression="Category" />
                <asp:BoundField DataField="Tags" HeaderText="Tags" SortExpression="Tags" />
                <asp:TemplateField>
                    <itemtemplate>
                        <asp:Button ID="Button1" runat="server" Text="Select" onclick="Button1_Click" />
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
        </asp:GridView>


Preview of Output
You can Select or Deselect GridView Rows.






Thank you for Reading this code snippet.
Feel Free to comment. if you have any doubts let me know.

Thursday, September 2, 2010

Ajax AutoComplete in ASP.Net

Without using AjaxControlToolKit we can implement AutoComplete Extender using pure Ajax Call. This article is explaining how to do make AutoComplete Extender.
OnKeyUp event help you to fetch data from Database with Ajax call. Here one Handler.ashx handles the AJAX request form Client. I add a Class file to handle database operations to better coding practice. Below I am explaining the database helper Class. Class have one method GetTable(string sqlQuery) this return DataTable after fetching data from database. And also include Provide Class, this Class help to get SqlConnection string.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.SqlClient;
using System.Configuration;
using System.Data;
/// 
/// Summary description for DBHelper
/// 
public class DBHelper
{
    SqlConnection connection;
    SqlDataAdapter adapter;
    SqlCommand command;
    DataTable dataTable;
    public DBHelper()
    {
    }
    /// 
    /// 
    /// 
    /// passing SQL Query here/// DataTable object is returned
    public DataTable GetTable(string sqlQuery)
    {
        //creating new instance of Datatable
        dataTable = new DataTable();
        connection = Provider.GetConnection();
        command = new SqlCommand(sqlQuery, connection);
        //Open SQL Connection
        connection.Open();
            try
            {
                adapter = new SqlDataAdapter(command);
                adapter.Fill(dataTable);
            }
            catch
            { }
            finally
            {
                //Closing Sql Connection 
                connection.Close();
            }
        return dataTable;
    }
}
public class Provider
{
    public static SqlConnection GetConnection()
    {
        //creating SqlConnection
        return new SqlConnection(ConfigurationManager.AppSettings["sqlConn"]);
    }
} 



Now we can look into Handler file. When request come from Ajax Call from Client it passes the data into our Database helper Class, handler file hold the data in DataTable. Result data are formatted in a table and write in the context. We can add JavaScript function for select the data, here api_helper.AddtoTaxtBox(selectedItem)is managing client section of data. Check Handler file



<%@ WebHandler Language="C#" Class="Handler" %>
using System;
using System.Web;
using System.Data;
public class Handler : IHttpHandler {
    public void ProcessRequest (HttpContext context) {

        HttpRequest request = HttpContext.Current.Request;
        //checking string null or empty
        if (!string.IsNullOrEmpty(request.QueryString["name"]))
        {
            string name=request.QueryString["name"];
            //creating instance of new database helper
            DBHelper objDBHelper = new DBHelper();
            //creating Sql Query
            string sqlQuery = string.Format("SELECT Name FROM User WHERE Name LIKE '{0}%'", name);
            //filling data from database
            DataTable dataTable = objDBHelper.GetTable(sqlQuery);

            string table = string.Empty;
            //table for hold data
            table = "";             string td = string.Empty;             //checking datatable                 if (dataTable.Rows.Count > 0)                 {                     for (int i = 0; i < dataTable.Rows.Count; i++)
                    {
                        //adding table rows
                        td += string.Format("
", dataTable.Rows[i][0].ToString());                     }                 }                 table += td + "
{0}
"; context.Response.Write(table); } } public bool IsReusable { get { return false; } } }

Now we can check how Ajax works. On Textbox onKeyUp event call the ajax code. It send the entered value into server using ajax and result displayed in div control under the search textbox.


<%@ 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></title>

<style type="text/css">
      .select{cursor:pointer;height:20px;color:red;}
      .select:hover{cursor:pointer;height:20px;color:black;background-color:#cccccc;}
      #myDiv{position:relative;top: -1px; left: 0px;width:150px; overflow:hidden;}
      #txtName{width:150px}
</style>

</head>
<body>
<form id="form1" runat="server">
<div>

<asp:TextBox ID="txtName" runat="server" onkeyup="api_helper.callAjax();"></asp:TextBox>
<div id="myDiv"></div>


<script language="javascript" type="text/javascript">

            if (typeof (api_helper) == 'undefined') { api_helper = {} }


            api_helper.doAjax = function(HandlerUrl, displayDiv) {
                var Req; try { Req = new XMLHttpRequest(); } catch (e) { try { Req = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try { xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) { return false; } } } Req.onreadystatechange = function() { if (Req.readyState == 4) { var d = document.getElementById(displayDiv); d.innerHTML = Req.responseText; } }
                Req.open("GET", HandlerUrl, true); Req.send(null);
            }


            api_helper.callAjax = function() {
                var text = document.getElementById("txtName").value;
                if (text != "") {
                    var requestUrl = "Handler.ashx?name=" + text;
                    var displayDiv="myDiv";
                    api_helper.doAjax(requestUrl, displayDiv);
                }
            }


            api_helper.AddtoTaxtBox = function(txt) {
                document.getElementById("txtName").value = txt;
                document.getElementById("myDiv").innerHTML = "";
            }
</script>
</div>
</form>
</body>
</html>



Thanks for reading this article and feel free to comment.
Tags Ajax AutoComplete, Ajax Example.