Accessing Different Controls inside the GridView
By AzamSharp
Views: 17313

Introduction:

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

Adding controls to the GridView control:

You can add different controls in the GridView control by simply using the <ItemTemplate> option. 

Populating ListBox and DropDownList:

Second first 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 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 GridView control:

We will try to print out the values on the Button click event 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 ObjectByVal 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!

 

By AzamSharp


Enter Comment/Feedback
  •  
  •  
  •  
  •  
  •  

Comments/Feedbacks
Subject: Thanks....
Name: VIjay
Date: 2/9/2007 3:38:09 AM
Comment:
gr88.... man,
i am master in asp.net 1.1..
but now shifted to .net 2.0 so every thing new over here,,,so was strugling to finding a solition for this and i got in this..

thanks a lot..dud
Subject: GOOD
Name: Divya Raj
Date: 3/6/2007 1:19:32 AM
Comment:
Itz been very helpful bit of code!
Subject: Thanks
Name: Mahesh Sharma
Date: 4/5/2007 10:26:34 AM
Comment:
I Read This Artical.This is Simple Code to Apply Control in GridView Not Only for DropDownList But I Apply it With Various Control.
Heartly Thanks
Subject: Datagrid problem
Name: Nagarjuna
Date: 4/24/2007 12:01:44 AM
Comment:
How can we insert textbox,combobox in
datagrid by using VB.Net
Subject: Not working
Name: Arka
Date: 8/27/2007 4:51:04 AM
Comment:
The find control method always giving the first value of dropdown irrespective of selected item.I have written same as above (vb.net). why it's not working in my case??
Please help!!!!!
Subject: Thanks
Name: Archana
Date: 12/20/2007 3:52:56 AM
Comment:
Hi,,,very good article...thanks a lot
Subject: plz help
Name: sona
Date: 2/20/2008 3:35:40 AM
Comment:
i have tried this but i didnt get the new values to textboxes..
i am getting old value that is already there in the text boxe
Subject: RE: PLZ HELP
Name: AzamSharp
Date: 2/20/2008 8:50:28 PM
Comment:
Hi Sona, Make sure you are not binding the Grid on postback.
Subject: add data row to grid view
Name: Rusty
Date: 3/18/2008 9:31:16 AM
Comment:
I am trying to create a blank gridview and be able to add blank rows to the grid by a button and I am having no luck
Subject: RE: Add Data Row to GridView
Name: AzamSharp
Date: 3/18/2008 9:13:08 PM
Comment:
Hi Rusty, Check out the following article: http://www.gridviewguy.com/ArticleDetails.aspx?articleID=374_Adding_Multiple_Rows_in_the_GridView_Control
Subject: list box update and gridview
Name: Natale
Date: 5/1/2008 12:07:20 PM
Comment:
Very nice code, however I need to take it a step futher. I popluate the listbox. and the user only selects certain items in the listbox. I want to be able to update the selection back to the grid along with all the existing elements of the listbox next time the user logs it adds or removes one selection from the group.

thanks
Nat
Subject: RE: ListBox Update and GridView
Name: AzamSharp
Date: 5/4/2008 7:57:00 PM
Comment:
Hi Natale, It seems like you want to save the selection state of the user. In this case you need to persist the selected ListBox values in the database and then when the page is requested fetch all the saved values and populate the controls with it.
Subject: Thanks for your help
Name: Abdishakur Mohamed
Date: 6/10/2008 12:43:33 PM
Comment:
I really thank you for the post. It was really nice and helpfull. Many thanks for sharing with us such inovative knowledge base



Join WebHost4Life.com






Copyright GridViewGuy 2007-2008