Click here to Skip to main content
Licence 
First Posted 20 Oct 2005
Views 290,280
Bookmarked 67 times

Accessing the different controls inside a GridView control

By | 20 Oct 2005 | Article
How to access the different controls inside a GridView control.

Introduction

I receive many emails asking how we can access a particular control which resides inside a GridView control. In this article I will show you how you can access different controls inside a GridView control. We will see how we can access a TextBox control, a DropDownList control and a ListBox control. If you are working with ASP.NET 1.X then you might want to check out my article Accessing Different Controls Inside a DataGrid.

Adding controls to the GridView control

You can add several controls to the GridView control by simply using the <ItemTemplate> option.

Populating ListBox and DropDownList

The next task is to populate the ListBox and the DropDownList control. Let's make a simple server side method that will populate both the ListBox and the DropDownList.

C# Code

// This method populates the DropDownList and the ListBox control
public DataSet PopulateControls()
{
    SqlConnection myConnection = new SqlConnection(GetConnectionString());
    SqlDataAdapter ad = new SqlDataAdapter("SELECT [Name] FROM tblPerson", 
                                                            myConnection);
    DataSet ds = new DataSet();
    ad.Fill(ds, "tblPerson");
    return ds;
}

VB.NET Code

' This method populates the DropDownList and the ListBox control
Public Function PopulateControls() As DataSet
    Dim myConnection As SqlConnection = New SqlConnection(GetConnectionString())
    Dim ad As SqlDataAdapter = New SqlDataAdapter("SELECT " & _ 
                               "[Name] FROM tblPerson",myConnection)
    Dim ds As DataSet = New DataSet()
    ad.Fill(ds, "tblPerson")
    Return ds
End Function

Now we need to bind this method in the HTML view. Check out the code below for the DropDownList, you can repeat the same procedure for the ListBox control.

<ItemTemplate>
  <asp:DropDownList ID="DropDownList1" DataTextField="Name" 
    DataValueField = "Name" DataSource= '<%# PopulateControls() %>' runat="server">
  </asp:DropDownList>
</ItemTemplate>

Now your DropDownList and the ListBox control are populated with some data. Now let's see how we can access different controls inside the GridView.

Accessing different controls within the GridView control

On the Button click event, we will try to print out the values that are either entered (TextBox) or selected (DropDownList and ListBox). Let's see how this can be done.

C# Code

protected void Button1_Click(object sender, EventArgs e)
{
    // Iterates through the rows of the GridView control
    foreach (GridViewRow row in GridView1.Rows)
    {
        // Selects the text from the TextBox
        // which is inside the GridView control
        string textBoxText = _
          ((TextBox)row.FindControl("TextBox1")).Text;
        Response.Write(textBoxText);
        // Selects the text from the DropDownList
        // which is inside the GridView control
        string dropDownListText = ((DropDownList)
           row.FindControl("DropDownList1")).SelectedItem.Value;
        Response.Write(dropDownListText);
        // Selects items from the ListBox
        // which is inside the GridView control
        ListBox myListBox = (ListBox)row.FindControl("ListBox1");

        foreach(ListItem selectedItem in myListBox.Items)
        {
            // Checks if the item in the ListBox is selected or not
            if (selectedItem.Selected)
            {
                // Print the value of the item if its selected
                Response.Write(selectedItem.Value);
            }
        }
    }

VB.NET Code

Protected Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs)
        ' Iterates through the rows of the GridView control
        For Each row As GridViewRow In GridView1.Rows
            ' Selects the text from the TextBox
            ' which is inside the GridView control
            Dim textBoxText As String = _
              CType(row.FindControl("TextBox1"),TextBox).Text
            Response.Write(textBoxText)
            ' Selects the text from the DropDownList
            ' which is inside the GridView control
            Dim dropDownListText As String = _
              CType(row.FindControl("DropDownList1"), _
              DropDownList).SelectedItem.Value
            Response.Write(dropDownListText)
            ' Selects items from the ListBox
            ' which is inside the GridView control 
            Dim myListBox As ListBox = _
                CType(row.FindControl("ListBox1"),ListBox)
            For Each selectedItem As ListItem In myListBox.Items
                ' Checks if the item in the ListBox is selected or not 
                If selectedItem.Selected Then
                    ' Print the value of the item if its selected
                    Response.Write(selectedItem.Value)
                End If
            Next
        Next
    End Sub

