I have a nested gridview and I want to get the value of the first gridview and assign it to the commandArgument of a button. Can someone advise how to do it
As you will see in the code below I'm already getting the row index with the following code:
"
Text="Save Changes" />
What I need is the DataField="name" instead
See full code below.
<script language="javascript" type="text/javascript">
function divexpandcollapse(divname) {
var div = document.getElementById(divname);
var img = document.getElementById('img' + divname);
if (div.style.display == "none") {
div.style.display = "block"; img.src = "Images/Icons/minus.jpg";
} else { div.style.display = "none"; img.src = "Images/Icons/plus.jpg"; }
}</script>
<asp:DropDownList ID="DateSelection" runat="server" AutoPostBack="True" Height="21px"
Width="134px">
</asp:DropDownList>
<asp:GridView ID="GV_SL" runat="server" OnRowDataBound="gvUserInfo_RowDataBound"
OnRowCommand="GV_SL_RowCommand" AutoGenerateColumns="False"
DataSourceID="SQL_Weekly" AllowSorting="True">
<Columns>
<asp:TemplateField ItemStyle-Width="50px">
<ItemTemplate>
<a href="JavaScript:divexpandcollapse('div<%# Eval("name") %>');">
<img id="imgdiv<%# Eval("name") %>" width="15px" border="0" src="Images/Icons/plus.jpg" /></a></ItemTemplate>
<ItemStyle Width="40px" />
</asp:TemplateField>
<asp:BoundField DataField="name" HeaderText="Group" SortExpression="name" />
<asp:BoundField DataField="ASL" HeaderText="SL% Act" ReadOnly="True" SortExpression="ASL" />
<asp:TemplateField>
<ItemTemplate>
<tr>
<td colspan="100%">
<div id="div<%# Eval("name") %>" style="display: none; position: relative; left: 15px;
overflow: auto">
<asp:GridView ID="gvChildGrid" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="Metric" HeaderText=" " HeaderStyle-HorizontalAlign="Left" />
<asp:BoundField DataField="Actual" HeaderText="Actual" HeaderStyle-HorizontalAlign="Left" />
</Columns>
</asp:GridView>
<br />
<asp:UpdatePanel ID="UP_SecondPanel" runat="server" UpdateMode="Always" >
<ContentTemplate>
<%-- --%>
<asp:TextBox ID="TB_Comments" runat="server" Text="Example: Text will be entered here"
TextMode="MultiLine" Rows="4" Width="510px"></asp:TextBox>
<asp:Button ID="B_Save" runat="server" CommandName="AddText" CommandArgument="<%# CType(Container,GridViewRow).RowIndex %>"
Text="Save Changes" />
</ContentTemplate>
</asp:UpdatePanel>
<%-- --%>
</div>
</td>
</tr>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Any ideas will be appreceiated
Thanks
I sorted the problem with VB code. See below if it helps someone
Protected Sub GV_SL_RowCommand(ByVal sender As Object, _
ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs)
If (e.CommandName = "AddText") 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 = GV_SL.Rows(index)
Dim GroupName As String = GV_SL.Rows(index).Cells(1).Text
'Rest of the code here
End If
End Sub
Related
I have this gridview inside an updatepanel:
<asp:GridView ID="GridView1" runat="server" AllowPaging="True" AllowSorting="True"
AutoGenerateColumns="False" DataKeyNames="id" DataSourceID="" BackColor="White"
BorderColor="#CCCCCC" BorderStyle="None" BorderWidth="1px" ForeColor="Black"
GridLines="Horizontal" Height="100%" Width="100%" HorizontalAlign="Justify" CssClass="table-responsive-lg table-striped table-hover" CellPadding="5" Style="text-align: center" OnRowEditing="GridView1_RowEditing">
This edit button on the row:
<ItemTemplate>
<asp:LinkButton ID="btnSelect" runat="server" CausesValidation="False" CommandName="Edit"
ToolTip="Seleziona"><i class="far fa-hand-point-up fa-3x" aria-hidden="true"></i></asp:LinkButton>
</ItemTemplate>
And this dropdown inside an EditItemTemplate:
<asp:TemplateField HeaderText="Mittente" SortExpression="Mittente">
<ItemTemplate>
<asp:Label ID="Label3" runat="server" Text='<%#: Bind("Mittente") %>' CssClass="content"></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<div style="text-align: left">
<div class="wrapper">
<asp:Button ID="btnPrendiMail" runat="server" Text="Prendi" OnClick="btnPrendiMail_Click" CssClass="btn btn-default" />
<asp:SqlDataSource ID="sqlClienti" runat="server"
ConnectionString="<%$ ConnectionStrings:dbVulcanoConnectionString %>"
SelectCommand="select idcliente,RagSociale,concat(ragsociale,' [' ,idcliente, ']') as Descr from clienti order by RagSociale"></asp:SqlDataSource>
<asp:DropDownList ClientIDMode="Static" OnSelectedIndexChanged="ddlClienti_SelectedIndexChanged" ID="ddlClienti" runat="server" Font-Size="X-Large" Font-Bold="True" AutoPostBack="true" DataSourceID="sqlClienti" DataTextField="Descr" DataValueField="idCliente" AppendDataBoundItems="true" CssClass="select2-single form-control-div" >
<asp:ListItem Text="-- Cerca Cliente per ID o Ragione Sociale --" Value="0" Selected="True"></asp:ListItem>
</asp:DropDownList>
</div>
<asp:Label ID="lblEmailMittente" ClientIDMode="Static" runat="server" Text='<%#: Bind("Mittente") %>' CssClass="content"
Visible="false"></asp:Label>
</div>
</EditItemTemplate>
<ItemStyle Width="10%" />
</asp:TemplateField>
I would to change the selected value of the dropdown when the Edit button is pressed, executing this subroutine on RowEditing event of the gridview:
Protected Sub GridView1_RowEditing(sender As Object, e As GridViewEditEventArgs)
Dim gvRow As GridViewRow = GridView1.Rows.Item(e.NewEditIndex())
Dim ddlClienti As DropDownList = TryCast(gvRow.FindControl("ddlClienti"), DropDownList)
Dim lblEmailMittente As Label = TryCast(gvRow.FindControl("lblEmailMittente"), Label)
If dbVulcano.emails.Any(Function(m) m.email = lblEmailMittente.Text) Then
Dim email As emails = dbVulcano.emails.Where(Function(m) m.email = lblEmailMittente.Text).SingleOrDefault
ddlClienti.SelectedValue = email.rfCliente
ddlClientiIndexChanged()
End If
End Sub
But while debugging it I see that ddlClienti is = Nothing so the routine fails.
What is the right way to do this? Thanks
I did the same thing using a timer inside the template field
I have a control which I can call to populate the top of a aspx page with demographic information as follows.
<div runat="server" id="headerline" style="width:100%; background-color:#FFFFCC; border-color: #FFFFCC; " >
<asp:GridView ID="GridView1" skinID="headerline" runat="server" DataSourceID="odsPatientByID" AutoGenerateColumns="False" Width="100%" >
<HeaderStyle CssClass="invisible" />
<RowStyle Width="100px" />
<Columns>
<asp:HyperLinkField DataNavigateUrlFields="PATIENT_ID" DataNavigateUrlFormatString="~/demographics/search_demographics.aspx?PatientID={0}" Text="DEMOGRAPHICS " ItemStyle-HorizontalAlign="Left" >
</asp:HyperLinkField>
<ItemTemplate >
<asp:Label SkinID="headerline" ID="lblNAME" runat="server" Text=' Name: ' />
<asp:Label SkinID="headerline" ID="lblPTNAME" runat="server" Text='<%# Shis.SCR.UI.Common.CapitalisePatientName(Eval("PT_NAME")) %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField >
<ItemTemplate >
<asp:Label SkinID="headerline" ID="lblDoB" runat="server" Text=' DoB: ' />
<asp:Label SkinID="headerline" ID="lblDateofBirth" runat="server" Text='<%# Bind("N1_10_DATE_BIRTH") %>' />
<asp:Label skinID="headerlineage" ID="lblAge" runat="server" Text='<%# GetDisplayAge("" & Eval("N1_10_DATE_BIRTH"),"" & Eval("L_DEATH_STATUS")) %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField >
<ItemTemplate >
<asp:Label SkinID="headerline" ID="lblSex" runat="server" Text=' Gender: ' />
<asp:Label SkinID="headerline" ID="lblGender" runat="server" Text='<%# EVAL("GENDER") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
I display the demographic data like this and it works fine
<div>
<controls:Demoline id="demoLine1" runat="server" />
</div>
What I would like to do is hide the HyperLinkfield when I select a Print option on the page and I get taken to the print page. Is this possible and if so how?
Look into RowDataBound event for the grid, it fires every time a row is bound to the grid. Do you check for a print param, from querystring or where ever and hide hyperlink. On phone so don't have code to hand
Look at
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.rowdatabound(v=vs.110).aspx
Give your Hyperlink an id eg "MyHyperLink"
add this code:
protected void GridView1_OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if (Request.QueryString["print"] != "1")
return;
var link = e.Row.FindControl("MyHyperLink") as HyperLink;
if (link != null)
link.Visible = false;
}
and then my add to your asp:GridView element:
OnRowDataBound="GridView1_OnRowDataBound"
I'm binding data to GridView nested in ListView via ItemDataBound and when I'm paging ListView it's loosing datakey value.
Here is DataBound event:
Protected Sub gvResult_ItemDataBound(sender As Object, e As System.Web.UI.WebControls.ListViewItemEventArgs) Handles gvResult.ItemDataBound
If e.Item.ItemType = ListViewItemType.DataItem Then
Dim dbSrc As New SqlDataSource
dbSrc.SelectParameters.Clear()
Dim gv As GridView = e.Item.FindControl("gvPrices")
Dim currentItem As ListViewDataItem = DirectCast(e.Item, ListViewDataItem)
Dim currentDataKey As DataKey = Me.gvResult.DataKeys(currentItem.DataItemIndex)
dbSrc.ConnectionString = ConfigurationManager.ConnectionStrings("hotelbedsConnectionString").ConnectionString
dbSrc.SelectCommandType = SqlDataSourceCommandType.StoredProcedure
dbSrc.SelectCommand = "GetPriceTest"
dbSrc.SelectParameters.Add(New Parameter("SearchID", DbType.String, CStr(Request.QueryString("SearchID"))))
dbSrc.SelectParameters.Add(New Parameter("HotelCode", DbType.String, CStr(currentDataKey.Value)))
gv.DataSource = dbSrc
AddHandler gv.RowCommand, AddressOf MarkSelected
gv.DataBind()
End If
End Sub
I'm using normal paging control in ListView like this one:
<LayoutTemplate>
<div id="itemPlaceholderContainer" runat="server" style="">
<span runat="server" id="itemPlaceholder" />
</div>
<div style="">
<asp:DataPager ID="DataPager1" runat="server">
<Fields>
<asp:NumericPagerField ButtonCount="10" CurrentPageLabelCssClass="CurrentPage" NumericButtonCssClass="PageNumbers"
NextPreviousButtonCssClass="PageNumbers" NextPageText=" > " PreviousPageText=" < " />
</Fields>
</asp:DataPager>
</div>
</LayoutTemplate>
Error is: Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index
Here is full markup of ListView with nested GridView:
<asp:ListView ID="gvResult" runat="server" DataSourceID="ds_hotels" DataKeyNames="HotelCode">
<EmptyDataTemplate>
<span>No data was returned.</span>
</EmptyDataTemplate>
<ItemTemplate>
<div style="width: 96%; float: left;" class="dashed">
<div style="width: 18%; float: left;">
<asp:HyperLink ID="hlHotelInfo" runat="server" Text="Фотографии и информация" NavigateUrl='<%# Eval("HotelCode", "details/{0}") %>'
ImageUrl='<%# Eval("HotelCode", "hotelfront.ashx?HotelCode={0}") %>' CssClass="img_hotel"></asp:HyperLink></div>
<h2 class="title_hotels">
<asp:HyperLink ID="Label2" runat="server" Text='<%# ShowHotelName(Eval("HotelCode")) %>'
NavigateUrl='<%# Eval("HotelCode", "details/{0}") %>'></asp:HyperLink></h2>
<p>
<asp:Label ID="lblHotelDesc" runat="server" Text='<%# ShowHotelDescr(Eval("HotelCode")) %>' />
</p>
</div>
<asp:GridView runat="server" ID="gvPrices" AutoGenerateColumns="False" GridLines="None"
Width="100%" RowStyle-HorizontalAlign="Center" DataSourceID="ds_prices" DataKeyNames="ID">
<AlternatingRowStyle BackColor="#00FF99" />
<SelectedRowStyle Font-Bold="true" BackColor="BlanchedAlmond" />
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:ImageButton ID="addToBasket" runat="server" ImageUrl="~/img/32px/Add.png" ToolTip="Добавить в корзину"
OnCommand="MarkSelected" CommandName="Select" CommandArgument='<%# Eval("ID") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Стоимость">
<ItemTemplate>
<asp:Label ID="lblPrice" runat="server" Text='<%# ShowMarkUp(Eval("Price", "{0:#0}")) %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Currency" HeaderText="Валюта" SortExpression="Currency" />
<asp:BoundField DataField="AdultCount" HeaderText="Взрослых" SortExpression="AdultCount" />
<asp:BoundField DataField="ChildCount" HeaderText="Детей" SortExpression="ChildCount" />
<asp:BoundField DataField="RoomCount" HeaderText="Номеров" SortExpression="RoomCount" />
<asp:BoundField DataField="RoomTypeName" HeaderText="Тип номера" SortExpression="RoomTypename" />
<asp:TemplateField HeaderText="Питание" SortExpression="BoardShortName">
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Eval("BoardShortName") %>' ToolTip='<%# ShowToolTip(Eval("BoardShortName")) %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<RowStyle HorizontalAlign="Center" />
</asp:GridView>
<asp:SqlDataSource ID="ds_prices" runat="server" ConnectionString="<%$ ConnectionStrings:hotelbedsConnectionString %>"
SelectCommand="GetPriceTest" CancelSelectOnNullParameter="False" SelectCommandType="StoredProcedure">
<SelectParameters>
<asp:Parameter Name="SearchID" Type="String" />
<asp:Parameter Name="HotelCode" Type="String" />
</SelectParameters>
</asp:SqlDataSource>
</ItemTemplate>
<LayoutTemplate>
<div id="itemPlaceholder" runat="server">
</div>
<br />
<asp:DataPager ID="DataPager1" runat="server">
<Fields>
<asp:NumericPagerField ButtonCount="10" CurrentPageLabelCssClass="CurrentPage" NumericButtonCssClass="PageNumbers"
NextPreviousButtonCssClass="PageNumbers" NextPageText=" > " PreviousPageText=" < " />
</Fields>
</asp:DataPager>
</LayoutTemplate>
</asp:ListView>
Correct question is the half of the answer, yeah...
I shoud rather ask - why there is out of range exception.
The asnwer is here:
currentDataKey = Me.gvResult.DataKeys(currentItem.DisplayIndex)
#Abide, thanks for tryinh to help me!
Make sure that in the data being brought back from the database there is no entry with a null value in your datakey causing a negative index.And try this
Dim currentItem As ListViewDataItem = DirectCast(e.Item, ListViewDataItem)
If currentItem.DataItemIndex < Me.gvResult.Count-1 then
Dim currentDataKey As DataKey = Me.gvResult.DataKeys(currentItem.DataItemIndex)
End if
Dim HotelCode As String = currentDataKey("HotelCode") ' where the value in quotes would be the name of your datakey.
I have an Ajax panel first panel inside another panel second panel and an updateProgress linked to the first panel
With this I have two problems:
The updateProgress show the progress image when the second panel updates but not when the first panel updates
To update the 2nd panel I have to press the button inside the second panel twice
<asp:UpdateProgress ID="UProc_TabContainer" runat="server" AssociatedUpdatePanelID="UP_FirstPanel"
DisplayAfter="1">
<ProgressTemplate>
<div id="dvProgress" runat="server" style="position: absolute; top: 300px; left: 450px;
text-align: center;">
<asp:Image ID="wait" runat="server" ImageUrl="~/Images/wait3.gif" Height="120px"
Width="128px" />
</div>
</ProgressTemplate>
</asp:UpdateProgress>
<asp:UpdatePanel ID="UP_FirstPanel" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<script language="javascript" type="text/javascript">
function divexpandcollapse(divname) {
var div = document.getElementById(divname);
var img = document.getElementById('img' + divname);
if (div.style.display == "none") {
div.style.display = "block"; img.src = "Images/Icons/minus.jpg";
} else { div.style.display = "none"; img.src = "Images/Icons/plus.jpg"; }
}</script>
<asp:DropDownList ID="DateSelection" runat="server" AutoPostBack="True" Height="21px"
Width="134px">
</asp:DropDownList>
<asp:GridView ID="GV_SL" runat="server" OnRowDataBound="gvUserInfo_RowDataBound"
OnRowCommand="GV_SL_RowCommand" AutoGenerateColumns="false" DataSourceID="SQL_Weekly">
<Columns>
<asp:TemplateField ItemStyle-Width="50px">
<ItemTemplate>
<a href="JavaScript:divexpandcollapse('div<%# Eval("name") %>');">
<img id="imgdiv<%# Eval("name") %>" width="15px" border="0" src="Images/Icons/plus.jpg" /></a></ItemTemplate>
<ItemStyle Width="40px" />
</asp:TemplateField>
<asp:BoundField DataField="name" HeaderText="Group" SortExpression="name" />
<asp:BoundField DataField="ASL" HeaderText="SL% Act" ReadOnly="True" SortExpression="ASL" />
<asp:TemplateField>
<ItemTemplate>
<tr>
<td colspan="100%">
<div id="div<%# Eval("name") %>" style="display: none; position: relative; left: 15px;
overflow: auto">
<asp:GridView ID="gvChildGrid" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="Metric" HeaderText=" " HeaderStyle-HorizontalAlign="Left" />
<asp:BoundField DataField="Actual" HeaderText="Actual" HeaderStyle-HorizontalAlign="Left" />
</Columns>
</asp:GridView>
<br />
<asp:UpdatePanel ID="UP_SecondPanel" runat="server" UpdateMode="Always">
<ContentTemplate>
<%-- --%>
<asp:TextBox ID="TB_Comments" runat="server" Text="Example: Text will be entered here"
TextMode="MultiLine" Rows="4" Width="510px"></asp:TextBox>
<asp:Button ID="B_Save" runat="server" CommandName="AddText" CommandArgument="<%# CType(Container,GridViewRow).RowIndex %>"
Text="Save Changes" />
</ContentTemplate>
</asp:UpdatePanel>
<%-- --%>
</div>
</td>
</tr>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="DateSelection" EventName="SelectedIndexChanged" />
</Triggers>
Any ideas on what I'm doing wrong?
Thanks
I have resolved the 1st problem presented by removing AssociatedUpdatePanelID="UP_FirstPanel" from the UpdateProgress. I hope it helps someone
I've created a separate posting with further detail and simplified code for the second problem (Nested Ajax UpdatePanel in Gridview needs button control to be clicked twice)
I am using this gridview:
<asp:GridView ID="gvMessages" runat="server" AutoGenerateColumns = "false"
CaptionAlign="NotSet" CellPadding="5" onrowcommand="gvMessages_RowCommand">
<Columns>
<asp:TemplateField HeaderText="Avändare">
<ItemTemplate>
<%# GetSender((int)Eval("Sender"))%>
<br />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Ämne">
<ItemTemplate>
<%# Eval("Head")%>
<br />
</ItemTemplate>
</asp:TemplateField>
<asp:ButtonField Text="Öppna" CommandName="Open" />
</Columns>
</asp:GridView>
I want a textbox to show the message member of the bound object (Eval("Message")) of the row that has been clicked.
from the comments, and I would suggest to have the show/hide in the client, so you can save a round trip to the server
<asp:GridView ID="gvMessages" runat="server" AutoGenerateColumns = "false"
CaptionAlign="NotSet" CellPadding="5">
<Columns>
<asp:TemplateField HeaderText="Avändare">
<ItemTemplate>
<%# GetSender((int)Eval("Sender"))%>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField HeaderText="Ämne" DataField="Head" />
<asp:TemplateField HeaderText="Avändare">
<ItemTemplate>
<button class="btn-showmsg">Öppna</button>
<div class="message hide">
<asp:TextBox runat="server"
TextMode="MultiLine" Text="<%= Eval("Message") %>" />
</div>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
and in javascript
$(function() {
$(".btn-showmsg").click(function() {
var tr = $(this).closest("tr"), // the <tr>
msg = tr.find(".message"); // the div wraping the message
msg.show(); // show it
});
});
Now, the position and the placement of the message, it's all up to you, but I would suggest something like Bootstrap Modal to show it.
also, remember to add a style of .hide { display: none; }