Databinding issue with Eval/Bind - C# Webforms asp.net - c#

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>

Related

How to use Ajax Calendar in Grid View to disable past date

I use a CalendarExtender of AjaxControlToolkit in a GridView and a TextBox. And from that TextBox I want to disable future dates.
I am trying below code
<asp:GridView ID="Gridview2" runat="server" AutoGenerateColumns="false" DataKeyNames="Sno" ShowFooter="true" OnRowCommand="Gridview2_RowCommand" CssClass="table table-bordered table-striped"
OnRowCancelingEdit="Gridview2_RowCancelingEdit" OnRowDeleting="Gridview2_RowDeleting" OnRowEditing="Gridview2_RowEditing" OnRowUpdating="Gridview2_RowUpdating" OnRowDataBound="Gridview2_RowDataBound">
<Columns>
<asp:TemplateField HeaderText="Sno" Visible="false">
<ItemTemplate>
<asp:Label ID="lbl_sno1" runat="server" Text='<%#Eval("Sno") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Date of visit" ShowHeader="false">
<EditItemTemplate>
<asp:TextBox ID="Txt_update_DateofVisit1" runat="server" Text='<%# Eval("DateofVisit","{0:MM/dd/yyyy}") %>' CssClass="form-control"/>
<cc1:CalendarExtender ID="CalendarExtenderedit11" CssClass="Calendar" TargetControlID="Txt_update_DateofVisit1" Format="MM/dd/yyyy" runat="server"></cc1:CalendarExtender>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lbl_DateofVisit1" runat="server" Text='<%# Eval("DateofVisit","{0:MM/dd/yyyy}") %>' />
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txt_DateofVisit_add" runat="server" CssClass="form-control" />
<cc1:CalendarExtender ID="CalendarExtendere21" CssClass="Calendar" TargetControlID="txt_DateofVisit_add" Format="MM/dd/yyyy" runat="server"></cc1:CalendarExtender>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:ImageButton ID="imgbtnDelete_add" runat="server" CommandName="Delete" ImageUrl="~/img/grid_delete.png" Text="Edit" ToolTip="click here to delete" />
</ItemTemplate>
<FooterTemplate>
<asp:ImageButton ID="imgbtnAdd_add" runat="server" CommandName="AddNew" ImageUrl="~/img/grid_add.png" ToolTip="click here to add" CausesValidation="true" ValidationGroup="outadd" />
</FooterTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Below is my RowDataBound
protected void Gridview2_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
AjaxControlToolkit.CalendarExtender CalendarExtendere21 = (AjaxControlToolkit.CalendarExtender)Gridview2.FooterRow.FindControl("CalendarExtendere21");
CalendarExtendere21.EndDate = DateTime.Now;
// CalendarExtendere21.StartDate = DateTime.Now;
}
}
I get below error:
Object reference not set to an instance of an object.
just use parameter e to find out control in grid
if (e.Row.RowType == DataControlRowType.Footer)
{
AjaxControlToolkit.CalendarExtender CalendarExtendere21 =
(e.Row.FindControl("CalendarExtendere21") as AjaxControlToolkit.CalendarExtender);
}
and don't forget to check for null

How to fill data in some of GridViewRow and leave some blank

ASP.net C#
I am creating a gridview having 5 rows containing detail of operations users have to perform. Detail of operations should be filled when it is completed. At a time any number of operation details can be filled.
In gridview, first Item-template contains Label (for operation name) and others are textbox (for other details).
If any user has filled 3 rows then rest of two rows should be blank.
My problem is how to bind those 3 rows filled previously leaving two bottom rows available for entry.
My Gridview design is :
<asp:GridView CssClass="table-bordered gridStyle" runat="server" ShowFooter="True"
ID="grdOperationEntry" GridLines="None" AutoGenerateColumns="False">
<Columns>
<asp:TemplateField HeaderText="Operation">
<ItemTemplate>
<asp:Label Text='<%# Eval("operation_title") %>' ID="lblOperationName" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Date of Completion">
<ItemTemplate>
<asp:TextBox runat="server" Text='<%# Eval("date_completed") %>' CssClass="form-control"
ID="txtDateCompletion" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Time Taken">
<ItemTemplate>
<asp:TextBox runat="server" Text='<%# Eval("time_taken") %>' ID="txtTimeTaken" CssClass="form-control" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Score">
<ItemTemplate>
<asp:TextBox runat="server" Text='<%# Eval("score_gain") %>' ID="txtScore" CssClass="form-control" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Reported To">
<ItemTemplate>
<asp:TextBox runat="server" Text='<%# Eval("reported_to") %>' ID="txtReportedTo"
CssClass="form-control" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
<AlternatingRowStyle BackColor="White" />
<EditRowStyle BackColor="#7C6F57" />
</asp:GridView>
Add a Label with all TextBoxes in GridView and set them visible false and bind also Label from database. I have added an example TemplateField to below, you can do it for all other:
.....
<asp:TemplateField HeaderText="Date of Completion">
<ItemTemplate>
<asp:Label runat="server" Visible="False" Text='<%# Eval("date_completed")
ID="lblDateCompletion" %>'></asp:Label>
<asp:TextBox runat="server" Visible="False" Text='<%# Eval("date_completed") %>'
ID="txtDateCompletion" />
</ItemTemplate>
</asp:TemplateField>
.....
In RowDataBound event set them visible true:
protected void grdOperationEntry_RowDataBound(object sender, GridViewRowEventArgs e)
{
// check if gridview row not a header or footer
if (e.Row.RowType == DataControlRowType.DataRow)
{
// get controls by id from gridview and cast them
Label lblDateCompletion = e.Row.FindControl("lblDateCompletion") as Label;
TextBox txtDateCompletion = e.Row.FindControl("txtDateCompletion") as TextBox;
if (lblDateCompletion.Text == null)
txtDateCompletion.Visible = true;
else
lblDateCompletion.Visible = true;
// perform same for other controls
}
}
Note: Don't forget to add OnRowDataBound property to your GridView <asp:GridView ID="grdOperationEntry" runat="server" OnRowDataBound="grdOperationEntry_RowDataBound" >

