Getting Value from Databound Row in Code-Behind

I have a DataGrid column (TemplateColumn) that is databound and I need to get the text from it. Normally I would just use e.Item.Cells[0].Text, but I came to the conclusion that since data binding is a form of late binding, it's not available in code behind. How can I get around this?

Thanks,
Tim
LVL 15
Timbo87Asked:
Who is Participating?

Improve company productivity with a Business Account.Sign Up

x
 
hamoodConnect With a Mentor Commented:
if you wanted to do some changes in the text or grid col then you can do that is item_created event of the grid here is small example in which i have add ... at the end of text if it is larger than 70 char

Private Sub Grid_ItemCreated(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DataGridItemEventArgs) Handles Grid.ItemCreated
        Dim lbl As New System.Web.UI.WebControls.Label
        lbl = CType(e.Item.FindControl("lblQuestion"), System.Web.UI.WebControls.Label)
        Dim d As System.Data.Common.DbDataRecord
        d = e.Item.DataItem
        If Not d Is Nothing Then
            If Not lbl Is Nothing Then
                Dim strVal As String = d.GetValue(1)
                If Not strVal Is Nothing AndAlso strVal <> "" Then
                    If strVal.Length > 70 Then
                        lbl.Text = strVal.Substring(0, 70) & "..."
                    Else
                        lbl.Text = strVal
                    End If
                End If
            End If
        End If
    End Sub

if you want to check that value and wanted to make any decesion on that value then you need to write itemdatabound event. here is small exaple in which i am attaching javascript window.open method with asp:link

Grid_ItemDataBound: its is last event of the grid in which we can do some actions on the grid cols.

Private Sub Grid_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DataGridItemEventArgs) Handles Grid.ItemDataBound
        If e.Item.ItemType = ListItemType.Item OrElse e.Item.ItemType = ListItemType.AlternatingItem Then
            Dim lnk As New System.Web.UI.WebControls.HyperLink
            lnk = CType(e.Item.FindControl("lnkDelete"), System.Web.UI.WebControls.HyperLink)
            lnk.NavigateUrl = "javascript:OpenDeleteWindow('PollQuestionDelete.aspx','" & e.Item.Cells(0).Text & "')"
        End If
    End Sub


In the databound method you can get values of the cols like e.Item.Cells(0).Text but i item_created event data is not bound to cols you have to get the data like this

Dim d As System.Data.Common.DbDataRecord
        d = e.Item.DataItem


hamood
0
 
nauman_ahmedConnect With a Mentor Commented:
You can get the text at DataGrid_ItemDataBound or DataGrid_ItemCreated event. What exactly are you trying to do?
Have a look at the following MSDN example as it will clear ur mind:

<%@ Page Language="C#" AutoEventWireup="True" %>
<%@ Import Namespace="System.Data" %>
 
<html>
<script language="C#" runat="server">
 
   DataTable Cart;
   DataView CartView;
 
   ICollection CreateDataSource()
   {
      DataTable dt = new DataTable();
      DataRow dr;
 
      dt.Columns.Add(new DataColumn("IntegerValue", typeof(Int32)));
      dt.Columns.Add(new DataColumn("StringValue", typeof(string)));
      dt.Columns.Add(new DataColumn("CurrencyValue", typeof(double)));
 
      for (int i = 0; i < 10; i++)
      {
         dr = dt.NewRow();
 
         dr[0] = i;
         dr[1] = "Item " + i.ToString();
         dr[2] = 1.23 * (i+1);
 
         dt.Rows.Add(dr);
      }
 
      DataView dv = new DataView(dt);
      return dv;
   }
 
   void Page_Load(Object sender, EventArgs e)
   {
 
      if (!IsPostBack)
      {
         // Need to load this data only once.
         ItemsGrid.DataSource = CreateDataSource();
         ItemsGrid.DataBind();
      }
 
   }
 
   void Item_Created(Object sender, DataGridItemEventArgs e)
   {
 
      Label1.Text = Label1.Text + " " + e.Item.ItemIndex;
 
   }
 
