Solved

Getting Value from Databound Row in Code-Behind

Posted on 2004-08-17
3
503 Views
Last Modified: 2010-05-18
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
0
Comment
Question by:Timbo87
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
3 Comments
 
LVL 25

Assisted Solution

by:nauman_ahmed
nauman_ahmed earned 100 total points
ID: 11827612
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
 
LVL 4

Accepted Solution

by:
hamood earned 400 total points
ID: 11827685
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
 
LVL 15

Author Comment

by:Timbo87
ID: 11827864
That did it, thanks.
0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Lots of people ask this question on how to extend the “MembershipProvider” to make use of custom authentication like using existing database or make use of some other way of authentication. Many blogs show you how to extend the membership provider c…
One of the pain points with developing AJAX, JavaScript, JQuery, and other client-side behaviors is that JavaScript doesn’t allow for cross domain request for pulling content. For example, JavaScript code on www.johnchapman.name could not pull conte…
A short tutorial showing how to set up an email signature in Outlook on the Web (previously known as OWA). For free email signatures designs, visit https://www.mail-signatures.com/articles/signature-templates/?sts=6651 If you want to manage em…
Finds all prime numbers in a range requested and places them in a public primes() array. I've demostrated a template size of 30 (2 * 3 * 5) but larger templates can be built such 210  (2 * 3 * 5 * 7) or 2310  (2 * 3 * 5 * 7 * 11). The larger templa…

740 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question