Accessing Different Controls inside the Datagrid
By AzamSharp
Views: 11532


Introduction:

Every now and then I get emails saying that how can we get value from a TextBox that is inside a Datagrid?. When I answer that the next question is how do we get values from a TextArea inside a Datagrid control? In this article I will show you how you can get values out of different controls that are inside the Datagrid control.

User Interface:

Since this Datagrid will contain different controls in each column hence it will look something like this:


 

As you can see that the Datagrid looks kinda ugly :) but the purpose of this article is to show you that how you can retrieve values of different controls which are present inside the Datagrid. Here are the column details:

Column 0 = TextBox

Column 1 = Listbox

Column 2 = DropDownList

Column 4 = CheckBox

You must be wondering that how I populated the controls. So let's see some code:

BindData method:

We used a very simple BindData method which is called by each control and hence each control is populated. Here is the page load event.

private void Page_Load(object sender, System.EventArgs e)

{

 

myDataGrid.DataSource = BindData();

myDataGrid.DataBind();

 

}

The page load event simply calls the BindData method which is the heart and soul for this application.

public DataSet BindData()

{

Database db = DatabaseFactory.CreateDatabase();

DBCommandWrapper selectCommandWrapper = db.GetSqlStringCommandWrapper("SELECT * FROM Articles");

return db.ExecuteDataSet(selectCommandWrapper);

 

}

I said before that BindData method is heart and soul but I forgot to mention that its also very simple :). I am using Microsoft Enterprise Library to access the data from the database. You can use whatever method you find suitable for you. The only thing to remember about this method is that it returns a dataset object which will later be assigned to the controls inside the Datagrid.


Binding the data to the controls:

Now let's see that how we have populated the controls inside the Datagrid.

<asp:DataGrid id="myDataGrid" runat="server" AutoGenerateColumns="False" Width="360px" Height="120px">
<Columns>
<asp:TemplateColumn>
<ItemTemplate>
<asp:TextBox text= '<%# DataBinder.Eval(Container.DataItem,"Title") %>' id="TextBox1" runat="server">
</asp:TextBox>
</ItemTemplate>
</asp:TemplateColumn>
<asp:TemplateColumn>
<ItemTemplate>
<asp:ListBox DataSource="<%# BindData() %>" DataTextField="Abstract" DataValueField ="Abstract" id="ListBox1" runat="server">
</asp:ListBox>
</ItemTemplate>
</asp:TemplateColumn>
<asp:TemplateColumn>
<ItemTemplate>
<asp:DropDownList DataSource="<%# BindData() %>" DataTextField="DateCreated" DataValueField="DateCreated" id="DropDownList1" runat="server"></asp:DropDownList>
</ItemTemplate>
</asp:TemplateColumn>
<asp:TemplateColumn>
<ItemTemplate>
<asp:CheckBox id="CheckBox1" runat="server"></asp:CheckBox>
</ItemTemplate>
</asp:TemplateColumn>
</Columns>
</asp:DataGrid>

 Don't be scared by looking at all the code above. Most of the code is automatically generated. I have made the lines bold which are important. As you can see that we are pretty much doing the same stuff on each control inside the Datagrid. We assign BindData method as a DataSource and than set the text of the controls and finally we set the value of the control.

Now comes the fun part since we have already populated the Datagrid embedded controls with some data now we can extract those values. You can use any type of event to extract the values, I will be using a simple button click controls to display values from different rows. Let's see the code in small pieces.

First we made the StringBuilder object. In order to use StringBuilder object you need to include the namespace System.Text.

StringBuilder str = new StringBuilder();

The code below extracts the values from the controls. We are using a simple foreach loop that goes through the Datagrid rows and gets the values of the controls.

foreach(DataGridItem dgi in myDataGrid.Items)

{

TextBox myTextBox = (TextBox) (dgi.Cells[0].Controls[1]);

ListBox myListBox = (ListBox) (dgi.Cells[1].Controls[1]);

DropDownList myList = (DropDownList) (dgi.Cells[2].Controls[1]);

CheckBox myCheckBox = (CheckBox) (dgi.Cells[3].Controls[1]);

str.Append(myTextBox.Text);

string a = myListBox.SelectedValue;

if(a != null && a != "")

{

str.Append(myListBox.SelectedItem.Text);

}

 

 

str.Append(myList.SelectedItem.Text);

str.Append(myCheckBox.Checked);

}

As I said before TextBox is the column number 0 that's why we are using dgi.Cells[0]. For ListBox we are using dgi.Cells[1] and so on.

UPDATE:

You can also use the FindControl("ControlID") Method to access the Controls inside the Datagrid. I am pulling the values out using the Cells method since my only purpose is to get the Control value and not perform any actions on those values. Also in this case my Datagrid columns are static.

FindControl method is more useful since you don't need to change the Cells indexes when the order in the Datagrid changes.

TextBox myTextBox = (TextBox) (dgi.FindControl("TextBox1");

ListBox myListBox = (ListBox) (dgi.FindControl("ListBox1");

DropDownList myList = (DropDownList) (dgi.FindControl("DropDownList1");

CheckBox myCheckBox = (CheckBox) (dgi.FindControl("CheckBox1");

string a = myListBox.SelectedValue;

if(a != null && a != "")

{

str.Append(myListBox.SelectedItem.Text);

}

The above 4 lines are very important in order to get the values from the ListBox control. Always remember to extract the value of the selected ListBox item and assign to a string variable and than check for null or empty values.

Basically that's all there is to do. Finally when you press the button all the data that you have selected is printed out on the screen. If you want to select the rows and not the whole Datagrid items than you can easily use the "select" column of the Datagrid and use the same technique to access the row items.

I hope you liked the article, Happy programming !

 

 

By AzamSharp


Enter Comment/Feedback
  •  
  •  
  •  
  •  
  •  

Comments/Feedbacks
Subject: GirdView Code
Name: Desmond Fernando
Date: 5/10/2007 5:19:36 AM
Comment:
the above gives me this error

Error 4 foreach statement cannot operate on variables of type 'System.Web.UI.WebControls.GridView' because 'System.Web.UI.WebControls.GridView' does not contain a public definition for 'GetEnumerator' C:\zapera\trunc\Sources\frontend\site\admin\ParticipantList.aspx.cs 169 9 C:\...\frontend\
Subject: RE: GridView Code
Name: AzamSharp
Date: 5/10/2007 11:26:08 AM
Comment:
Dear Desmond Fernando,

You will need to paste more code. It seems like you are iterating the GridView instead of the GridView row collection.

Subject: Good
Name: phani.vattikuti
Date: 5/31/2007 12:16:25 AM
Comment:
This is good article..

very nice..


Regards,
phani.vattikuti.
Subject: c#
Name: Narendra
Date: 7/16/2007 1:05:31 AM
Comment:
nice,it is very helpful for beginners to understand
Subject: listboxselected item
Name: peleg
Date: 9/1/2007 3:48:40 AM
Comment:
how can i in a listbox get all selected item?

thnaks in advance
peleg
Subject: RE: listboxselected item
Name: AzamSharp
Date: 9/1/2007 11:30:42 AM
Comment:
Hi Peleg,

Once, you get a reference to the ListBox inside the GridView control. Simply, iterate through the ListBox items and check whether the item has been selected or not.
Subject: checkbox not return value
Name: bhavesh
Date: 10/5/2007 5:46:12 AM
Comment:
hi
Dear

I used this code in .net but when i do
loop for each item in datagrid the checkbox checked property always return false value how to solve the problem
my code is as below:
foreach(DataGridItem DemoGridItem in grdInbox.Items)
{
//CheckBox chkDelete = (CheckBox)DemoGridItem.Cells[0].Controls[1];
CheckBox chkDelete = (CheckBox)DemoGridItem.FindControl("chkDelete");

string strName=grdInbox.DataKeys[DemoGridItem.ItemIndex].ToString();
if(chkDelete.Checked == true)
{
rowCount++;

}
}
please send me mail asap

thanks & regards
Bhavesh sharma
Subject: RE: checkbox not return value
Name: AzamSharp
Date: 10/7/2007 9:22:01 AM
Comment:
Hi Bhavesh,

Make sure you are using TemplateColumn and not the CheckBoxColumn.
Subject: Object Ref
Name: anonymous
Date: 10/22/2007 3:38:42 AM
Comment:
foreach (GridViewRow dr in grdItems.Rows)
{

TextBox txtQuantity = (TextBox)grdItems.FindControl("txtQuantity");

string str=txtQuantity.Text;//this throws object ref not set to instance of an object why ???
}
Subject: Code for how to access listbox control in the datagrid
Name: sanket Valimbe
Date: 3/19/2008 2:43:26 AM
Comment:
this is a preety short n simple code. main thing is tht i like the explaination. Thanxs.......
Subject: A big doubt for datagrid
Name: MohammedAsifAli
Date: 3/28/2008 7:20:24 AM
Comment:
i have some values in my datagrid and i want few values should be enter into the textboxes only when i press ENTER button but not using mouse plz help me out
Subject: RE: A big doubt for datagrid
Name: AzamSharp
Date: 3/31/2008 9:37:56 AM
Comment:
Hi Mohammad Asif, Do you want this client side or server side?



Join WebHost4Life.com






Copyright GridViewGuy 2007-2008