</script>
 
<body>
 
   <form runat=server>

      <h3>DataGrid ItemCreated Example</h3>
 
      <asp:DataGrid id="ItemsGrid" runat="server"
           BorderColor="black"
           BorderWidth="1"
           CellPadding="3"
           ShowFooter="true"
           OnItemCreated="Item_Created"
           AutoGenerateColumns="true">

         <HeaderStyle BackColor="#00aaaa">
         </HeaderStyle>

         <FooterStyle BackColor="#00aaaa">
         </FooterStyle>
   
      </asp:DataGrid>
 
      <br>
 
      <asp:Label id="Label1"
           Text="Order of items created: " 
           runat="server"/>

      <br>

      <asp:Label id="Label2"
           Text="Note: The -1's refer to the header and footer."
           runat="server"/>
 
   </form>
 
</body>
</html>
[JScript]
<%@ Page Language="JScript" AutoEventWireup="True" %>
<%@ Import Namespace="System.Data" %>
 
<html>
<script language="JScript" runat="server">
 
      var Cart : DataTable;
      var CartView : DataView;
 
      function CreateDataSource() : ICollection
      {
       
         var dt : DataTable = new DataTable();
         var dr : DataRow;
 
         dt.Columns.Add(new DataColumn("IntegerValue", Int32));
         dt.Columns.Add(new DataColumn("StringValue", System.String));
         dt.Columns.Add(new DataColumn("CurrencyValue", double));
 
         for (var i : int = 0; i < 9; i++)
         {
            dr = dt.NewRow();
 
            dr[0] = i;
            dr[1] = "Item " + i.ToString();
            dr[2] = 1.23 * (i+1);
 
            dt.Rows.Add(dr);
         }
 
         var dv : DataView = new DataView(dt);
         return dv;
      }

 
   function Page_Load(sender, e : EventArgs)
   {
 
      if (!IsPostBack)
      {
         // Need to load this data only once.
         ItemsGrid.DataSource = CreateDataSource();
         ItemsGrid.DataBind();
      }
 
   }
 
   function Item_Created(sender, e : DataGridItemEventArgs)
   {
 
      Label1.Text = Label1.Text + " " + e.Item.ItemIndex;
 
   }
 
</script>
 
<body>
 
   <form runat=server>

      <h3>DataGrid ItemCreated Example</h3>
 
      <asp:DataGrid id="ItemsGrid" runat="server"
           BorderColor="black"
           BorderWidth="1"
           CellPadding="3"
           ShowFooter="true"
           OnItemCreated="Item_Created"
           AutoGenerateColumns="true">

         <HeaderStyle BackColor="#00aaaa">
         </HeaderStyle>

         <FooterStyle BackColor="#00aaaa">
         </FooterStyle>
   
      </asp:DataGrid>
 
      <br>
 
      <asp:Label id="Label1"
           Text="Order of items created: " 
           runat="server"/>

      <br>

      <asp:Label id="Label2"
           Text="Note: The -1's refer to the header and footer."
           runat="server"/>
 
   </form>
 
</body>
</html>
[Visual Basic]

<%@ Page Language="VB" AutoEventWireup="True" %>
<%@ Import Namespace="System.Data" %>
 
