How to read a dataitem from a parent repeater?
<asp:Repeater ID="rpt" runat="Server">
<ItemTemplate>
<%# DataBinder.Eval(Container.DataItem, "MyRepeaterDataItem")%>
<asp:GridView ID="gv" runat="Server">
<Columns>
<asp:TemplateField>
<HeaderTemplate>
<%# DataBinder.Eval(Container.DataItem, "MyRepeaterDataItem")%>
</HeaderTemplate>
<ItemTemplate>
TEXT
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</ItemTemplate>
</asp:Repeater>
I am trying to get the dataitem MyRepeaterDataItem belonging to the repeater to appear in the nested gridviews header.
I have tried using .Parent and .NamingContainer but cannot get the correct syntax using VB.NET
Assuming you're binding a Datasource to the GridView in the RepeaterItem's ItemDataBound Event Handler you can wire up a Handler for the RowCreated (or DataBound) Events of the GridView using AddHandler:
Private Sub rpt_ItemDataBound(sender As Object, e As RepeaterItemEventArgs) Handles rpt.ItemDataBound
If e.Item.ItemType = ListItemType.AlternatingItem OrElse e.Item.ItemType = ListItemType.Item Then
AddHandler gvTarget.RowCreated, AddressOf GridViewRowCreated
'Bind your Datasource to the GridView AFTER you wire it up:
'Dim gvTarget As GridView = CType(e.Item.FindControl("gv"), GridView)
'gvTarget.DataSource = lstYourDataSource
'gvTager.DataBind()
End If
End Sub
Then your Event Handler for gv's RowCreated can get the value from the parent RepeaterItem:
Public Sub GridViewRowCreated(ByVal sender As Object, ByVal e As GridViewRowEventArgs)
Dim lblHeader As Label = CType(e.Row.FindControl("lblGridViewHeader"), Label)
'Check due to Header/Footer.
If Not lblHeader Is Nothing Then
lblHeader.Text = DataBinder.Eval(CType(sender.Parent, RepeaterItem).DataItem, "MyRepeaterDataItem")
End If
End Sub
The code mentioned above requires you to add a label to your GridView's HeaderTemplate:
<asp:GridView ID="gv" runat="Server">
<Columns>
<asp:TemplateField>
<HeaderTemplate>
<asp:Label ID="lblGridViewHeader" runat="server"></asp:Label>
</HeaderTemplate>
<ItemTemplate>
TEXT
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Or optionally you could just do this in GridViewRowCreated:
e.Row.Cells(0).Text = DataBinder.Eval(CType(sender.Parent, RepeaterItem).DataItem, "MyRepeaterDataItem")
Get Parent Data Item From Any Nested Control
After a little trial and error I worked out a simple solution that can work without any code behind.
VB.NET
<HeaderTemplate>
<%# DataBinder.Eval(Container, "NamingContainer.NamingContainer.DataItem.MyRepeaterDataItem")%>
</HeaderTemplate>
Where MyRepeaterDataItem is the data column.
Related
I have a gridView with a textBox inside a templateField. I wan to extract the text of the textBox if a checkbox is marked in the row.
I have the gridView defined as follows
<asp:GridView ID="GV_Comments" runat="server" AutoGenerateColumns="False" DataKeyNames="id"
DataSourceID="SQL_Comments">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox runat="server" ID="Comment_Select" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="ID" HeaderText="ID" ReadOnly="True" SortExpression="ID" />
<asp:TemplateField HeaderText="comment" SortExpression="comment">
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("comment") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="CommentForPeriod" runat="server" Text='<%# Bind("comment") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:Button ID="B_Load" runat="server" Text="Transfer Selection" onclick="B_Load_Click" />
<br />
<asp:TextBox ID="CompiledText" runat="server" Width="662px" Rows="10"
TextMode="MultiLine"></asp:TextBox>
And the code as follows
Protected Sub B_Load_Click(ByVal sender As Object, ByVal e As EventArgs) '(sender As Object, e As System.EventArgs) Handles B_Load.Click
Dim FullText As String = ""
For Each row As GridViewRow In GV_Comments.Rows
Dim CB_Control As CheckBox = CType(row.FindControl("Comment_Select"), CheckBox)
Dim Txt_Control As TextBox = CType(row.FindControl("CommentForPeriod"), TextBox)
If CB_Control IsNot Nothing AndAlso CB_Control.Checked AndAlso Txt_Control IsNot Nothing Then
FullText = FullText & Txt_Control.Text & "<br/>"
End If
Next row
CompiledText.Text = FullText.ToString
End Sub
When I debug the code I can see that the Checkbox control is found but not the TextBox control. Would anyone see why?
You can't do like this. When you click the button: B_Load, then GridView is NOT in Edit mode. And this is why you can't get the TextBox, which is in EditItemTemplate.
You can only get the controls inside <ItemTemplate> in your button click as gridview is in Normal display Mode. <EditItemTemplate> controls are rendered only when GridView enters Edit mode.
So, you need to get the value of the Label: Label1 here actually, which has the same value and is inside <ItemTemplate> .
Dim Lbl_Control As Label= CType(row.FindControl("Label1"), Label)
// button click as usual, just get and check the value of Label control, rather than TextBox control.
Protected Sub B_Load_Click(ByVal sender As Object, ByVal e As EventArgs) '(sender As
Object, e As System.EventArgs) Handles B_Load.Click
Dim FullText As String = ""
For Each row As GridViewRow In GV_Comments.Rows
Dim CB_Control As CheckBox = CType(row.FindControl("Comment_Select"),
CheckBox)
Dim Lbl_Control As Label= CType(row.FindControl("Label1"), Label)
If CB_Control IsNot Nothing AndAlso CB_Control.Checked AndAlso Lbl_Control
IsNot Nothing Then
FullText = FullText & Lbl_Control.Text & "<br/>"
End If
Next row
CompiledText.Text = FullText.ToString
End Sub
Hi all I have a simpe ASP button inside a grid. But the onclick event doesn't seem to fire. Where did I go wrong?
Here's the first line of my aspx page.
<%# Page Title="Trainer Data" Language="vb" AutoEventWireup="false" MasterPageFile="~/Site.Master" CodeFile="TrainerData.aspx.vb" Inherits="TrainerData"%>
And the button inside my gridview..
<asp:GridView ID ="gvExecSummary" runat="server" CssClass="gridview" AllowSorting="false" AllowPaging="false" AutoGenerateColumns="false" Width="98%" >
<RowStyle Height="22px" />
<AlternatingRowStyle Height="22px" CssClass="bg" BackColor="LightGray"/>
<HeaderStyle Height="22px" BackColor="#4b6c9e" Font-Bold="true"/>
<Columns>
<asp:TemplateField HeaderStyle-HorizontalAlign="Left" HeaderStyle-Width="5%" HeaderText="Action">
<ItemTemplate>
<asp:Button ID="btnExecutiveGenerate" runat="server" Text="Generate" OnClientClick="btnExecutiveGenerate_Click" />
</ItemTemplate>
</asp:TemplateField>
P.S. I tried even onclick but it doesn't work either.
EDIT: My code for server side.
Protected Sub btnExecutiveGenerate_Click(sender As Object, e As EventArgs)
Dim gvrow As GridViewRow = CType(CType(sender, Control).Parent.Parent, GridViewRow)
Dim lblSchoolId As System.Web.UI.WebControls.Label = gvrow.FindControl("lblSchoolMasterID")
Dim lblFacultyId As System.Web.UI.WebControls.Label = gvrow.FindControl("lblFacultyMasterID")
Dim btnExecutiveGenerate As System.Web.UI.WebControls.Button = gvrow.FindControl("btnExecutiveGenerate")
PDF_Creation_Executive(Val(lblSchoolId.Text), Val(lblFacultyId.Text))
End Sub
Use Command Argumnet,
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="AddButton" runat="server"
CommandName="AddToCart"
CommandArgument="<%# CType(Container,GridViewRow).RowIndex %>"
Text="Add to Cart" />
</ItemTemplate>
</asp:TemplateField>
add code page side
Protected Sub GridView1_RowCommand(ByVal sender As Object, _ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs)
If (e.CommandName = "AddToCart") Then
' Retrieve the row index stored in the CommandArgument property.
Dim index As Integer = Convert.ToInt32(e.CommandArgument)
' Retrieve the row that contains the button
' from the Rows collection.
Dim row As GridViewRow = GridView1.Rows(index)
' Add code here to add the item to the shopping cart.
End If
End Sub
You need to handle the button click event of Gridview in RowCommand event
NOTE: Please see the CommandName & CommandArgument properties added to the button.
<asp:GridView ID ="gvExecSummary" runat="server" CssClass="gridview" AllowSorting="false" AllowPaging="false" AutoGenerateColumns="false" Width="98%" >
<RowStyle Height="22px" OnRowCommand="gvExecSummary_RowCommand" />
<AlternatingRowStyle Height="22px" CssClass="bg" BackColor="LightGray"/>
<HeaderStyle Height="22px" BackColor="#4b6c9e" Font-Bold="true"/>
<Columns>
<asp:TemplateField HeaderStyle-HorizontalAlign="Left" HeaderStyle-Width="5%" HeaderText="Action">
<ItemTemplate>
<asp:Button ID="btnExecutiveGenerate" runat="server" Text="Generate" CommandName="GenerateExecutive" CommandArgument="<%#((GridViewRow)Container).RowIndex %>" />
</ItemTemplate>
</asp:TemplateField>
And and RowCommand event will be..
protected void gvExecSummary_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "GenerateExecutive")
{
// button click code goes here
}
}
change OnClientClick event to OnClick if btnExecutiveGenerate_Click is vb.net event handler
<asp:Button ID="btnExecutiveGenerate" runat="server" Text="Generate"
OnClick="btnExecutiveGenerate_Click"/>
OnClientClick event use to execute client-side script, if you have given OnClientClick event with OnClick event, then if OnClientClick return true only it will call OnClick event.
so make sure you are returning true or false from OnClientClick event if you using it.
note that if you are loading data in page laod, do as below
Sub Page_Load
If Not IsPostBack
LoadGridViewData()
End If
End Sub
This may help someone, but I was experiencing edit buttons not firing the event within rows (and not footer).
The cause was a gridview containing a label, which had the same ID as one elsewhere on the page.
Seemingly this did not cause problems for the footer row, which did not contain any such labels.
I hope this helps someone.
I have the following GridView, which has as DataSource a List<T>:
<asp:GridView ID="gvDownloads" UseAccessibleHeader="False"
AutoGenerateColumns="False" runat="server" PageSize="10" AllowPaging="true"
CellPadding="4" CellSpacing="1" GridLines="None" DataKeyNames="productid">
<EmptyDataTemplate>
No licenses found
</EmptyDataTemplate>
<Columns>
<asp:TemplateField HeaderText="Id" >
<ItemTemplate>
<%# Eval("ProductId")%>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Product Name">
<ItemTemplate>
<%# Eval("ProductName")%>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Stock Code">
<ItemTemplate>
<%# Eval("StockCode")%>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Which renders correctly and with the proper values.
Now, I would like to modify on the fly the field StockCode and in order to do so I have in my code behind:
Sub gvDownloads_RowDataBound(ByVal sender As Object, ByVal e As GridViewRowEventArgs) Handles gvDownlads.RowDataBound
If e.Row.RowType = DataControlRowType.DataRow Then
e.Row.Cells(2).Text = StockCodeConverter.Convert(e.Row.Cells(2).Text)
End If
End Sub
But the data cells corresponding to StockCode are empty. Now I tried to debug and for some reason the code finds just the value of the header row. The values of the other rows are string.Empty or &nsbp. Might it depend on the List as DataSource?
Use ASP.NET controls instead, for example Labels:
If e.Row.RowType = DataControlRowType.DataRow Then
Dim lblStockCode = DirectCast(e.Row.FindControl("lblStockCode"), Label)
lblStockCode.Text = StockCodeConverter.Convert(lblStockCode.Text)
End If
on aspx:
<asp:TemplateField HeaderText="Stock Code">
<ItemTemplate>
<asp:Label Id="LblStockCode" runat="server" Text='<%# Eval("StockCode") %>'></asp:label>
</ItemTemplate>
</asp:TemplateField>
You can even omit the Eval on aspx and set the Text property completely in codebehind:
If e.Row.RowType = DataControlRowType.DataRow Then
Dim row = DirectCast(e.Row.DataItem, DataRowView)
Dim lblStockCode = DirectCast(e.Row.FindControl("lblStockCode"), Label)
lblStockCode.Text = StockCodeConverter.Convert(row["StockCode"].ToString)
End If
Edit: If you want to stay with your text and also with the TemplateField you could cast the first control in the cell which is a autogenerated DataBoundLiteralControl when there's only text and use it's Text property.
Dim StockCode = DirectCast(e.Row.Cells(2).Controls(0), DataBoundLiteralControl).Text
But that makes your code less readable in my opinion.
I think in GridView RowDataBound Event as the Binding is still in process you are not getting any Value...I would suggest you to use "DataRowView"
DataRowView drv = (DataRowView)e.Row.DataItem;
e.Row.Cells(2).Text = drv["StockCode"].ToString();
This is my Gridview code
<asp:DataGrid id="dg" runat="server" ondeletecommand="Delete_Item" >
<columns>
<asp:buttoncolumn buttontype="LinkButton" commandname="Delete" text="Remove" />
</columns>
<HeaderStyle BackColor="#95C736" ForeColor="White" Font-Bold="True" />
</asp:DataGrid>
I want to replace my buttoncolumn with an image, what must I do to my GridView?
I would use a template column for this:
<asp:DataGrid ID="DataGrid1" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:TemplateColumn>
<ItemTemplate>
<asp:ImageButton ID="btnDelete" runat="server" ImageUrl="/images/delete.png" CommandName="Delete" />
</ItemTemplate>
</asp:TemplateColumn>
</Columns>
</asp:DataGrid>
Replace the Button Column with a TemplateColumn with allows you to put standard asp controls inside. Then you can handle the Datagrid_ItemCommand event normally.
<asp:DataGrid ID="dgTest" runat="server">
<Columns>
<asp:TemplateColumn>
<ItemTemplate>
<asp:ImageButton ID="ibtnDelete" runat="server" CommandName="cmdDelete"
ImageUrl="~/images/delete.png" />
</ItemTemplate>
</asp:TemplateColumn>
</Columns>
</asp:DataGrid>
The ItemCommand handler would be something like:
Protected Sub dgTest_ItemCommand(ByVal source As Object, ByVal e As System.Web.UI.WebControls.DataGridCommandEventArgs) Handles dgTest.ItemCommand
If (e.CommandName = "cmdDelete") Then
Response.Write("the command argument was :" & e.CommandArgument)
End If
End Sub
The only other thing you would need to do is bind some data to the image button for a command argument. I usually do something like:
Protected Sub dgTest_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DataGridItemEventArgs) Handles dgTest.ItemDataBound
If (e.Item.ItemType = ListItemType.Item Or e.Item.ItemType = ListItemType.AlternatingItem) Then
Dim di As FAQTable = e.Item.DataItem
DirectCast(e.Item.FindControl("ibtn"), ImageButton).CommandArgument = di.FAQID
End If
End Sub
You could also use an asp:image control with an asp:Hyperlink control to get the same results.
One thing I just did that worked awesome is to put encoded html into the text. Text="<img src='images/btn-find.png' class='ttip' alt='View Details' />" This let me know only put in the img src, but also specify a class and an alt tag.
All you need to do is use single tick marks and encode your <> with gt and lt.
I've got an asp:DataGrid which has an asp:Gridview within it and this has many nested asp:Repeater's within that and i'm trying to reference the nested repeater from within my OnItemDataBound function
My code is similar to this
<asp:Datagrid runat="server" id="DataGrid1" OnItemDataBound="ItemDB" AutoGenerateColumns="false" Gridlines="None">
<Columns>
<asp:TemplateColumn HeaderText="">
<ItemTemplate>
<asp:GridView id="GridView1" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Repeater id="Repeater1" runat="server">
<ItemTemplate>
<p>Test</p>
</ItemTemplate>
</asp:Repeater>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</ItemTemplate>
</asp:TemplateColumn>
</Columns>
</asp:Datagrid>
bit complicated but that's kinda what i'm working with.
In my ItemDB command I have this
Sub ItemDB(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DataGridItemEventArgs)
Dim drv As DataRowView = CType(e.Item.DataItem, DataRowView)
If e.Item.ItemType = ListItemType.Item Or e.Item.ItemType = ListItemType.AlternatingItem Then
If CType(e.Item.FindControl("GridView1"), GridView).Visible = True Then
CType(e.Item.FindControl("Repeater"), GridView).Visible = True
End If
End If
End Sub
but i get the error
Object reference not set to an instance of an object
and i'm guessing it's because i am referencing a Repeater within a GridView
Any ideas how to reference this properly?
This code may not be the simplest way of doing this but i've taken over someone else's work and need a quick fix before re-coding it all
Thanks in advance
You'll have to find the Gridview in the template and then register the event for it's RowDataBound, and the find the repeater in the event handler. You should use the OnItemCreated Event to register the OnItemDataBound events, but the easiest would be to indicate the methods in your .aspx:
<asp:GridView id="GridView1" runat="server" AutoGenerateColumns="false" onrowdatabound="GridView1_RowDataBound">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Repeater id="Repeater1" runat=""server"
onitemdatabound="Repeater1_ItemDataBound">
<ItemTemplate>
<p>Test</p>
</ItemTemplate>
</asp:Repeater>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
and in your code behind:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
//you could find the repeater in the gridview's itemtemplate here
// to the BulletedList
if (e.Row.RowType == DataControlRowType.DataRow)
{
Repeater rpt = (Repeater)e.Row.FindControl("Repeater1");
rpt.Visible = false;
}
}
protected void Repeater1_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
//you could find controls in the repeater's itemtemplate here.
}