I have an issue with having a asp.net Grid View loaded into a div tag on a page (UI/Host.aspx). The Grid View itself is on a seperate page (GridViews/GridView1.aspx) and I'm using the jQuery load() function to load this page into the div tag.
My problem is when sorting the grid view it tries to postback to the page that's hosting it, and comes back with the error "Unable to find page UI/GridView1.aspx", is there a way to override this so that it post backs to itself, (which I assumed it would but doesn't) or is there an easier way to do the sorting.
Is there any other way of doing this, even if it means getting rid of the GridView altogether and using a repeater and table?
Below is the code:
UI/Hosts.aspx
//jQuery to load the div with the page UI/Hosts.aspx
$(document).ready(function() {
StartRefresh();
});
function startRefresh()
{
refreshID = setInterval(function() {
DisplayDate();
$("#divDests").load("../GridViews/Gridview1.aspx?ConfigID=" + $("#ctl00_MainContent_dlConfiguration").val() + "&ModuleID=" + $("#ctl00_MainContent_ddlModule").val());
}, $("#ctl00_MainContent_ddlRefresh :selected").val());
}
GridViews/Gridview1.aspx;
//Markup for GridViews/Gridview1.aspx
<html>
<head><title></title></head>
<body>
<form runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<asp:UpdatePanel ID="up1" runat="server">
<ContentTemplate>
<br />
<asp:GridView Font-Size="8.7pt" ID="gvLiveDest" runat="server" AutoGenerateColumns="False"
EmptyDataText="No Records Found" AllowSorting="true"
onsorting="gvLiveDest_Sorting" onrowcreated="gvLiveDest_RowCreated" OnRowDataBound="gvLiveDest_RowDataBound">
<Columns>
<asp:TemplateField HeaderText="Name" SortExpression="DestinationName" HeaderStyle-CssClass="centralalignment">
<ItemTemplate>
<asp:Label ID="lblDescription" runat="server" Text='<%# WebHelper.HTMLSafe(Eval("Description")) %>' ToolTip='<%# WebHelper.HTMLSafe(Eval("Description")) %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Logged <br /> In" HeaderStyle-CssClass="centralalignment" SortExpression="LoggedIn" >
<ItemStyle CssClass="centralalignment" />
<ItemTemplate>
<asp:Label ID="lblLoggedIn" runat="server" Text='<%# SetLoggedIn(Convert.ToBoolean(Eval("Active"))) %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Current<br />Status" HeaderStyle-CssClass="centralalignment" SortExpression="LastStatus" >
<ItemStyle CssClass="centralalignment" />
<ItemTemplate>
<asp:Label ID="lblCurrentStatus" runat="server" Text='<%# WebHelper.HTMLSafe(Eval("LastStatus")) %>' ToolTip='<%#Eval("LastStatus") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Time in<br />Current<br />Status" HeaderStyle-CssClass="centralalignment" SortExpression="CurrentDuration">
<ItemStyle CssClass="RightAlignment" />
<ItemTemplate>
<asp:Label ID="lblCurrentTime" runat="server" Text='<%# ICT.DAL.Reporting.CallDurFormat(Eval("CurrentDuration")) %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Lines" HeaderText="Lines" HeaderStyle-CssClass="centralalignment" SortExpression="Lines"
ItemStyle-CssClass="centralalignment" />
<asp:BoundField DataField="LinesBusy" HeaderText="Lines <br /> Busy" HeaderStyle-CssClass="centralalignment"
ItemStyle-CssClass="centralalignment" ReadOnly="True" HtmlEncode="False" SortExpression="LinesBusy" />
<asp:BoundField DataField="LinesAvailable" HeaderStyle-CssClass="centralalignment"
ItemStyle-CssClass="centralalignment" SortExpression="LinesAvailable"
HeaderText="Lines <br /> Available" HtmlEncode="false" ReadOnly="True" />
<asp:TemplateField HeaderText="Last Call Time" SortExpression="Timestamp" HeaderStyle-CssClass="centralalignment">
<ItemTemplate>
<asp:Label ID="lblLastCallTime" runat="server" Text='<%# WebHelper.HTMLSafe(Eval("LastCallTime")) %>' ToolTip='<%# WebHelper.HTMLSafe(Eval("LastCallTime")) %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</ContentTemplate>
</asp:UpdatePanel>
</form>
</body>
</html>
And the onSort Event Code (However it never hits this)
protected void gvLiveDest_Sorting(object sender, GridViewSortEventArgs e)
{
if (string.Compare(e.SortExpression, ViewState["SortField"].ToString(), true) == 0)
{
_sortDir = (_sortDir == "ASC") ? "DESC" : "ASC";
}
else
_sortDir = "ASC";
_SortField = e.SortExpression;
ViewState["SortField"] = e.SortExpression;
ViewState["sortDir"] = _sortDir;
BindLiveDestination();
}
I switched over to client-side paging/sorting a while ago and haven't been happier. Of course, you would need to set AllowSorting="false" and AllowPaging="false" in your GridView.
You could put it into an iframe...
Related
I'm working on an existing project, doing some updates and have troubles setting the value of "FenSelectedValue" in the "FenDropDownListRoles" Control.
I keep getting the error:
Databinding methods such as Eval(), XPath(), and Bind() can only be used in the context of a databound control in repeater control
But the eval in the Label control works fine. I've been reading here and there, and I read things about it not being bound at the right time so I moved the control from "EditItemTemplate" where it eventually should be to "ItemTemplate", to test it, but still no luck..
<ItemTemplate>
<asp:Label ID="lblRolOmschrijving" Text='<%# Eval("Rol_omschrijving") %>' runat="server" />
<fen:FenDropDownListRoles ID="ddlRoles" FenSelectedValue='<%# Eval("Rol_omschrijving") %>' runat="server" Watermark="AdministratorType" Required="true" ValidationGroup="grpAddUser" />
</ItemTemplate>
Here's how I've learned to set drop down selected items in a grid view.
Example grid:
<div id="gridContainerFormulations">
<script type="text/javascript">
$(document).ready(function () {
//This is done here, instead of codebehind, because the SelectedValue property of the drop down list
//simply does not work when databinding. I set the two 'hid' values via the RowEditing event
$("[id$='drpLotNumber']").val($("#hidSelectedFormulationLotNo").val());
});
</script>
<asp:hiddenfield runat="server" id="hidSelectedFormulationLotNo" value="-1" />
<asp:gridview id="dgrStudyFormulations" cssclass="data" runat="server" allowpaging="False" autogeneratecolumns="False"
datakeynames="Id, FormulationLotNo, FormulationNo">
<Columns>
<asp:BoundField HeaderText="Formulation" ReadOnly="True" DataField="FormulationName" />
<asp:TemplateField HeaderText="Lot #">
<EditItemTemplate>
<asp:dropdownlist ID="drpLotNumber" AddBlank="False" runat="server" />
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblLotNumber" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "FormulationLot.Name")%>' />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField HeaderText="AI in Formulation" ReadOnly="True" DataField="ActiveIngredientName" />
<asp:TemplateField HeaderText="AI Of Interest">
<EditItemTemplate>
<asp:CheckBox ID="chkOfInterest" Checked='<%# DataBinder.Eval(Container.DataItem, "OfInterest")%>' runat="server" />
</EditItemTemplate>
<ItemTemplate>
<%--<asp:Label ID="lblOfInterest" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "OfInterest")%>' />--%>
<asp:image runat="server" id="imgOfInterest" Visible="False" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField HeaderText="AI Amount" ReadOnly="True" DataField="AIAmountText" />
<asp:CommandField ShowEditButton="True" ShowCancelButton="True" ShowDeleteButton="True"/>
</Columns>
</asp:gridview>
Then in row_editing event of grid:
SelectedFormulationLotNo = CType(dgrStudyFormulations.DataKeys(e.NewEditIndex)("FormulationLotNo"), String)
Which sets the hidden field in the HTML
Property SelectedFormulationLotNo() As String
Get
Return hidSelectedFormulationLotNo.Value.Trim()
End Get
Set(value As String)
If String.IsNullOrEmpty(value) Then
hidSelectedFormulationLotNo.Value = String.Empty
Else
hidSelectedFormulationLotNo.Value = value.Trim()
End If
End Set
End Property
And then the jQuery function call sets the correct option in the newly editable row in the grid.
How I finally did it(but leaving the answer on Rake36's answer, since it probably works too and got me in the direction I needed) Since I couldn't get the Javascript to work for some reason and I knew from messing around that I could get the value of labels in "RowDataBound" I combined the method of Rake36 with the hidden field and set the value in the codebehind (in RowDataBound)
In the codebehind:
protected void gvwUsers_RowDataBound(object sender, GridViewRowEventArgs e)
{
DropDownList DropDownListRol = (DropDownList)e.Row.FindControl("ddlRolOmschrijving");
if (e.Row.RowType == DataControlRowType.DataRow && DropDownListRol != null)
{
DsFenVlaanderen.tb_rolDataTable dtRole = DsFenVlaanderen.RolTableAdapter.GetData();
//Fill Dropdownlist
DropDownListRol.DataSource = dtRole;
DropDownListRol.DataValueField = dtRole.Rol_IDColumn.ColumnName;
DropDownListRol.DataTextField = dtRole.Rol_omschrijvingColumn.ColumnName;
DropDownListRol.DataBind();
//Set Selected value
DropDownListRol.Items.FindByValue(hidSelectedRole.Value).Selected = true;
}
}
protected void gvwUsers_RowEditing(object sender, GridViewEditEventArgs e)
{
//Set hiddenfield to value of Rol_ID
hidSelectedRole.Value = gvwUsers.DataKeys[e.NewEditIndex].Values["Rol_ID"].ToString();
}
This is my grid:
<asp:hiddenfield runat="server" id="hidSelectedRole" value="-1" />
<fen:FenGridViewSelectable ID="gvwUsers" runat="server" Selectable="False"
DataSourceID="dsUsers" EnableModelValidation="True" SkinID="Blue"
AllowSorting="True" OnDataBound="gvwUsers_DataBound" OnRowDeleting="gvwUsers_RowDeleting"
AutoGenerateColumns="False" DataKeyNames="User_ID,Rol_ID" OnRowDataBound="gvwUsers_RowDataBound" OnRowEditing="gvwUsers_RowEditing" OnRowUpdating="gvwUsers_RowUpdating">
<Columns>
<asp:BoundField DataField="User_ID" HeaderText="Gebruikersnaam" ReadOnly="True" SortExpression="User_ID" />
<asp:BoundField DataField="User_ID_EXT" HeaderText="Naam" ReadOnly="true" SortExpression="User_ID_EXT" />
<%-- <asp:BoundField DataField="Rol_omschrijving" HeaderText="Type bestuurder" SortExpression="Rol_omschrijving" /> --%>
<asp:TemplateField HeaderText="Type bestuurder" SortExpression="Rol_omschrijving">
<ItemTemplate>
<asp:Label ID="lblRolOmschrijving" Text='<%# Eval("Rol_omschrijving") %>' runat="server"/>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="ddlRolOmschrijving" runat="server" DataField="Rol_omschrijving"></asp:DropDownList>
</EditItemTemplate>
</asp:TemplateField>
<fen:FenTemplateField HeaderStyle-Width="100px">
<ItemTemplate>
<fen:FenButton ID="btnEdit" runat="server" Function="Edit" />
<fen:FenButton ID="btnDelete" runat="server" Function="Delete" />
</ItemTemplate>
<EditItemTemplate>
<fen:FenButton ID="btnUpdate" runat="server" Function="Update" />
<fen:FenButton ID="btnCancel" runat="server" Function="CancelInline" />
</EditItemTemplate>
</fen:FenTemplateField>
</Columns>
</fen:FenGridViewSelectable>
<asp:ObjectDataSource ID="dsUsers" runat="server"
OldValuesParameterFormatString="original_{0}" SelectMethod="GetData"
TypeName="FenVlaanderen.DsFenVlaanderenTableAdapters.vUsersTableAdapter"></asp:ObjectDataSource>
<asp:Label ID="lblNoResults" runat="server" Visible="false" CssClass="error">Er werden geen gebruikers gevonden.</asp:Label>
<asp:Label ID="lblDeleteNotAllowed" runat="server" Visible="false" CssClass="error" />
<fen:AddUser ID="addUser" runat="server" OnFenControlSaved="addUser_FenControlSaved" />
</ContentTemplate>
I have a DetailsView control that's filled with a LinqDataSource without problems.
The user needs to upload a file when updating the information, so, I created a TemplateField with an asp:FileUpload control inside the EditItemTemplate (the itemTemplate is just an asp label).
The problem is that when I try to update the data, in the DetailsView.OnItemUpdating, the DetailsViewUpdateEventArgs.OldValues does not contain all the old values (nor the keys). Actually, it just has the ArticleTitle and ArticleNumber.
I thougth it was because the otheres where TemplateFields, so I changed the ArticleDesc from BoundField to TemplateField, added a Multiline Textbox to the EditItemTemplate and an asp Label to the ItemTemplate, and it worked fine (the original value of ArticleDesc was there).
This problem can be solved by other ways, like querying again for the data, but I don't like that solution. Besides, I want to understand why it happens.
ASPX Page
<asp:DetailsView ID="ModArticleDV" runat="server" AllowPaging="True" OnItemUpdated="ModArticleDV_ItemUpdated" OnItemUpdating="ModArticleDV_ItemUpdating" OnModeChanged="ModArticleDV_ModeChanged" OnDataBound="ModArticleDV_DataBound" OnDataBinding="ModArticleDV_DataBinding" AutoGenerateRows="False" DataSourceID="ArticleDS" DataKeyNames="ArticleID">
<Fields>
<asp:BoundField DataField="ArticleID" HeaderText="ID" SortExpression="ArticleID" ReadOnly="true" />
<asp:BoundField DataField="ArticleNumber" HeaderText="Número" SortExpression="ArticleNumber" />
<asp:BoundField DataField="ArticleTitle" HeaderText="Título" SortExpression="ArticleTitle" ConvertEmptyStringToNull="false" />
<asp:TemplateField HeaderText="Archivo PDF" SortExpression="ArticleFile">
<EditItemTemplate>
Archivo Actual: <asp:Label ID="EditCurrentFileLbl" Text='<%# Eval("ArticleFile") %>' runat="server" /><br />
<label class="upload-file">Nuevo Archivo</label>: <asp:FileUpload ID="NewFileUpload" runat="server" CssClass="file-upload" />
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="CurrentFileLbl" runat="server" Text='<%# Eval("ArticleFile") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Descripción" ConvertEmptyStringToNull="false">
<EditItemTemplate>
<asp:TextBox ID="NewDescription" TextMode="MultiLine" Text='<%# Eval("ArticleDesc") %>' runat="server" />
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="CurrentDescription" Text='<%# Eval("ArticleDesc") %>' runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Cantidad de Páginas" SortExpression="ArticlePageCount" ConvertEmptyStringToNull="false">
<EditItemTemplate>
<asp:UpdatePanel ID="CountPagesUP" runat="server" UpdateMode="Conditional">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="CountPagesLink" EventName="Click" />
</Triggers>
<ContentTemplate>
Páginas: <asp:Label runat="server" ID="PageCountLabel" Text='<%# Eval("ArticlePageCount") %>' />
</ContentTemplate>
</asp:UpdatePanel>
<asp:LinkButton ID="CountPagesLink" runat="server" OnClick="CountPagesLink_Click">Contar Páginas</asp:LinkButton>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="CurrentPageCountLbl" Text='<%# Eval("ArticlePageCount") %>' runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Pertenece al" SortExpression="MagazineID">
<EditItemTemplate>
<asp:DropDownList ID="NewMagazine" runat="server" DataSourceID="MagazineDS" DataTextField="MagazineTitle" DataValueField="MagazineID" OnPreRender="NewMagazine_PreRender"></asp:DropDownList>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="CurrentMagazineLbl" runat="server" OnPreRender="CurrentMagazineLbl_PreRender" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Autores" SortExpression="ArticleID">
<EditItemTemplate>
<label>Filtrar Autor</label>: <input type="text" class="search-in-list" title="Reduce la lista de autores. Ingrese el appellido paterno, materno y/o nombre. Debe incluir tildes de ser necesario." /><br />
<asp:ListBox ID="NewAuthors" runat="server" CssClass="list-to-search" SelectionMode="Multiple" DataSourceID="AuthorDS" DataTextField="AuthorFullName" DataValueField="AuthorID" Height="206px" Width="292px" OnDataBound="NewAuthors_DataBound"></asp:ListBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="CurrentAuthorsLbl" runat="server" OnPreRender="CurrentAuthorsLbl_PreRender" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField Visible="false">
<ItemTemplate>
<asp:Label ID="MagazineID" Text='<%# Eval("MagazineID") %>' runat="server" />
<asp:Label ID="CurrentAuthorID" runat="server" OnPreRender="CurrentAuthorID_PreRender" />
</ItemTemplate>
</asp:TemplateField>
<asp:CommandField ShowDeleteButton="True" ShowEditButton="True" UpdateText="Guardar" CancelText="Cancelar" SelectText="Seleccionar" NewText="Nuevo" InsertText="Agregar" EditText="Editar" DeleteText="Borrar" ControlStyle-CssClass="command-field-control" />
</Fields>
</asp:DetailsView>
<asp:LinqDataSource ID="ArticleDS" runat="server" ContextTypeName="LinqToSql.FinderSchemaDataContext" EnableUpdate="True" OrderBy="ArticleID" TableName="Articles" EnableDelete="True" EntityTypeName=""></asp:LinqDataSource>
<asp:LinqDataSource ID="MagazineDS" runat="server" ContextTypeName="LinqToSql.FinderSchemaDataContext" EntityTypeName="" OrderBy="PublishYear, MagazineNumber" TableName="Magazines" Select="new (MagazineID, MagazineNumber, MagazineName, PublishYear, String.Format("Volumen {0} del año {1}", MagazineNumber.ToString(), PublishYear.ToString()) AS MagazineTitle)"></asp:LinqDataSource>
<asp:LinqDataSource ID="AuthorDS" runat="server" ContextTypeName="LinqToSql.FinderSchemaDataContext" EntityTypeName="" OrderBy="AuthorFName, AuthorMName, AuthorName" TableName="Authors" Select="new (AuthorID, AuthorFName, AuthorMName, AuthorName, String.Format("{0} {1} {2}", AuthorFName.ToString(), AuthorMName.ToString(), AuthorName.ToString()) AS AuthorFullName)" />
Code Behind
protected void ModArticleDV_ItemUpdating(object sender, DetailsViewUpdateEventArgs e)
{
Messages.InnerHtml = "";
try
{
Messages.InnerHtml += "<h3>Old Values</h3><br />";
foreach (DictionaryEntry de in e.OldValues)
{
Messages.InnerHtml += String.Format("Key: {1} - Value: {0}<br />", de.Value, de.Key);
}
Messages.InnerHtml += "<h3>New Values</h3><br />";
foreach (DictionaryEntry de in e.NewValues)
{
Messages.InnerHtml += String.Format("Key: {1} - Value: {0}<br />", de.Value, de.Key);
}
e.Cancel = false;
}
catch (Exception ex)
{
Messages.InnerHtml += ex.Message;
}
}
This shows me only the ArticleNumber and ArticleTitle
What Have I tried?
Using Bind instead of Eval
Using a default DetailsView and LinqDataSource fills the e.OldValues with the original values, but I didn't notice the difference :(.
I have read many times the MSDN documentation on DetailsView, DetailsViewUpdateEventArgs and many other resources, but none gave me a hint (I read somewhere that it may be because of the TemplateField(s), but in the tests I run, they work ok).
This question is related, but that's the way I've always added data to TemplateField.
If someone could give me something to read to understand why it happens or if someone could tell me where to fill the OldValues (other than the ItemUpdating event), it would be great :).
Thanks in advance.
I confirm that the dictionaries e.(New|Old)Values are not filled with the data in TemplateField(s).
My solution (I don't know of any better) was to use a hidden TemplateField (Visible="false") and, inside the ItemTemplate, add the original values with labels (asp:Label) then access them using DetailsView.FindControl("control_id"):
<TemplateField Visible="false">
<ItemTemplate>
<asp:Label ID="OriginalValue1" runat="server" Text='<%# Eval("Column1") %>' />
<asp:Label ID="OriginalValueN" runat="server" Text='<%# Eval("ColumnN") %>' />
</ItemTemplate>
</TemplateField>
And in the Code Behind:
// DetailsView.ID = "MyDetailsView";
Label original1 = (Label)MyDetailsView.FindControl("OriginalValue1");
Label originalN = (Label)MyDetailsView.FindControl("OriginalValueN");
For some reason I can't explain, some test I've run with TemplateFields worked (the data was added to the dictionary without my intervention), that's why I was confused and thought it was an error.
Anyway, the problem is now solved and I hope this helps someone :).
First of all the ASPcode, the problemdescription below.
<asp:GridView ID="GridViewContacts" runat="server" ForeColor="#333333" DataKeyNames="L_ID_CONTACT" AllowPaging="True" AllowSorting="True"
OnPageIndexChanging="GridViewContacts_PageIndexChanging" PageSize="25" AutoGenerateColumns="False" OnRowCommand="GV_Contacts_RowCommand" >
<FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
<Columns>
<asp:TemplateField HeaderText="Edit">
<ItemTemplate>
<asp:LinkButton ID="LinkButtonEdit" runat="server" CommandArgument="Edit" CommandName="Edit" Text="Edit">Edit</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="View">
<ItemTemplate>
<asp:LinkButton ID="LinkButtonView" runat="server" CommandArgument="View" CommandName="View" Text="View">View</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<asp:Label ID="L_Name" runat="server" Text='<%# Eval("L_Name") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Companydetails">
<ItemTemplate>
<asp:Label ID="L_Companydetails" runat="server" Text='<%# Eval("L_Companydetails") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="EMail">
<ItemTemplate>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField Visible="False" HeaderText="ID_CONTACT" >
<ItemTemplate>
<asp:Label Visible="false" ID="L_ID_CONTACT" runat="server" Text='<%# Eval("L_ID_CONTACT") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
<%-- //Stylesettings here--%>
</asp:GridView>
Okay, then in the CodeBehind I have a Select from my database, where i select the ID_Contact, the Name, the Companydetails, which can be 1 per Row only.
On the RowCreated event I get the UserID of the actual User, and I select all E-Mails the user has, can be 0-10 per row.
Now my problem is:
How can i insert Linkbuttons with the onClick-event in the description into this part of my code?
Like this:
<asp:TemplateField HeaderText="EMail">
<ItemTemplate>
<asp:LinkButton[i] runat="server" onClick="SendEmail">
</asp:Linkbutton[i]>
<asp:LinkButton[i] runat="server" onClick="SendEmail">
</asp:Linkbutton[i]>
</ItemTemplate>
</asp:TemplateField>
So i want to add those controlls with code into THIS TemplateField.
Is this possible ?
Thoughts i allready had:
This.GridViewContacs.Controlls.AddAt(index,Linkbutton)
But also no clue here how it should work.
Thanks in advance,
me
Easiest is to add a placeholder control to the ItemTemplate, as ItemTemplate has no ID.
<asp:TemplateField>
<ItemTemplate>
<asp:PlaceHolder ID="emails" runat="server"></asp:PlaceHolder>
</ItemTemplate>
</asp:TemplateField>
and then in RowDataBound event
if (e.Row.RowType == DataControlRowType.DataRow)
{
PlaceHolder emails = e.Row.FindControl("emails") as PlaceHolder;
if (emails != null)
{
LinkButton lbEmail = new LinkButton();
lbEmail.Text = "your text";
lbEmail.Click += new EventHandler(SendEmail);
emails.Controls.Add(lbEmail);
}
}
Of course, the example is simplified. You can easily extend it to your needs.
I wish to attach a hovermenu pop up to rows of a gridview which is dynamically populated from a datasource. I tried to set TargetcontrolId property of hovermenuextender control to row unique Id on occurence of rowdatabound event. But rather than appearing on the right side of each row, pop up is appearing on the right side of header row. Can somebody help me resolve this problem? I used below code for the same
CodeBehind:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
try
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
HoverMenuExtender hoverMenu =(HoverMenuExtender)e.Row.FindControl("hme2");
if (hoverMenu != null)
{
hoverMenu.TargetControlID = hoverMenu.Parent.Parent.UniqueID;
}
}
}
}
Aspx page:
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" BackColor="White" ShowFooter="false" ShowHeader="false"
OnRowEditing="GridView1_RowEditing" OnRowCommand="GridView1_RowCommand" OnRowUpdating="GridView1_RowUpdating"
GridLines="None" OnRowDataBound="GridView1_RowDataBound">
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:TemplateField HeaderText ="Talk Title">
<ItemTemplate>
<asp:Label Font-Bold="true" ID="lbltalktitle" runat="server" Text='<%#Eval("Talk_Title") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText ="Brand">
<ItemTemplate>
<asp:Label ID="lblBrand" runat="server" Text='<%# Eval("Brand") %>' /></td>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText ="Franchise">
<ItemTemplate>
<asp:Label ID="lblFranchise" runat="server" Text='<%# Eval("Franchise") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText ="programmetype">
<ItemTemplate>
<asp:Label ID="lblprg" runat="server" Text='<%# Eval("programmetype") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText ="programmetype">
<ItemTemplate>
<asp:Label ID="lblsaledforce" runat="server" Text='<%# Eval("salesforce") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText ="Start_Date">
<ItemTemplate>
<asp:Label ID="lblstartdate" runat="server" Text='<%# Eval("Start_Date") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText ="End_Date">
<ItemTemplate>
<asp:Label ID="lblenddate" runat="server" Text='<%# Eval("End_Date") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<cc1:HoverMenuExtender ID="hme2" runat="server" TargetControlID="lblenddate"
PopupControlID="PopupMenuX" HoverCssClass="popupHover" PopupPosition="Right"/>
<asp:Panel CssClass="popupMenu" ID="PopupMenuX" runat="server">
<asp:LinkButton ID="LinkButton1" runat="server" CommandName="Edit" Text="Edit" /><br />
<asp:LinkButton ID="LinkButton2" runat="server" CommandName="Delete" Text="Delete" />
</asp:Panel>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<FooterStyle BackColor="#C6C3C6" ForeColor="Black" />
<HeaderStyle BackColor="#4A3C8C" Font-Bold="True" ForeColor="#E7E7FF" />
<PagerStyle BackColor="#C6C3C6" ForeColor="Black" HorizontalAlign="Right" />
<RowStyle ForeColor="Black" />
<SortedAscendingCellStyle BackColor="#F1F1F1" />
<SortedAscendingHeaderStyle BackColor="#594B9C" />
<SortedDescendingCellStyle BackColor="#CAC9C9" />
<SortedDescendingHeaderStyle BackColor="#33276A" />
</asp:GridView>
protected void gv_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
AjaxControlToolkit.HoverMenuExtender ajxhovermenu = (AjaxControlToolkit.HoverMenuExtender)e.Row.FindControl("ahm_1");
e.Row.ID = e.Row.RowIndex.ToString();
ajxhovermenu.TargetControlID = e.Row.ID;
}
}
Give TargetControlID of the HoverMenuExtender in RowCreated event of GridView and set it as the RowID
I'm stuck on this problem where I have grid within grid where the nested grid is editable. I can't get the edit working. What's complicates things is that the nested grid is inside a modal popup extender.
It works to the point where I click on the edit button. Then the EmptyDataText property kicks in with the message. If I click on it second time the grid opens in edit mode but the update/cancel buttons don't work. The cancel button when click displays the EmptyDataText property.
Another issue is that this nested grid doesn't use a object data source so I'm going to have to all the updating and deleting in the code file. Not sure now to do that either.
I would like some advice as to how to make this corrected. Here is the code:
<asp:GridView ID="gvForum" runat="server" DataSourceID="odsForumApproval" DataKeyNames="id" Width="200px"
RepeatColumns="1" DataKeyField="id" CssClass="gridview"
AutoGenerateColumns="False" GridLines="None" OnSelectedIndexChanged="_OnCommand">
<AlternatingRowStyle CssClass="altbgcolor" />
<Columns>
<asp:TemplateField >
<ItemTemplate>
<asp:Label runat="server" ID="lblTitle" Text='<%# Bind("Title") %>' />
<asp:Panel id="div" runat="server" align="center" class="confirm" style="display:none" >
<asp:GridView runat="server" ID="gvForumDetail" AutoGenerateColumns="False" DataKeyNames="id"
AllowPaging='true' CssClass="gridview"
AllowSorting="true" PageSize="5" CellPadding="5" OnRowEditing="gvForumDetail_OnRowEditing"
OnRowCancelingEdit="gvForumDetail_CancelRecord" >
<AlternatingRowStyle CssClass="altbgcolor" />
<RowStyle VerticalAlign="Top" HorizontalAlign="Left" />
<HeaderStyle CssClass="greenbar" ForeColor="White" /> <Columns>
<asp:BoundField DataField="id" ReadOnly="true" Visible="false" />
<asp:TemplateField HeaderText="Title">
<ItemTemplate>
<asp:Label runat="server" ID="lblTraining" Text='<%# Bind("title") %>' />
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox runat="server" ID="txtTraining" Text='<%# Bind("title") %>' />
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Post Message">
<ItemTemplate>
<asp:Label runat="server" ID="lblCompletionDate" Width="250" Text='<%# Bind("description") %>' />
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox runat="server" ID="txtDescription" Text='<%# Bind("description") %>' TextMode="MultiLine" Rows="5" Width="250" />
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Posted By">
<ItemTemplate>
<asp:Label runat="server" ID="lblRecurence" Text='<%# Bind("MemberName") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Posted Date">
<ItemTemplate>
<asp:Label runat="server" ID="lblNotes" Text='<%# Eval("itemdate", "{0:d}") %>' />
</ItemTemplate>
<EditItemTemplate>
<asp:CheckBox runat="server" ID="cbxApproved" Text='<%# Bind("approved") %>' />
</EditItemTemplate>
</asp:TemplateField>
<asp:CommandField ShowCancelButton="true" ShowEditButton="true" ShowDeleteButton="true" />
</Columns>
</asp:GridView>
<br />
<Club:RolloverLink ID="btnClose" runat="server" Text="Close" />
</asp:Panel>
<ajaxToolKit:ModalPopupExtender ID="ModalPopupExtender1" runat="server"
TargetControlID="lblTitle"
PopupControlID="div"
CancelControlID="btnClose"
BackgroundCssClass="modalBackground" />
</ItemTemplate>
</asp:TemplateField>
<asp:CommandField ShowSelectButton="True" />
</Columns>
Code behind:
public void _OnCommand(object sender, EventArgs e)
{
ObjectDataSource ods = new ObjectDataSource();
ods.ID = "ods_ForumDetail";
ods.EnableViewState = true;
ods.TypeName = "ForumApproval";
ods.SelectMethod = "GetForumById";
string id = "";
int rowIndex = gvForum.SelectedIndex;
id = gvForum.DataKeys[rowIndex].Value.ToString();
ods.SelectParameters.Add("id", System.TypeCode.Int32, id);
var ModalPopupExtender1 = (ModalPopupExtender)(gvForum.SelectedRow.FindControl("ModalPopupExtender1"));
ModalPopupExtender1.Show();
var gvForumDetail = (GridView)(gvForum.SelectedRow.FindControl("gvForumDetail"));
gvForumDetail.DataSource = ods;
gvForumDetail.DataBind();
}
protected void gvForumDetail_OnRowEditing(Object sender, GridViewEditEventArgs e)
{
var ModalPopupExtender1 = (ModalPopupExtender)(gvForum.SelectedRow.FindControl("ModalPopupExtender1"));
ModalPopupExtender1.Show();
var gvForumDetail = (GridView)(gvForum.SelectedRow.FindControl("gvForumDetail"));
gvForumDetail.EditIndex = e.NewEditIndex;
gvForumDetail.DataBind();
}
protected void gvForumDetail_CancelRecord(object sender, GridViewCancelEditEventArgs e)
{
var ModalPopupExtender1 = (ModalPopupExtender)(gvForum.SelectedRow.FindControl("ModalPopupExtender1"));
ModalPopupExtender1.Show();
var gvForumDetail = (GridView)(gvForum.SelectedRow.FindControl("gvForumDetail"));
gvForumDetail.EditIndex = -1;
gvForumDetail.DataBind();
}
I will try to answer part of your question, updating and deleting the code. you need to take advantage of the "onrowcommand" for the inner gridview (OnRowCommand).