Solved

Getting Value from Databound Row in Code-Behind

Posted on 2004-08-17
3
480 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
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

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

AJAX ModalPopupExtender has a required property "TargetControlID" which may seem to be very confusing to new users. It means the server control that will be extended by the ModalPopup, for instance, if when you click a button, a ModalPopup displays,…
IntroductionWhile developing web applications, a single page might contain many regions and each region might contain many number of controls with the capability to perform  postback. Many times you might need to perform some action on an ASP.NET po…
Sending a Secure fax is easy with eFax Corporate (http://www.enterprise.efax.com). First, Just open a new email message.  In the To field, type your recipient's fax number @efaxsend.com. You can even send a secure international fax — just include t…
This demo shows you how to set up the containerized NetScaler CPX with NetScaler Management and Analytics System in a non-routable Mesos/Marathon environment for use with Micro-Services applications.

757 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

Need Help in Real-Time?

Connect with top rated Experts

17 Experts available now in Live!

Get 1:1 Help Now