make Row in gridview asp.net clickable?

I create gridview and remove the select button to make all row clickable but I want to redirect the user for selected item detail
Note: I remover the CommandField select Visible="False"
int rowCount = 0;
protected void gv_TasksProjectForUser_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
//var taskID = gv_TasksProjectForUser.SelectedDataKey.Value;
e.Row.Attributes.Add("onclick", "location='TaskDetail.aspx?taskID=" + e.Row.RowIndex + "'");
e.Row.Attributes.Add("onmouseover", "JavaScript:this.style.cursor='pointer';");
}
rowCount++;
}
I have made this with Item Templates.
What you have to do is remove the property AutogenerateColums and add them manually with objects and item templates, on those add one that could be a button.
Later on the code Behind add a event to handle the button click, on that event you can do the response.redirect to another page.
<asp:GridView ID="userGrid" runat="server" CssClass="AdminGrid"
AllowPaging="True" AutoGenerateColumns="False" PageSize="11">
<Columns>
<asp:BoundField DataField="ApplicationId" Visible="False" />
<asp:BoundField DataField="UserName" Visible="False" />
<asp:TemplateField >
<HeaderTemplate>
<asp:Label ID="lblEmail" Text="E-Mail" runat="server" CssClass = "HeaderLabel" meta:resourcekey="lblEmail"></asp:Label>
<asp:ImageButton ID="imgSortEMail" runat="server" ImageUrl="~/Images/normal.gif" OnClick="SortGrid" CommandArgument="EMail" CssClass="SortButton" ToolTip="Click here to Order" />
</HeaderTemplate>
<ItemTemplate>
<asp:HyperLink ID="lnkEMail" runat="server" CssClass="EmailLinkButton" Text='<%# FormatGridTextDisplay(DataBinder.Eval(Container.DataItem, "EMail")) %>' ToolTip='<%# DataBinder.Eval(Container.DataItem, "EMail") %>' NavigateUrl='<%# DataBinder.Eval(Container.DataItem, "EMail","mailto:{0}") %>' ></asp:HyperLink>
</ItemTemplate>
<HeaderStyle CssClass="OverFlowStringField" />
<ItemStyle CssClass="OverFlowLeftAligned" />
</asp:TemplateField>
<asp:TemplateField >
<HeaderTemplate>
<asp:Label ID="lblSalonUser" Text="Salon User" runat="server" CssClass = "HeaderLabel" meta:resourcekey="lblSalonUser"></asp:Label>
<asp:ImageButton ID="imgSortIsSalonUser" runat="server" ImageUrl="~/Images/normal.gif" OnClick="SortGrid" CommandArgument="IsSalonUser" CssClass="SortButton" ToolTip="Click here to Order" />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="chkSalonUser" runat="server" Checked='<%# DataBinder.Eval(Container.DataItem, "IsSalonUser") %>' onclick="javascript:if (this.checked==true) this.checked=false; else this.checked=true;"/>
</ItemTemplate>
<HeaderStyle CssClass="OverFlowStringField" />
<ItemStyle CssClass="CenterAligned" />
</asp:TemplateField>
<asp:TemplateField >
<ItemTemplate>
<asp:Button ID="btnEdit" runat="server" Text="Editar" CssClass="GridButton" CommandArgument='<%# DataBinder.Eval(Container.DataItem, "UserName")%> ' OnClick="btnEdit_Click" meta:resourcekey="btnEdit"/>
</ItemTemplate>
<HeaderStyle CssClass="OverFlowStringField" />
<ItemStyle CssClass="CenterAligned" />
</asp:TemplateField>
</Columns>
</asp:GridView>
There You can see that i add a few types of items template, the most important is the btnEdit, on that one there are 2 important properies, one is the CommandArgument where you send the values to redirect to the page and the other is the event OnClick that is the one that will handle the click for the button.
Protected void btnEdit_Click(Object sender , System.EventArgs e ){
Button clickedButton = (sender)Button;
String() argumentsSend = clickedButton.CommandArgument.ToString().Split("|");
String backParameters;
Response.Redirect(String.Concat("RedirectPage.aspx?user=", Server.UrlEncode(argumentsSend(0)), "&company=", Server.UrlEncode(argumentsSend(1)), True);
}
I took this code from VB and change it to c# with a compiler, it may have errors, but that's the idea.
A easyest way is to use a link button or an hipperlink on the template of the grid, that eay you may no need to go to the code file.

Asp.Net GridView Sorting Separate Page

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...

Nested grid edit doesn't work

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).

Categories