GridView and Javascript - how to get the ID of a control from the gridview when gridview is in edit mode.

Hey All,

 I need help from  you.

I have a GridView. In the  Edit Item template of the first Column I have a textbox, an user control and hidden field. When I click on the user control it  opens a pop up from which I can choose the required value. The text value is populated in the textbox and Id in the hidden field. Here's the code for edit template.

                        <table cellpadding ="0" cellspacing ="0">
                                    <asp:TextBox id = "txtEditKnownBy" runat ="server" ReadOnly ="true"  Text='<%# DataBinder.Eval(Container.DataItem,"userName")%>'></asp:TextBox>
                                    <uc2:ucChoose ID="UcEditChooseKnownBy" runat="server" />
                                     <asp:HiddenField id = "hdnEditKnownById" runat ="server" Value='<%# DataBinder.Eval(Container.DataItem,"userId")%>'></asp:HiddenField>

 The usercontrol textbox thing works fine if I have them outside the grid. I pass the id of textbox and hidden field using

var vFirstName = document.getElementById("<%=txtEditKnownBy.ClientID %>"); and get them populated.

The problem is when I put the textbox and usecontrol inside a grid it isn't able to find the ID using document.getElementById("<%=txtEditKnownBy.ClientID %>");

so nothing is returned and an error is thrown.

Can anybody tell me how to get the ID of a control from the gridview when gridview is in edit mode.

 Thanking You

Nitin Maheshwari 


1/30/2007 1:10:46 PM 72751 articles. 3 followers. Follow

6 Replies

Similar Articles

[PageSpeed] 42
Get it on Google Play
Get it on Apple App Store

You need to use FindControl to get to it. Try something like this.


1/30/2007 1:50:32 PM


Have you checked what id it brings when txtbox in GridView.(use ViewSource to find)

Some time you have to use uniqueID of txtbox. I hope this works for you.

 or if you want value of that txtbox just use in ItemCreated event of Grid

EditButton.Attributes.Add("Onclick","return confirm('Are you sure you want to edit this " + DataBinder.Eval(e.Item.DataItem,"userName") +"?');");


Anuj Patel
If this post answers your question please mark it as Answered.
1/30/2007 2:02:53 PM

You need to use FindControl to get to it. Try something like this.



Thanx for your reply but I want to get that clinet id in javascript not in code behind.

I am doing some validations before post back.  

1/31/2007 6:02:46 AM


Have you checked what id it brings when txtbox in GridView.(use ViewSource to find)

Some time you have to use uniqueID of txtbox. I hope this works for you.

 or if you want value of that txtbox just use in ItemCreated event of Grid

EditButton.Attributes.Add("Onclick","return confirm('Are you sure you want to edit this " + DataBinder.Eval(e.Item.DataItem,"userName") +"?');");



I have checked that. That works but I don't want to hardcore the Id's so is there any other way 

1/31/2007 6:11:05 AM


If you need to access the Textbox in the javascript you could not directly get it by

var vFirstName = document.getElementById("<%=txtEditKnownBy.ClientID %>");

But, as this textbox is inside the Gridview, you need to get it by getting the gridview, and the editindex. Depending upon the editindex you could go to that row and get the cell in which the textbox is present and get it from the controls.

You can use the below code,

// Get the GridView
var GridView = document.getElementById('<%= gvData.ClientID %>');
// Get the EditIndex from a hidden variable
var EditIndex = document.getElementById('<%= hidEditIndex.ClientID %>').value;
// Now go to the EditIndex row and loop throgh the control collection to get the Textbox
var FirstName = GridView.rows[EditIndex].cells[ColumnNo].children[0]; 
// This will give you the first element in that cell, ie the TextBox
// To access the Hiddenvariable, which is the third element in the cell, we nned to use
var HiddenValue = GridView.rows[EditIndex].cells[ColumnNo].children[2]; 
 Hope it helps you.
My Blog
If this post answers your question please mark it as Answered.
1/31/2007 1:06:57 PM

I usually use Literal controls to populate variables in my javascript code. like this.

