Click here to Skip to main content
15,879,474 members
Articles / Programming Languages / Visual Basic
Article

Accessing the different controls inside a GridView control

Rate me:
Please Sign up or sign in to vote.
3.41/5 (29 votes)
20 Oct 20051 min read 430K   68   26
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

C#
// 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

VB
' 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.

ASP.NET
<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

C#
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

VB
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


Written By
Web Developer
United States United States
My name is Mohammad Azam and I have been developing iOS applications since 2010. I have worked as a lead mobile developer for VALIC, AIG, Schlumberger, Baker Hughes, Blinds.com and The Home Depot. I have also published tons of my own apps to the App Store and even got featured by Apple for my app, Vegetable Tree. I highly recommend that you check out my portfolio. At present I am working as a lead instructor at DigitalCrafts.




I also have a lot of Udemy courses which you can check out at the following link:
Mohammad Azam Udemy Courses

Comments and Discussions

 
Questionsearch the selected row in edit event rather than entire gridview Pin
htm1123-Dec-15 4:59
htm1123-Dec-15 4:59 
GeneralNice Code Pin
Member 1121106916-Jun-15 20:38
Member 1121106916-Jun-15 20:38 
GeneralMy vote of 1 Pin
JB030124-Apr-14 16:15
professionalJB030124-Apr-14 16:15 
GeneralVery nice Article Pin
munirshaikh14-Oct-13 1:26
munirshaikh14-Oct-13 1:26 
GeneralVery nice Article--- thank you Pin
balaramanN22-May-14 0:44
balaramanN22-May-14 0:44 
QuestionRegarding web solutions Pin
Rahul K Soni19-Jun-12 1:41
Rahul K Soni19-Jun-12 1:41 
GeneralVery Easy to Learn http://banyansoft.blogspot.com/ Pin
ayyappanit18-Jan-11 22:52
ayyappanit18-Jan-11 22:52 
GeneralVery Easy to Learn http://banyansoft.blogspot.com/ Pin
ayyappanit18-Jan-11 22:51
ayyappanit18-Jan-11 22:51 
QuestionGridview FindControl Pin
syam.in24-Oct-10 18:21
professionalsyam.in24-Oct-10 18:21 
QuestionGridview FindControl Pin
syam.in24-Oct-10 18:19
professionalsyam.in24-Oct-10 18:19 
QuestionGridview FindControl Pin
syam.in24-Oct-10 18:18
professionalsyam.in24-Oct-10 18:18 
GeneralVery good Pin
Raynier Rivero17-Aug-09 8:37
Raynier Rivero17-Aug-09 8:37 
GeneralMy vote of 1 Pin
jgakenhe16-Dec-08 2:12
professionaljgakenhe16-Dec-08 2:12 
doesn't work, you can even tell because the syntax is wrong
QuestionHow to access last row of gridview... Pin
frifun29-Aug-08 3:13
frifun29-Aug-08 3:13 
Generaldidnt get the value Pin
nitendra7-Mar-08 1:28
nitendra7-Mar-08 1:28 
GeneralGet Checkbox values of Gridviewcontrol in button click Pin
senjith14-Oct-07 3:43
senjith14-Oct-07 3:43 
QuestionHow to get the new value Pin
beaglepuppy23-Feb-07 11:34
beaglepuppy23-Feb-07 11:34 
GeneralMultiple TextBoxes Pin
superstringman5-Jan-07 2:59
superstringman5-Jan-07 2:59 
GeneralAccess a control value in the Editing Row. Pin
ra ra ra ra21-Dec-06 7:26
ra ra ra ra21-Dec-06 7:26 
GeneralDoes not work for my gridview. Pin
Break4022-Sep-06 10:02
Break4022-Sep-06 10:02 
GeneralRe: Does not work for my gridview. Pin
azamsharp22-Sep-06 10:10
azamsharp22-Sep-06 10:10 
GeneralRe: Does not work for my gridview. [modified] Pin
Break4022-Sep-06 10:23
Break4022-Sep-06 10:23 
Questiongridview header Pin
o5ama14-Aug-06 21:31
o5ama14-Aug-06 21:31 
Questionhow to access dataItem Pin
xz2317-Jan-06 17:13
xz2317-Jan-06 17:13 
AnswerRe: how to access dataItem Pin
azamsharp17-Jan-06 17:18
azamsharp17-Jan-06 17:18 

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.