<html>
   <script runat="server">
 
      Function CreateDataSource() As ICollection

         ' Create sample data for the DataGrid control.
         Dim dt As DataTable = New DataTable()
         Dim dr As DataRow
 
         ' Define the columns of the table.
         dt.Columns.Add(New DataColumn("IntegerValue", GetType(Int32)))
         dt.Columns.Add(New DataColumn("StringValue", GetType(String)))
         dt.Columns.Add(New DataColumn("CurrencyValue", GetType(Double)))
 
         ' Populate the table with sample values.
         Dim i As Integer        

         For i=0 To 10

            dr = dt.NewRow()
 
            dr(0) = i
            dr(1) = "Item " & i.ToString()
            dr(2) = 1.23 * (i + 1)
 
            dt.Rows.Add(dr)
         
         Next i
 
         Dim dv As DataView = New DataView(dt)

         return dv
     
      End Function
 
      Sub Page_Load(sender As Object, e As EventArgs)
 
         ' Load sample data only once, when the page is first loaded.
         If Not IsPostBack Then
         
            ItemsGrid.DataSource = CreateDataSource()
            ItemsGrid.DataBind()
         
         End If

      End Sub
 
      Sub Item_Created(sender As Object, e As DataGridItemEventArgs)
 
         ' Customize the footer section with an image.
         If e.Item.ItemType = ListItemType.Footer Then        
 
           ' Create an Image control.
           Dim NewImageControl As Image = New Image()

           ' Set the properties of the Image control.
           NewImageControl.ImageUrl = "Image1.jpg"
           NewImageControl.AlternateText = "Image 1"
           
           ' Add the Image control to the Controls collection of the
           ' cell representing the third column in the DataGrid.
           e.Item.Cells(2).Controls.Add(NewImageControl)

         End If        
 
      End Sub
 
</script>
 
<body>
 
   <form runat=server>

      <h3>DataGrid ItemCreated Example</h3>
 
      <asp:DataGrid id="ItemsGrid" runat="server"
           BorderColor="black"
           BorderWidth="1"
           CellPadding="3"
           ShowFooter="true"
           OnItemCreated="Item_Created">

         <HeaderStyle BackColor="#00aaaa">
         </HeaderStyle>

         <FooterStyle BackColor="#00aaaa">
         </FooterStyle>
   
      </asp:DataGrid>

   </form>
 
</body>
</html>
[C#]

<%@ Page Language="C#" AutoEventWireup="True" %>
<%@ Import Namespace="System.Data" %>
 
<html>
   <script runat="server">
 
      ICollection CreateDataSource()
      {

         // Create sample data for the DataGrid control.
         DataTable dt = new DataTable();
         DataRow dr;
 
         // Define the columns of the table.
         dt.Columns.Add(new DataColumn("IntegerValue", typeof(Int32)));
         dt.Columns.Add(new DataColumn("StringValue", typeof(String)));
         dt.Columns.Add(new DataColumn("CurrencyValue", typeof(Double)));
 
         // Populate the table with sample values.
         for (int i=0; i<=10; i++)
         {

            dr = dt.NewRow();
 
            dr[0] = i;
            dr[1] = "Item " + i.ToString();
            dr[2] = 1.23 * (i + 1);
 
            dt.Rows.Add(dr);
         
         }
 
         DataView dv = new DataView(dt);

         return dv;
     
      }
 
      void Page_Load(Object sender, EventArgs e)
      {
 
         // Load sample data only once, when the page is first loaded.
         if (!IsPostBack)
         {
         
            ItemsGrid.DataSource = CreateDataSource();
            ItemsGrid.DataBind();
         
         }

      }
 
      void Item_Created(Object sender, DataGridItemEventArgs e)
      {
 
         // Customize the footer section with an image.
         if(e.Item.ItemType == ListItemType.Footer)
         {        
 
           // Create an Image control.
           Image NewImageControl = new Image();

           // Set the properties of the Image control.
           NewImageControl.ImageUrl = "Image1.jpg";
           NewImageControl.AlternateText = "Image 1";
           
           // Add the Image control to the Controls collection of the
           // cell representing the third column in the DataGrid.
           e.Item.Cells[2].Controls.Add(NewImageControl);

         }        
 
      }
 
</script>
 
<body>
 
   <form runat=server>

      <h3>DataGrid ItemCreated Example</h3>
 
      <asp:DataGrid id="ItemsGrid" runat="server"
           BorderColor="black"
           BorderWidth="1"
           CellPadding="3"
           ShowFooter="true"
           OnItemCreated="Item_Created">

         <HeaderStyle BackColor="#00aaaa">
         </HeaderStyle>

         <FooterStyle BackColor="#00aaaa">
         </FooterStyle>
   
      </asp:DataGrid>

   </form>
 
</body>
</html>


HTH, Nauman
0
 
Timbo87Author Commented:
That did it, thanks.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.