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 it...

by 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,
Mhaey

Please remember to click “Mark as Answer” on the post that helps you.. =)
0
darkcat02
5/6/2008 8:59:16 AM
asp.net.presentation-controls 72751 articles. 3 followers. Follow

10 Replies
3789 Views

Similar Articles

[PageSpeed] 29

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 Shahid
Sr. Software Engineer
(MCP,MCAD.net,MCSD.net,MCTS,MCPD.net[web])
Netprosys Inc.
www.netprosys.com

Remember to click "Mark as Answer" on the post that helps U
0
kamii47
5/6/2008 9:13:22 AM

 hi,

you can use the find control method....if suppose the textbox is in the first column

TextBox txt = Gridview1.Rows[0].Cells[0].FindControl("Textboxname") as TextBox;

thanks,

rajiv

0
rbansal44
5/6/2008 9:16:39 AM

You can do so by using row data bound event and e.row.findcontrol("textbox1").ClientID, where textbox1 is the id of the textbox

0
pradeepbohra
5/6/2008 9:16:49 AM

I agree wihth Kamran Shahid. What do you want to do by getting id?


Sridhar
0
SRIDHAR
5/6/2008 9:21:58 AM

if i get the id i will put some value into it... is that possible...

for some reasons... instead of putting codes into the client side.. i would put it to the server side...

but i cant get the id of it... Tongue Tied 


Regards,
Mhaey

Please remember to click “Mark as Answer” on the post that helps you.. =)
0
darkcat02
5/6/2008 9:28:07 AM

Hi darkcat02 ,

See my sample,

 

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            DataTable table = new DataTable();
            table.Columns.Add("test");
            DataRow dr = table.NewRow();
            dr["test"] = "before change";
            table.Rows.Add(dr);
            this.GridView1.DataSource = table;
            GridView1.DataBind();

        }
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
       TextBox box =  this.GridView1.Rows[0].FindControl("TextBox1") as TextBox;
       box.Text = "changed";
    }
    string clientid;
    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            TextBox box = e.Row.FindControl("TextBox1") as TextBox;
            clientid = box.ClientID;
        }
    }
    protected void Button2_PreRender(object sender, EventArgs e)
    {
        this.Button2.Attributes.Add("onclick","document.getElementById('"+clientid+"').value = 'changed' ; return false;");
    }

 

    <form id="form1" runat="server">
    <div>
        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" Width="194px" OnRowDataBound="GridView1_RowDataBound">
            <Columns>
                <asp:TemplateField>
                    <ItemTemplate>
                        <asp:TextBox ID="TextBox1" runat="server" Text='<%# Eval("test") %>'></asp:TextBox>
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
        </asp:GridView>
    
    </div>
        <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="change" />
        <asp:Button ID="Button2" runat="server" OnPreRender="Button2_PreRender" Text="change on client" />
    </form>

 

 



Samu Zhang
Microsoft Online Community Support

Please remember to click “Mark as Answer” on the post that helps you, and to click “Unmark as Answer” if a marked post does not actually answer your question.
1
Samu
5/8/2008 3:24:18 AM

 thank you for the replies...

 

but now i still dont get it... sorry... the code isn't getting into my head.. argh!

i have a simple for you guys... by the way the code above was being asked by my friend... so now.. this question is mine..

 

i need the code to find the control id (again! yes.. again! i cant understand how should i do it) of a dropdownlist and sqldatasource... how should i do it...

 pls help me... i am still a student... anyone? Sad
 


Regards,
Mhaey

Please remember to click “Mark as Answer” on the post that helps you.. =)
0
darkcat02
5/15/2008 6:18:30 AM

 

on  itemdatabound function of gridview

just give the following code;

TextBox objtxt1 = (TextBox)e.Item.FindControl("txt1");

string  strtxtID = objtxt1.ClientID;

0
ams16
5/16/2008 4:43:06 AM
Use this in .aspx.cs page......

 

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            DropDownList ddl =(DropDownList) e.Row.FindControl("DropDownList1");
            ddl.DataSource = "WhateverUrDataSource";
            ddl.DataTextField = "YourDataTextField";
            ddl.DataTextField = "YourDataValueField";
            ddl.DataBind();
        }
    }

  

Use this iin .aspx page

 <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" Width="194px" OnRowDataBound="GridView1_RowDataBound">

            <Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:DropDownList ID="DropDownList1" runat="server"></asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
 

 


"Mark as Answer" on the post that helped you.

Chandan,
Imfinity India Pte Ltd.
0
chandan
5/16/2008 5:00:26 AM

chandan.max:
Use this in .aspx.cs page......

 

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            DropDownList ddl =(DropDownList) e.Row.FindControl("DropDownList1");
            ddl.DataSource = "WhateverUrDataSource";
            ddl.DataTextField = "YourDataTextField";
            ddl.DataTextField = "YourDataValueField";
            ddl.DataBind();
        }
    }

  

Use this iin .aspx page

 <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" Width="194px" OnRowDataBound="GridView1_RowDataBound">

            <Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:DropDownList ID="DropDownList1" runat="server"></asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
 

 

 

 

how about the selected value... it can't read it... and also.. if i update the grid.. the data wouldn't save...

 

 

 Protected Sub GridView1_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView1.RowDataBound
        Dim drpUnit1 As DropDownList

        If Not IsNothing(e.Row.FindControl("drpUnit1")) Then
            drpUnit1 = CType(e.Row.FindControl("drpUnit1"), DropDownList)
            drpUnit1.DataSource = sqlDrpUnit
            drpUnit1.DataTextField = "Unit"
            drpUnit1.DataValueField = "UnitID"
            If Not IsNothing(CType(e.Row.FindControl("drpUnit1"), DropDownList).Items.FindByValue(DataBinder.Eval(e.Row.DataItem, "UnitID").ToString())) Then

                CType(e.Row.FindControl("drpUnit1"), DropDownList).SelectedValue = DataBinder.Eval(e.Row.DataItem, "UnitID").ToString()

            End If
            drpUnit1.DataBind()




        End If
    End Sub
  
Regards,
Mhaey

Please remember to click “Mark as Answer” on the post that helps you.. =)
0
darkcat02
5/16/2008 5:13:44 AM
Reply:

Similar Artilces:

How to apply ID to each control & find that specific control again to get data from the control?
Hi. i have problem with my codes & need someone help to fix my codes. my case is in addRow function, when i click the button, i will add textbox & dropdownlist control dynamically. but after click Save button, i got error msg  " File saved failed. Reason is as follows System.NullReferenceException: Object reference not set to an instance of an object. at Default2.Save_Click(Object sender, EventArgs e) in C:\Documents and Settings\My Documents\Visual Studio 2008\WebSites\WebSite2\Default2.aspx.vb:line 290  (objStreamWriter.WriteLine(CStr(MapTable.Rows.Count...

Custom Control within a Control Control
I am developing a custom controls that will render headers for different web sites. Within these controls, I want to place another custom control that will change the language. I created the language control and had it implement IPostBackDataHandler. This control works fine if I drag it on a new web form, but if I tell a header custom control to render it problems occur. The Language Selector custom control does not have a Page member anymore and the event handlers do not work. Does anyone have any experience with doing something similiar? Anyone have any suggestions? Thanks, ...

How do I control one control from another control?
I have a page page1.aspx which is within a master page. On page I have a table with two cells. Within each cell I have placed two controls (ascx) that I have developed. Now I'd like to be able to get these two controls to interact. One needs to update the other. One has some search criteria that the other one needs to update its gridview. One needs to make the other visible/not visible at certain times. Out of the box neither control can see each other at all. Is there a good article or someplace I can find some information on how to do this?  AllAboutFocus.com. Information Technology SolutionsHelping You Focus. Helping You Succeed. Here's a hint for you... ascx user controls are self-contained objects that hide their contents from other applications.  When you build them, you will need to place in properties and methods are are accessable from an outside. Here is a down-and-dirty example Create a usercontrol. name it HelloOutsideWorld.ascx with the following contents:<%@ Control Language="C#" AutoEventWireup="true" CodeFile="HelloOutsideWorld.ascx.cs" Inherits="HelloOutsideWorld" %> <asp:Label ID="lblMessage" runat="server" Text="Awaiting Message From The Outside..."></asp:Label>  Here is the codebehind for HelloOutsideWorld.ascx.cs: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 S...

Get controlID from control (textbox) inside another control (gridview)
Ok, so I've been trying to get a link within the edit item template of a gridview to open a new window.  I can do that fine, but when I try to pass the new window the controlID of the textbox to pass the value back to in the originating page I can't get the correct ID.  (that was a mouthful)  Maybe my code will explain better...  <EditItemTemplate> <asp:TextBox ID="EndTextBox" runat="server" Text='<%# Bind("endtime") %>'></asp:TextBox> <a href="javascript:;" onclick="window.open('popup.aspx?reqbox=<%=Me.findcontrol("GridView1").FindControl("EndTextBox").clientid %>','cal','width=350,height=300,left=270,top=180')"> <img src="images/calendar_icon_small_trans.gif" border="0" align="absMiddle"></a> </EditItemTemplate> I've basically had problems with the part "Me.findcontrol("GridView1").FindControl("EndTextBox").clientid"I've tried many other things in the line above, like <%=EndTextBox.ClientID%> but get errors that endtextbox is not declaredI had been using this page: http://spellcoder.com/blogs/bashmohandes/archive/2007/06/17/7297.aspx as a reference, and looked through several other posts, but can't seem to get this to work.Just FYI, is more than a calendar as the image name denotes. Thansk in adv...