All we are doing in the code above is iterating through all the rows of the GridView control using the GridViewRow object. Next we find the control using the FindControl method and prints out the control's value.

I hope you liked the article, happy coding!

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

azamsharp

Web Developer

United States United States

Member

I am the founder of knowledge base website, HighOnCoding, GridViewGuy, RefactorCode.com and ScreencastADay.com.
 
HighOnCoding is a website which will get you high legally with useful information. There are tons of articles, videos and podcasts hosted on HighOnCoding.
 
HighOnCoding.com www.HighOnCoding.com
 

My Blog:

Blog

 

Buy my iPhone app ABC Pop


Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
GeneralVery Easy to Learn http://banyansoft.blogspot.com/ Pinmemberayyappanit22:52 18 Jan '11  
GeneralVery Easy to Learn http://banyansoft.blogspot.com/ Pinmemberayyappanit22:51 18 Jan '11  
QuestionGridview FindControl Pinmembersyam@tnt18:21 24 Oct '10  
QuestionGridview FindControl Pinmembersyam@tnt18:19 24 Oct '10  
QuestionGridview FindControl Pinmembersyam@tnt18:18 24 Oct '10  
GeneralVery good PinmemberMember 47574608:37 17 Aug '09  
GeneralMy vote of 1 PinmemberJoe Gakenheimer )2:12 16 Dec '08  
QuestionHow to access last row of gridview... Pinmemberfrifun3:13 29 Aug '08  
Generaldidnt get the value Pinmembernitendra1:28 7 Mar '08  
GeneralGet Checkbox values of Gridviewcontrol in button click Pinmembersenjith3:43 14 Oct '07  
QuestionHow to get the new value Pinmemberbeaglepuppy11:34 23 Feb '07  
GeneralMultiple TextBoxes Pinmembersuperstringman2:59 5 Jan '07  
GeneralAccess a control value in the Editing Row. Pinmemberra ra ra ra7:26 21 Dec '06  
Have seen a few examples now of how to iterate through a gridview and retrieve the values in various controls.
 
But how do you retrieve a value from a specific control in a specific row?
 
for example, I have a gridview showing a list of items , with a column called 'Current Status'
 
When I want to edit a particular row I need to show a list of valid status's to change it to. This list is dependent on the currentStatus_ID . I have a method in my business logic layer that will return a strongly typed collection limited by currentStatus_ID
 
I was thinking it would be simple enough to create an Edit template for the column , put in a dropdown list and as the data source reference my business logic layer method GetNextStatusByCurrentStatus_ID(int currentStatus_ID)
 
but I have ran into a problem . As I need to pass a parameter in. I can't seem to be able to reference the currentStatus_ID for the row thats been currently edited and succesfully pass into another method to populate the drop down. I haven't even been able to figure out in what event handler I should be doing this!!! help. I'm stuck.
I think that edit template controls are only data bound after the RowEditing event , but before the RowDataBound event? but I'm not sure.Confused | :confused:
 

Hope it makes some sense.
GeneralDoes not work for my gridview. PinmemberBreak4010:02 22 Sep '06  
GeneralRe: Does not work for my gridview. Pinmemberazamsharp10:10 22 Sep '06  
GeneralRe: Does not work for my gridview. [modified] PinmemberBreak4010:23 22 Sep '06  
Questiongridview header Pinmembero5ama21:31 14 Aug '06  

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

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

Permalink | Advertise | Privacy | Mobile
Web04 | 2.5.120529.1 | Last Updated 20 Oct 2005
Article Copyright 2005 by azamsharp
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid