Accessing Data in DataGrid Template Column


I have a Datagrid (called dgDataGrid) with a bound column that display a textbox when the user clicks the Edit button on a row of the datagrid. I can access the cell (cell [0]) of the clicked row and save its content (in OldValue) before the user enters a new entry with the following C# code:

private void dgDataGridEdit_Click(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
      string OldValue = dgDataGrid.SelectedItem.Cells[0].Text.ToString();
      dgDataGrid.EditItemIndex = (int)e.Item.ItemIndex;

However, when I change the bound column to a template column, executing the same code causes nothing to be saved in OldValue.

Can anyone tell me why is this so? What can I do to save the value of a Template Column cell before the user overwrite it?

FYI, I have tried the followings FindControl statements but got Object reference not set to an instance of an object error. (apparenltly it cannot find tthe TextBox):

TextBox tb = (TextBox) dgDataGrid.Items[dgDataGrid.SelectedIndex].FindControl("Name");
TextBox tb = (TextBox) dgDataGrid.Items[e.Item.ItemIndex].FindControl("Name");
TextBox tb = (TextBox) dgDataGrid.Items[0].Cells[0].FindControl("Name");
TextBox tb = (TextBox) e.Cells[0].FindControl("Name");
TextBox tb = (TextBox) e.Item.FindControl("Namee");
string OldValue = tb.Text;

The HTML code for the Template Column is:

<asp:TemplateColumn HeaderText="Name">
          <asp:Label runat="server" Text='<%# DataBinder.Eval(Container, "DataItem.NAME") %>'>  </asp:Label>
         <asp:TextBox id=Name runat="server" Text='<%# DataBinder.Eval(Container, "DataItem.NAME") %>' CssClass="uppercase">

 Would really appreciate your help. Thanks in advance.



12/5/2006 7:21:41 AM 72751 articles. 3 followers. Follow

4 Replies

Similar Articles

[PageSpeed] 38

Hi! The error means that the control id textbox cannot be found. So what you need to do is to specify the row you've been using to get the old values.

TextBox tb = (TextBox) dgDataGrid.Rows[dgDataGrid.SelectedIRow].FindControl("Name");

Hope it helps. I know VB not C. ^_^ 


I don't know .NET! Why I'm here???
12/5/2006 8:24:12 AM


I found out the problem. In the private void dgDataGridEdit_Click routine, you have to use FindControl after DataBound so that he textbox (with the original value) will be displayed at that time. Calling FindControl before DataBound will not find the TextBox since it is not yet displayed.

Thanks for anyone who view this problem.


12/5/2006 8:35:39 AM


Thanks for the suggestion. I tried and it did not work. I got a compile error saying 'System.Web.UI.WebControls.DataGrid' does not contain a definition for 'Rows'. Look like it does not like "dgDataGrid.Rows" .

Anyway, I got the problem solved. Please refer to my post before.

Thanks very much.


12/5/2006 3:24:15 PM

Hi, sg2000:

As the TextBox is in the EditTemplate, so the findcontrol will not access it.

Try to add this before using findcontrol to force the DataGrid into edit mode. 

this.DataGrid1.EditItemIndex = RowindexYouDeal;

Best Regards,
Rex Lin
Microsoft Online Community Support

This posting is provided "AS IS" with on warranties, and confers no rights.
12/6/2006 7:48:23 AM

Similar Artilces:

How to access a template column in a datagrid control
I have a DataGrid control on a web form with a template column. How can I access the dropdownlist column "ddlusertype" from my c# code? I need to bind it with a DataTable. Please help, thanks! Here is my code <Columns> <asp:BoundColumn DataField="rolName" HeaderText="User Type"></asp:BoundColumn> <asp:BoundColumn DataField="rolDescription" HeaderText="Description"></asp:BoundColumn> <asp:BoundColumn DataField="gtyAbbr" HeaderText="Client Type"></asp:B...

accessing data in a datagrid template column
Can anyone out there tell me how to access data that is placed in a datagrid template column? I am coding in From what part of your code do you want to access it? If you want to access it while the grid is being databound, you can use ItemDataBound. Elsehwere, you'll need to iterate the items in the grid. Either way, you get to the specific column via the DataListItem.FindControl method. When you set up the template column, you put controls in the column and give them IDs. FindControl will return the control in the column, based on its id. You then get the data from the control.Ji...

Data presentation control in another Data presentation control
 Hello,I want to make a menu with datalist or gridview control.Basically,the menu will be like this,Categories     Sub Categories.For example, for COMPUTING category there will be NOTEBOOKS DESKTOPS etc.There will be a image for CATEGORIES and linkbuttons with Subcategories.If I put a datalist inside a datalist and a link button inside the second datalist visually it satisfies my need.However,CommandArguments come from database to linkbutton.Andwhen one of these command buttons is cliked it must go to proper page.I dont know how to wrie an event_handler ,specifically, for...

how can i access a control in the edit template column of Datagrid
Hi I want to access or setfocus in a textbox control in the edit template column of a datagrid. i'm using the visual studio 2003 version. thanks for your responses..   Hi, You can browse through the following link. It might help you. ThanksSharmila Use FindControl to get the reference of the textbox in the ItemDataBound event. TextBox tb  = (TextBox )e.Item.FindControl("TextBox1");   I'm sorry.. it doesn't worked.. i need to set focus  to a text box control used in the datagrid's edit template column.. wi...

How to access datagrid template column textbox text in
I just want to access text from datagrid template column textbox,any one who knows solutions or suggestions(through codes), pls share it.Thanks in advance.  to access text from template column textbox... use FindControl() method... for Ex.,Label1.Text = ((TextBox)GridView1.Rows[0].Cell[0].FindControl("txtTextBox")).Text; //assuming that First Column; cells[0] is the TextBox Column... the code will retrieve text from first column textbox of the first row and assign to can refer to this link also.. Control.FindControl Method (String) (System.Web.UI)  Edit...

Datagrid Dynamic Template Columns with a Data-Driven User Control
All, I am writing a dynamic datagrid that contains X number of columns. The columns are of type Template. Each cell contains a Web user control (which is a database-driven dropdown list). The problem I am having is that when I dynamically create the colum I have to data-bind the dropdown list and apperently it does not it exists. The Web user control works like a champ if I call it directly from another page. This is the error: Object reference not set to an instance of an object. Public Sub Load_List() Line 44: Line 45: Histopathology_Values_List.DataSource =...

How to access a CheckBox in the header row of a Template Column in a data-bound DataGrid
All-- Please help. How can one get a handle to a CheckBox that is in the header row of template column in a DataGrid that is data-bound? See below for details on what does NOT work. Any ideas? Please advise. Thank you. --Mark Here is the code in the ASPX file... <asp:datagrid id="MainDataGrid" runat="server"> <headerstyle horizontalalign="Left" verticalalign="Top" backcolor="LightBlue" font-bold="True" font-size="x-small"></headerstyle> <itemstyle horizontalal...

Solution Title: Datagrid Template Column Radio Button (get access to the rb control)
Hi. I have a radio button in a template column of a datagrid. All I need to know is how to get access to this to be able to set the radio button as checked or unchecked (depending on the results of a query). I'm trying this: Dim rbactionneeded As RadioButton = CType(e.Item.FindControl("rbactionneeded"), RadioButton) If ansval = "Y" Then 'result from stored procedure rbactionneeded.Checked = True End if (very simplified). I'm getting an erro...

display XML data in datagrid with checkbox column <template column>
i can set the datagrid.datasource = myXmlDataset, but anyone know how i can hook an unbound column (template column with a checkbox) to one of my XML fields ??? i was thinking of creating a datatable from scratch, cycling thru the items in the XML document and wring them into the table, then filling myXmlDataset, then binding that dataset to my datagrid. but this has proved to be more of a challenge than i thought. anyone tried doing this before ??? is it even feasible ???"If it is secrect enough, you alone know it." I might be missing something but why don't you read you...

Issue with Template Columns & Bound Columns while updating the data in a GridView control
Hi, I'm facing the below problem (In general, ObjectDataSource is driving me crazy ! ) I have a simple gridview control and an ObjectDataSource is used to populate the grid. I'm trying to update a row and the corresponding tableadapter methods & stored procedure are in place. Each row has 2 checkboxes and 2 textboxes in edit mode. When the change the values in edit mode and hit update, the checkbox values changed are saved into the Database properly, whereas the textbox values are not being saved. If the textbox column is a bound column then the column is updated with <NULL> in...

Bind Data to an Image Control not in a Data Presentation Control
I've been searching for two days but I don't really know what to search for.I'm making a site for a photographer.  The Default.aspx page displays Albums by showing a title, image and description from the database table Albums. Click an album to view the contents and it passes the QueryString which is AlbumName.  The ViewAlbum.aspx page uses the QueryString to display an UpdatePanel holding a Large Image and a Repeater full of dynamically filled ImageButtons for thumbs.  Both are from the database table Photos and are retrieved using an ObjectDataSource. Click the ...

Datagrid Control, template columns
Hi all i am working on datagrid control. I have to columns both are template columns.The first template column contains a textbox control, the second column contains a dropdownlist. I need to bind the data to the first column fileupload control and the dropdownlist should be populated from the database. How do i go about doing this please help me.  Hi...If u want to Bind Text Box From Data Base then Bind TextBox Template as like below                          &l...

Control-Access in Template-Column ?
Hi! I createted a Template-Column in a DataGrid with a Dropdownlis set as edititem-control and bound it to values of a table on a MS-SQL-Server. So far so good - calling the edit command on runtime is working properly. The Items are correct i can select one and it will be written down to the database *but * I want to initialize the dropdownlist when calling th edit-command - the selecteditem should be a default-value. How can I achieve this. The Control is only exiting @ runtime ... Tryed to do sthg. like this: -- Private Sub DataGrid1_EditCommand(ByVal source...

Columns arrangement in DataGrid
Dear Friends, Please give me a solution for below problem, I have to bind a data table to a DataGrid, I will be not knowing no of columns and data until runtime, so I did not configured columns widh at design time. Now my client is asking me like, he want a facility to alter the column width at runtime, I mean he want to change columns width in client (IE), like window application. So, will you please tell me how to provide facility to change column width of a datagrid at client by user ? Thank you, Sreedhar Nasum.     Hi:   DataGrid will render as <table>. Ta...

Web resources about - Accessing Data in DataGrid Template Column -

Highest Percentage Of Opera Mini Users Accessing Facebook? Macau
If you were asked to guess which country had the highest percentage of users of Opera mobile Web browser Opera Mini users accessing Facebook ...

International Users Accessing Facebook Places Through US VPN Accounts
By using a virtual private network (VPN) hosted in the United States, Facebook users from around the world are accessing Facebook Places. The ...

What are some alternatives to Yodlee for accessing bank information?
Clay Loveless , Founder, Jexy. Co-founder, Mashery. Founder, Jexy. Co-founder, Mashery.

Cloud Console - Accessing files in cloud storage for iPad on the iTunes App Store
Get Cloud Console - Accessing files in cloud storage on the App Store. See screenshots and ratings, and read customer reviews.

Meryl Streep On Accessing The Characters Within - YouTube
Meryl Streep talks about the importance of an actors work representing their ability. CONNECT WITH AFI: ...

Accessing the Future Fund a sensible proposal, says super expert Daryl Dixon
As portfolios go, the Future Fund's asset allocation is concentrated in higher-risk investment, including equities and alternative assets.

Accessing my Super
I'm 57 - can I access my super?

Australia, US accessing Indonesian telephone data, leaked documents show
Newly disclosed documents from former US intelligence contractor Edward Snowden have revealed that Australian intelligence efforts against Indonesia ...

Euthanasia advocate Philip Nitschke detained at Melbourne Airport, accuses Customs officials of accessing ...
Euthanasia advocate Philip Nitschke has accused Customs officials of accessing hundreds of patients' sensitive records on his laptop after detaining ...

Frances Abbott scholarship: Sydney woman pleads guilty to accessing Whitehouse Institute records on PM's ...
A Sydney woman who leaked the student records of Tony Abbott's daughter pleads guilty. A Sydney woman who leaked the student records of Prime ...

Resources last updated: 12/11/2015 7:30:12 AM