Help Req: !!! :- On Disabling Controls Present inside a Gridview control
Hi All, We have A requirement Where we have disable controls inside a grid.These controls can be textbox, DropDownlist (in TemplateField), ComandField present inside the grid.We have to call a generic method for doing the same .(since it can be done for multiple grid.) PFB the code snippet we use. Which disables all the controls inside the page.The bolded part of the code is used to loop inside a grid view.(Not Working.)Is this ideal way to deal with the requirement.Or can someone suggest be a better way.        public void DisableMe(Page p1, st...

How do you control the placement of controls in a user define control
I have a user define control.  I put the control on the (C# Visual Studio 2008) page where I want them. When I run the program, the controls are all over the page.  How do I place them where they do not move form where I put them? You'll need to study the HTML output and see what it's producing, then start to look at how to do an HTML layout. hi, there are absolute and Relative position in html. I guess you must use relative position. For example, at design-time, you place a TextBox below an Image, at run-time, no matter what size is the image, the TextBox is alway bel...

Trying to load a control into a control from another control
Exactly as the subject states, I'm trying to load a control into another control from a control loaded into a page, I keep getting this error from the code I have below. I've also tried the findcontrol but it keeps coming up null. (67): 'System.Web.UI.UserControl' denotes a 'class' where a 'variable' was expected UserControl ut = ((webcontrols.BrowseItems)UserControl).LoadControl("BrowseItems"); ((webcontrols.BrowseItems)UserControl).pnl_browse_main.Controls.Add(ut); This is how we Load User controls into a content place holder. try { UserControl ctl; ctl = (UserControl)LoadControl(PagePath.ReturnPagePath(Request.QueryString["CurrentPage"])); this.contentPlaceholder.Controls.Add(ctl); } catch (Exception ex) { Response.Write(ex.Message); Response.Write("Unable to load " + (string)Session["CurrentPage"] + " control"); } You need to replace the whole ctl call with the UserControl object the you created. When you Response.Write your execption on a load fail. change the output to whatever you would like to display. By looking at your naming scheme it looks like you just want to fill a Panel. For this we usually make a Panel on the page and goto the solution explorer then drag and drop the usercontrol we wish to display into the panel. If you are not wanting to change this dynamically later in your solution the drag and drop is the easiest way to go.It's not ...

Accordion Control : Multiple controls with the same ID (1) were found. FindControl requires that controls have unique IDs.
I am not trying to add any Accordionpane dynamically . I have an accordion on my page but when I try to run the page, I get the above exception message. I have no idea what else I need to set for to make fix the error. Anyone know how?? Thanks in advance.   <br /> ACCORDION CONTROL TEST AREA <br /> <br /> <ajaxToolkit:Accordion ID="MyAccordion" runat="Server" SelectedIndex="0" HeaderCssClass="accordionHeader" HeaderSelectedCssClass="accordionHeaderSelected" ContentCssClass="accordionContent" Aut...

gridview control in another gridview control
Hi ia have a questioni have a gridview control which contains button in one colum.now 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 data.now 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 to do it.                http://msdn2.microsoft.com/en-us/library/aa992038(VS.80).aspx                Let me know if I have misunderstood what you mean. Thanks. KarlClick "Mark as Answer" on the post if the answers helpClick "Unmark as Answer" if you need more directionThank you for your cooperation Hi Siri,      Take a grid view with two template fields.      Place a button in first template.And Place GridView in Second Template.     This will complete your work.     This will help you completing your work.Still If you want I can send you code..           Lokanadham M.Hyderabad. Hi LokanadhamTh...

getting properties of controls inside a table control
Hi, I h ave a Table control "tbl" in which I am adding other controls such as textboxes and labels dynamically. I am trying to access the propertiesof the controls, such as label1.text and textbox1.text , that I dynamically created and added into the table control. The tbl has two columns, in the first column it has labels and textboxes in the second one Is there anyway I can access the properties of all the controls that I added in different columns and rows of table control by looping through the table. Something like, string temp; for(int i-0;i<=(num...

Cannot access a dropdownlist control inside the gridview control
I am using the Gridview control without a DataSource control. When I click on the Edit button, the page posts back and enters the following code: <code>     Protected Sub GridView1_RowEditing(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewEditEventArgs) Handles GridView1.RowEditing         Try            Dim row As GridViewRow = GridView1.Rows(e.NewEditIndex)            Dim ddlCustomerID As DropDownList = row.FindControl("ddlCustomerID")            ddlCustomerID.DataSource = dstCustomers            ddlCustomerID.SelectedIndex = ddlCustomerID.Items.IndexOf(ddlCustomerID.Items.FindByValue(dstCustomers.Tables(0).Rows(row.RowIndex).Item("CustomerID")))            ddlCustomerID.DataBind()        Catch ex As Exception            Response.Write(ex.Message)        End Try     End Sub </code> I cannot get an instance of the control in the above boldfaced code after passing thru that line during debugging. It has a value of Nothing. My html code is set up as follows (shortened for brevi...

How to catch the controls inside other control
Hi, I place a couple of controls such as linkbutton and placeholder inside a datalist control. When I use code behind to find the control and do something with them, I cannot find these controls. Can anyone help me. Some of my codes are as follows: <asp:DataList id="dltInfo" runat="server"> <ItemTemplate> Report: <%# container.dataitem("rptName") %> <br> Requestor: <%# container.dataitem("requestor") %><br> Assigned To:<%# container.dataitem("assignedto") %><br> <asp:...

Access Controls inside Controls
I have a login control (Login1) inside a Login View control (LoginView1). MembershipUser mbr; mbr = Membership.GetUser(Login1.UserName); It can not find control Login1.  Cheers.  MattSystems Engineer / ASP.NET Web Developermbaughan@raecomputing.com You have to use FindControl. Try creating a local Login control using   LoginView1.FindControl("Login1");Remember: mark posts that helped you as the answer to aid future readersWhy UpdatePanels Are DangerousWhy You Should Not Place Your Whole Site In An UpdatePanel MembershipUser mbr; LoginView1.Find...

validation controls in gridview control
hi, I m using the grid view to add,edit,update,delete the data table. Everything is fine.In the footertemplate i get the values through text boxes and drop down lists.i took place sm validation controls to validate these controls.the problem arises here.if i want to update the record after i click the edit button, it validate the page n dont allow me to update the record.I want to validate the particular controls only. i checked if any causes validation property for update button.there is nothing like that. pls help me.. thanks in advance gowri  regards,gowripillaimark as answer if...

SqlDataSource Control and Gridview control
Hi, I'm new to web development and learning about these controls.  The books teach you to bind the gridview control to an sqldatasource to perform delete,update,insert functions as well as to list the records in a table.  Is this standard practice for real world applications?  Or is there another way that should be used to display/manage table data in the gridview control? Thanks. Tulsi Using a sqldatasource is the best way I know of for binding data to a gridview.  (I'm pretty new to web development too, so maybe someone else can chime in if they know someth...

Adding Control inside a Control
Here's the deal.  Through C#, I've cleared a panel and I want to add a <div> tag with a border and some other styles to the placeholder.  The <div> will have a text message and a button in it. Exactly how do I do this?  I've got some source below which has two Labels.  The first label has the opening two div tags, the second label has the closing </div> tags. Then I add the first label to the PlaceHolder; next, I add the button; finally, I add the second label.  Theoretically it should work (and it...

Controls inside Datalist control
When I droped a CustomValidator on a web form and double click on the control, it brings me to the code withPrivate Sub CustomValidator1_ServerValidate(ByVal source As System.Object, ByVal args As System.Web.UI.WebControls.ServerValidateEventArgs) Handles CustomValidator1.ServerValidate End SubBut if I droped a CustomValidator in a DataList control, I couldn't see the control.  I tried Handles DataList.CustomValidator1.ServerValidate, but it didn't work.  How do I make the CustomValidator in a DataList work?  Thanks.Dan-Yeung Hi, you cannot assign event handler into a control contained by a databound control quite like that, because those controls aren't exposed in top-level way as normal controls on Page (DataListItem is a naming container for its controls). Basically it's because with databound control you could have 1 or 5 of them, so top-level way isn't the one with these. Instead, you can wire event handler into a control contained inside a DataList by either handling dataList's ItemCreated event where you could look for the contained control with FindControl method of DataListItem and assign the event handler programmatically. ...Dim cvalid As CustomValidator = Ctype(e.Item.FindControl("CustomValidator1"),CustomValidator)AddHandler cvalid.ServerValidate, AddressOf CustomValidator1_ServerValidate... Or you could wire the event handler declaratively in aspx inside DataList's ItemTemplate<asp:CustomValidator ... OnServerValidate="Cust...

Getting all the controls of Toolstrip control
Hi,     How will i be able to retrieve all the controls under toolstrip controls. Something like for all controls in me.controls....i need to access all the controls inside Toolstrip.  Let me know the options on how i would be able to achieve this. Thanks,Kris      ...

Precise Control over GridView controls?
Hi.When you create a GridView in visual studios and bind it to, say, an SqlDataSource, it automatically creates fields and templates according to the types retrieved from the data source. (ie, it creates a Label for number/string columns, checkboxField for booleans, etc). My question: How do I control precisely what WebControls/Fields are used for each column?thanks,Tombow Hi Tombow Using TemplateFields you can control that explicitly.  See the Data Tutorial #12 at http://www.asp.net/learn/dataaccess/default.aspx?tabid=63 for more details. Hope that helps. AaronDon't...

Control and control collection inside it
I'm writing control (ProductCollection) which must contains collection of Products.ProductCollection has Linkbutton to add new Product object into Controls state: void lb_Click(object sender, EventArgs e){  foreach (Control con in Controls)  {   _hash.Clear();   if (con is ProductControl)    {    _hash.Add(_hash.Count + 1, con);   }  }  ProductControl ep = new ProductControl();  Controls.Add(ep);  _hash.Add(_hash.Count + 1, ep);  Context.Session["Coll"] = _hash;} andprotected o...

using controlS to control a gridview
This question is probably posted but i did not bother to look at 10,000+ posts so i am sorry. I've seen the tutorial where he builds a dataset and uses a gridview and controls the gridview with the drop down list box. What i am trying to do is to control the gridview with 2 drop down list boxes. First select the Country you life in and then the State. I've looked at the grid view properties but couldn't find where i can add another parameter. Is it possible to control a grid view (or any form of displaying the information) with more than 1 controller? Thank You.  ...

Get control in repeater control
Dear all, I want to use HtmlControls.HtmlTableCell in repeater control but i cant not access it,  in my table in Repeater Control,  i have 2 "td" which on page_load, i want to show only 1 of them depend on condition given. But i cant do it. This is my code : <asp:repeater id="repeaterViewNew" runat="server">                   <HeaderTemplate>                      <table width="100%" cellpadding="1" cellspacing="1">   &...

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: http://forums.asp.net/t/1069245.aspx 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....

Control Ids in Control Tree
I have had an issue the last few days in trying to rebuild a composite control during the PreRender event. The issue is that links do not fire from the reconstructed control. I've been able to isolate the problem to a case of mismatch ids in the control tree and ids specified by the link button. Reconstruct the control and the framework continues to increment ids from its last value: ctl2 might become ctl12 and so forth. However, when the ctrl is rebuilt on the next request (to respond to the link button click) it is only rebuilt once and ids based from zero instread of the value that t...

Web resources about - Getting the control id of a control inside gridview control - asp.net.presentation-controls

GridView SelectedItem Binding Gotcha in WinRT
Last night when I was doing some WinRT hacking I was trying to setup databinding to the selected item in the GridView control and I ran into ...

CNW Group
Home Services Beyond the Wire About CNW Financials Webcasts Events My CNW All News Releases Advanced Search Gridview Latest News Releases All ...

CNW Group
... Services Beyond the Wire About CNW my CNW CNW Access CNW Directories Financials Webcasts Events my CNW All News Releases Advanced Search Gridview ...

CNW Group
Home Services Beyond the Wire About CNW Financials Webcasts Events My CNW All News Releases Add a Filter Gridview Latest News Releases All Today ...

New CmdLets of Powershell 2.0
New CmdLets of Powershell 2.0

Price Drop: Softbox
... objects- create product reflection- changing the background with something more interestingUse it as:- softbox- honeycomb softbox- gridview ...

Profile.aspx: ASP Alliance
.NET,ASP,ASP.NET,SQL,XML,HTML,ADO,ADO.NET,JavaScript,JScript,CSharp,VBScript and VB tutorials from AspAlliance.

Quick Answers - CodeProject
Questions - Free source code and tutorials for Software developers and Architects.; Updated: 25 Oct 2012

DotNetKicks.com - Upcoming stories
DotNetKicks.com is a community based news site edited by our members. It specialises in .NET development techniques, technologies and tools including ...

View Features - ExtendASP
Call 847-681-9827 or Request a Demo View Features Testimonials Pricing About Us Coming Soon ExtendASP exposes every feature, more than any other ...

Resources last updated: 3/9/2016 8:19:28 PM