Click here to Skip to main content
15,867,453 members
Articles / Web Development / ASP.NET
Tip/Trick

Fire TextBox TextChanged Event from GridView

Rate me:
Please Sign up or sign in to vote.
4.80/5 (7 votes)
8 Oct 2013CPOL3 min read 85.2K   8   1
Fire TextBox TextChanged event from GridView

Introduction

In this tip, I will show you how to fire textbox textchanged event from GridView.

Many developers are faced with this problem of how to fire the textbox textchanged event within gridview. Firing an event of one control which is present in another control is known as event bubbling.

Background

Here, I have used C# code in the background, Ajax and ASP.NET controls. You need a little knowledge of C# code, AJAX and ASP.NET controls. Normally, we can't fire the Textbox TextChanged event which is present within the gridview control. The solution to this problem can be achieved by using Ajax Update Panel control. The Update Panel Control contains two tags that are <Content Template> and another one is <Triggers>.

In the Content template, we put the control which needs to be updated, i.e., the control which is present in the update panel is being updated asynchronously. Update panel holds controls which are processed when the triggering event of that update panel is fired.

Using the Code

To start with, add the Gridview control to your page, then add three template columns: in each template control, we have a item template control and in each item template control, we have a textbox control. The three TextBox ids are as follows:

  1. TxtName
  2. TxtId
  3. TxtCategoryId

In this post, I have fired the TextChanged event of the textbox control that contains id('TxtId'). Now set the AutoPostBack property to "True" for the TextBox (TxtId), and create the TextChanged event. I have used two Update Panels. The Id of the two Update Panels is as follows:

  1. Up1 (The gridview control is placed in Update Control Up1)
  2. UpId (The textbox control 'TxtId' is placed in Update Control UpId)

We have to set the properties of update control. The properties are: UpdateMode and ChildrenAsTriggers.

Please follow the code below.

The ASP code looks like this:

ASP.NET
 <html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <asp:ScriptManager ID="sm1" runat="server"></asp:ScriptManager>
    <asp:UpdatePanel ID="Up1" runat="server" 
    UpdateMode="Conditional" ChildrenAsTriggers="true">
    <ContentTemplate>
    <asp:GridView  ID="grdResult" runat="server" 
    AutoGenerateColumns="false" 
            AutoGenerateSelectButton="true" 
            onrowcommand="grdResult_RowCommand" 
            onrowdatabound="grdResult_RowDataBound" >
    <Columns>
    <asp:TemplateField HeaderText="Title">
    <ItemTemplate>
    <asp:TextBox ID="TxtName" runat="server" 
    Text='<%#Bind("Name") %>'></asp:TextBox>
    </ItemTemplate>
    
    </asp:TemplateField>

    <asp:TemplateField HeaderText="ID">
    
    <ItemTemplate>
    <asp:UpdatePanel runat="server" ID="UpId" 
    UpdateMode="Conditional" ChildrenAsTriggers="true">
    <ContentTemplate>
    <asp:TextBox ID="TxtId" runat="server" 
    Text='<%#Bind("Id") %>' OnTextChanged="TxtId_TextChanged" 
    AutoPostBack="true"></asp:TextBox>
    </ContentTemplate>
    
    </asp:UpdatePanel>
    </ItemTemplate>

    </asp:TemplateField>
    <asp:TemplateField HeaderText="Category">
    <ItemTemplate>
    <asp:TextBox ID="TxtCategoryId" runat="server" 
    Text='<%#Bind("CategoryId") %>'></asp:TextBox>
    </ItemTemplate>

    </asp:TemplateField>
    
    </Columns>
    </asp:GridView>

  
    </ContentTemplate>
     
    </asp:UpdatePanel>
  
    </div>
    </form>
</body>
</html>   

The source behind code is as follows:

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

public partial class ShowGridDataSource : System.Web.UI.Page
{
    DataTable _table=null;
    DataTable _tempTable=null;
    DataRow row = null;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            _table = new DataTable();
            _tempTable = new DataTable();
            _tempTable.Columns.Add("Name");
            _tempTable.Columns.Add("Id");
            _tempTable.Columns.Add("CategoryId");
            SqlConnection con = new SqlConnection
            (@"Data Source=.\SQLEXPRESS;AttachDbFilename=
            D:\My Programs Practise\GridViewAllFunction\App_Data\GuestBookDB.mdf;
            Integrated Security=True;User Instance=True");
            SqlCommand cmd = new SqlCommand("select name,Id,
            CategoryId from MovieCategories", con);
            con.Open();
            SqlDataReader sdr = cmd.ExecuteReader();
            _table.Load(sdr);
            sdr.Close();
            con.Close();
            if (_table.Rows.Count > 0)
            {
                for (int i = 0; i < _table.Rows.Count; i++)
                {
                    row = _tempTable.NewRow();
                    row["Name"] = _table.Rows[i]["name"];
                    row["Id"] = _table.Rows[i]["Id"];
                    row["CategoryId"] = _table.Rows[i]["CategoryId"];
                    _tempTable.Rows.Add(row);
                }

                grdResult.DataSource = _tempTable;
                grdResult.DataBind();
            }
            //Label lbl = (Label)grdResult.Rows[0].FindControl("lblresult");
            //lbl.Text = "hello";
            Up1.Update();
        }
    }

    protected void TxtId_TextChanged(object sender, EventArgs e)
    {
        GridViewRow currentRow = (GridViewRow)((TextBox)sender).Parent.Parent.Parent.Parent;
        TextBox txt = (TextBox)currentRow.FindControl("TxtId");
        Int32 count = Convert.ToInt32(txt.Text);
        txt.Text = Convert.ToString(count + 10);
 
    }
    protected void grdResult_RowCommand(object sender, GridViewCommandEventArgs e)
    {

    }
    protected void grdResult_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            
        }
    }
} 

Here I bind the DataSource of GridView with a DataTable which is accessing data from the database. After that, I placed the gridview within an Update Panel (up1) and set its UpdateMode property="Conditional" and ChildrenAsTriggers="true". Then I created columns and within columns I created template field and then placed item template field in it and within the item template I placed the textbox controls. But as you can see above, the textbox with id(TxtId) which contains the TextChanged Event is being placed in another UpdatePanel so the TextChanged Event can be called.

After that, in the code behind page, I called the up1.update() method which will update all the ChildControls which are present in that UpdatePanel(up1).

As you run this Page and then change the text of TxtID and press Tab or click on the page, the text of the TxtId will change automatically with an increment of 10, i.e., at the first time the TxtId text is equal to 1 and you change 1 to 2, then it will show you 12.

That's it...

Thank's for reading. I hope this tip will help you.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
India India
Hi Guys,

I am Saurav Ray have done M.C.A from Inder prastha Enginnering College and currently working as a Software Developer on .Net Technologies from the last 2 year.

Comments and Discussions

 
GeneralMy vote of 5 Pin
muratcantuna9-Oct-13 3:51
muratcantuna9-Oct-13 3:51 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.