// get the javascript reference to the object. 
var tb = document.getElementById('<asp:Literal runat="server" ID="lit_textBoxId" />");


Then in the RowEditing event of the gridview add this code.


Sub gv_RowEditing(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewEditEventArgs) Handles Gridview1.RowEditing

Me.lit_textBoxId.Text = Me.Gridview1.Rows(e.NewEditIndex).FindControl("txtEditKnownBy").ClientId

End Sub

2/1/2007 12:01:55 AM

Similar Artilces:

using javascript getting value from textbox when edit button is clicked and both controls are present in gridview control
Hi All using javascript I want to get value  from textbox when edit button is clicked and both controls that is texbox and button are present in gridview control .Alok Hi aloksinha83, Please see this post: Thanks,Qin Dian TangMicrosoft Online Community SupportPlease remember to mark the replies as answers if they help and unmark them if they provide no help....

Getting the control id of a control inside gridview control
 uhmm.. a little bit confusing regarding my subject because i dont know how to say the way my problem is how can i get the id of a control (e.g. textbox) inside the gridview... and the textbox is in the templatefield... is there any way i can get its id??  hoping i could get a reply as soon as possible... Regards,MhaeyPlease remember to click “Mark as Answer” on the post that helps you.. =) What do you want's to do by getting the id of the Text box? Do you want's to find particular Textbox with certain id ? Kamran ShahidSr. Software Engineer(MCP,,MC...

gridview control in another gridview control
Hi ia have a questioni have a gridview control which contains button in one my question is i need another gridview to be placed in the  first gidviewso that when i click on the button the second gridview will populate the my question is how to place second gridview in first gridview.or is there any approach like first grid itself acting as parent and child.please help me  Hi sirikalavalapalli:                I think nested gridview will help you. Check this link and it will show you how...

Add new controls to a gridview row; when editing that row using the edit row feature in the gridview control.
Hi all  I have a questions that looks hard / complex to me, and i know you can help me in this. Q {  I have row in a Gridview and i have an edit option to it. I press the edit button, to edit the values in that row and update data all the way back to the database. Now when i press the edit button, i want a drop down list to be displayed that contain values for a particular field in my grid view. (for now only plain text boxes appear.) } I hope you understand my question, all i need to do is replace the text box controls with a dropdown list when i am editing a row in ...

GridView child of GridView
I have a Parent GridView and when you click in the Edit one of the columns has a Template Field which has a Child GridView. When you click Edit on the Child GridView I have a Template Field that has a TextBox. How to I retreive this value of the TextBox? GridViewParent-- GridViewChild (Edit - Template Field containing this GridViewChild)----- TextBox inside Template Field in GridViewChild. Thank you.Peace in ChristMarco Napoli What you can do as a solution is to override the RowDataBound and try to find the child GridView control. Once you get a reference to...

Gridview control embedded in another gridview control
I am writing an ambulance crew scheduling application on the web and I need some help completing the last part.  I have an access database that has three tables: user table, shift table (describing the shifts available), and a schedule table (that stores shift by shift_id and user by user_id).  I have a gridview control that will display the available shifts but I cannot get the embedded gridview control that will display the user that is signed up for each shift to display because I cannot figure out how to use the OnRowDataBound method.  I need a simple VB example of how to...

There is a Gridview Control in the tmplate field of another GridView Control.
    For instance,a gridview displays the information of the  students in a class.A table is recording the information except their mark.There is another table recording the mark of the students whose foreign key is the primary key of the previous table.   string strSQLconnection=".................."; SqlConnection sqlCononection=new SqlConnection(strSQLconnection); SqlCommand sqlCommand=new SqlCommand("select * from stuendent where classID=1",sqlConnection); SqlConnection.Open(); SqlDataReader reader=sqlCommand.ExecuteReader(); GridVie...

Handling control events while in edit mode for a gridview control
I have a dropdownlist and checkbox in a single column of a gridview. While the row is in edit mode, I want to set the visibility of the checkbox based on the value selected in the dropdown list. I can do this easily enough  when the row is first put into edit mode, but how do I access the dropdown list's change event when the row is already sitting there in edit mode? Thanks for any help you can provide.   Penny Penny, Just create a SelectedIndexChanged event like below. Create a row object for the currently edited row, find the checkbox you want to control, then set the Visib...

Trying to use the FAQ " Sorting and paging in the GridView control when not using data source controls "Sorting and paging in the GridView control when not using..."
and I am not getting the results I had hoped for.  I keep getting a "Compiler Error Message: CS0123: No overload for 'AdhocJobGridView_PageIndexChanged' matches delegate 'System.EventHandler'".   Here is my event handling... protected void AdhocJobGridView_PageIndexChanged(object sender, GridViewPageEventArgs e){ try { AdhocJobGridView.DataSource = wsBaseInfoArray; AdhocJobGridView.PageIndex = e.NewPageIndex; AdhocJobGridView.DataBind(); }catch (Exception ex) {throw ex; }   Here is my aspx... <asp:GridView ID="AdhocJobGridView...

Can I populate a Gridview outside of the Gridview using my own edit controls ?
I want to be able to populate a GridView control through some edit controls that willbe displayed above my GridView control. Is their a way to do this without using a DetailsView control ? (Refer to the following article) Or can I have my own edit controls seperately from the GridView control? Actually, all you need to do is to put some textboxes and button. Than on button click insert that data in database and bind data to your gridviewagain. __Please mark post as answer if it helps, if not come back and a...

Gridview to gridview
Hi,   I have a website with a gridview that shows the summary of one person's account, when they click select it reveals a 2nd gridview with details of that specific year. (it's actually 2 different databases) Now my problem is, when I click select on my top datagrid the bottom one doesn't update (by default, it selects the current year). Now I need to "refresh" the gridview without refreshing the page otherwise the content will bounce back to what it was originally, is there a way to update my gridview when I click select but only the gridview? Thanks in advance!  ...

To GridView or not to GridView
All, Just been banging my head against a brick wall thinking about ways to display data. I was wondering on the best way to display a DataSet in my application.  Immediate thoughts were GridView. Thing is when working with large data sets.  Suppose I have the following data set: Name             Cost                Month             YearTom       ...

Hi guys, two gridviews, same page, but one cant define paramters, the other one can.  the one that works is the first example, the one that doesnt work is the second example.  what is the difference? if you could highlight why example two doesnt detect contorls that would be great!!! example one <asp:GridView ID="GridView1" runat="server" AllowPaging="True" AllowSorting="True" AutoGenerateColumns="False" BackColor="LightGoldenrodYellow" BorderColor="Tan" BorderWidth="1px" CellPadding="2&qu...

I have a gridview that contains a hyperlink control that pops up a calendar control (as a separate aspx page).  I assign a javascript to the NavigateUrl attribute of the hyperlink control to open the calendar window like so:                                 NavigateUrl="'DatePicker.aspx?src=ctl00_ContentPlaceHolder1_GridView1_ctl08_txtInsertClassDate','calendar','width=165,height=135,top=400,left=400');calendar_window.focus()...

Get the ID of a control in the gridview
Hi. i have a FilUpload control named "PictureUpload" inside my gridviews edit item template and have realised that the IDs of the controls change when they are in a control. Could i please have the new ID of my FilUpload control, named "PictureUpload" and is in a gridviews edit item template Thanks The control IDs are only changed when they are rendered and sent to the browser (to avoid duplicates). At the server you can access them like this: protected void Button1_Click(object sender, EventArgs e) { int Index = GridView1.EditIndex; ...

Finding a GridView control inside a GridView
I'm working on a page where I programmatically added a GridView inside a Gridview's cell. Actually I have 2 GridViews sitting inside a GridView. What's the best way to find the sub control?I tried:GridviewMain.FindControl("SubGrid") and it doesn't work. Any suggestion would be greatly appreciated,  It would be helpful to see more code, it may be depending where you are doing this in respect to the page's lifecycle - if you are doing within scope of creating the main gridview, it's likely it hasn't been rendered y...

Using INNER JOIN for fields in GridView control--Enable editing breaks GridView
Visual Studio 2005 used for everything below:2 tables created--Physician and PracticePhysician has a field named practiceID (int) which should act as foreign key to (both type int, BUT NO relationships created)Dragged Physician table onto new .aspx pageSQL statement: SELECT, Physician.lname, Physician.fname, Physician.mname, Physician.title,, Physician.address1, Physician.address2,, Physician.state,, FROM Physician INNER JOIN Practice ON Physician.practiceID = ORDER BY Physician.lname, Physician.f...

GridView control enters edit mode only when I click Edit link twice
Hi all..I have a GridView control in an ASP.NET 2.0 page. I added a column that contains edit, update, cancel buttons. Because I did that, I had to handle RowEditing event or an exception was thrown.Well... this is the body of the RowEditing event:protected void gvParametros_RowEditing(object sender, GridViewEditEventArgs e){      gvParametros.EditIndex = e.NewEditIndex;}The fact is that when page is loaded and I click the edit link, page is refreshed but GridView doesn't enter edit mode. When I press edit link again, GridView enters edit mode.Any help to solve this behavior w...

Edit data with GridView Control ? or another control ? help
I use GrivView in ASP.Net 2.0 to show data from DataTable. And i want to edit some fields in some rows. How can I do it? If i touch EDIT button - all columns, which have ReadOnly=false, switch into EDIT mode. But I want, that in first raw I can edit 2,3 column and in second row only 3 column. How can I do it ? ...

Find Control - GridView
Hi I'm using a standard gridView to which I've added the ability to Edit. I've converted one of the fields to a custom template and within that field I've added a textbox (to the update template). When the user clicks the edit button, I'd like to be able to update that text box. I know I need to use FindControl, but is it using Row Editing? Can someone please help with the code? (I'm using C#). Many thanksRichard Check this: remember to click “Mark as Answer” on the post that helps you You can edit ...

GridView Control (Edit Mode) with a checkboxlist
If there is an aswer somewher in the forums please point it out I could not find one. I have a gridview - that simply displays data untill i hit edit then a column is changed into a Checkbox list where I mark the options they already have marked - this part works fine When i click the save icon on the datagrid row - the RowUpdating routine runs but none of the checkbox items I have chosen are saved to the database - I think the problem is that I load the checkboxlist dynamically when the grid goes into the edit mode - Can anyone give me a good solution on this   TIADylan Ba...

javascript to get ClientId for controls in GridView
Hello Every1 I am sorry if this question has been answered asked before, i tried to search but was not able to find it. I have GridVirew and every row contains 4 textboxes and a corresponding label. Using javascript(in textbox change event) , I want to add the number in the textbox and display them in the corresponding label. So the issue is that how Javascript can identify the textbox and its corresponding label. Any clue?  Duck  ThanksDuck"Marking a Reply as 'Answered', not only GAIN us some POINTS, but it also HELP others to find RIGHT solution." Suppose ur GridView ID is grdView Then in javascript var grdView = document.GetElementById("grdView"); var textbox = grdView.getElementsByTagName('input'); for (var i=0; i< textbox.length;i++) { if (textbox[i].type == "text") { textbox[i].value = "MAK"; } }   //same for labels var label= grdView.getElementsByTagName("span"); for (var i=0; i< label.length;i++) { label[i].innerText = "MAK"; }  MAKMark as Answer if this reply helps youMVP ASP/ASP.NetASP.Net Hosting : Host DepotMy Site : ASPSnippets That won't work mudassarkhan as your code reads ALL TextBoxes in the Grid and not just the row. You'd need to handle the Grid's RowDataBound event and attach the JavaScript there. aspx file: <asp:GridView ID="GridView1" ... OnRowDataBound="GridView1_RowDataBound">...

How to get the Id of the controls inside gridview
I have a checkbox control inside the gridview. How to find the id of the checkbox control using javascript. To get the id on clicked   <input type = "checkbox" id = "chk" onclick = "alert(" /> To get from gridview function GetCheckBox() { var grd = document.GetElementByID("GridView1"); varc checkboxes = document.GetElementByTagName("input"); for (var i=0;i<checkboxes.length; i++) { if (checkboxes[i].type == "checkbox" ) { alert(checkboxes[i].id); } } }MAKMark as Answer if this reply helps...

populating gridview controls in edit mode
I know how to populate a dropdown list in a gridview in edit mode when the dropdown is populated by a datasource (see below eg 1), but how do you populate the dropdown when the dropdown is populated in the ASP.NET (ie you are adding asp:ListItems in the ASP see eg 2) rather than by a datasource? Eg 1: <asp:TemplateField HeaderText="Forecast Type" SortExpression="ForecastDescription"> <ItemTemplate> <asp:Label ID="lblForecastType" Text='<%# Eval("ForecastDescription") %>' runat="server"></asp:Label> </ItemTemplate> <EditItemTemplate> <asp:Dr...

Web resources about - GridView and Javascript - how to get the ID of a control from the gridview when gridview is in edit mode. -

JavaScript Kit- Your comprehensive JavaScript, DHTML, CSS, and Ajax stop
Your comprehensive JavaScript, DHTML, CSS, and Ajax stop

Let's Code: Test-Driven Javascript by James Shore — Kickstarter
James Shore is raising funds for Let's Code: Test-Driven Javascript on Kickstarter! A screencast series focusing on rigorous, professional Javascript ...

Eloquent JavaScript: A Modern Introduction to Programming
... and pragmatics. I loved the tutorial-style game-like program development. This book rekindled my earliest joys of programming. Plus, JavaScript! ...

Lightbox (JavaScript) - Wikipedia, the free encyclopedia
On a Lightbox-enabled page, a user can click an image to have it magnified in a Lightbox window, which resizes itself according to the size of ...

Open Directory - Computers: Programming: Languages: JavaScript: Tools: Obfuscators
about dmoz - help Top : Computers : Programming : Languages : JavaScript : Tools : Obfuscators Tools for obfuscation/compression JavaScript code. ...

Facebook Open-Sources JavaScript Static-Type Checker Flow
The latest software to be open-sourced by Facebook is Flow , a static-type checker for JavaScript . (more…) New Career Opportunities Daily: ...

Under the Hood: The JavaScript SDK - The use of polyfills - Facebook
Facebook Engineering hat eine Notiz mit dem Titel Under the Hood: The JavaScript SDK - The use of polyfills geschrieben. Du kannst den vollständigen ...

Quickstart: Facebook SDK for JavaScript
This quickstart will show you how to setup the SDK, load social plugins, trigger a dialog, and get it to make some basic Graph API calls.

Facebook App Devs Get Javascript
It has been an oft-lamented fact of the Facebook Platform thus far in its life that, in order to use all but the most simple of Javascript functionality–the ...

Badass JavaScript (@badass_js) on Twitter
WebGLWorker is an open source library that allows using WebGL from Web Workers. Great work as always from @kripken .… ...

Resources last updated: 2/26/2016 9:17:29 AM