I have a repeater which contains a nested gridview. Now I need to be able to retrieve a value databound in a label inside of a repeater and use it as an input parameter for the gridview.
Here is some code which will hopefully give you a better idea of what I'm trying to do.
enter code here
<asp:Repeater ID="Repeater1" runat="server" DataSourceID="RepeaterDS" OnItemDataBound="Repeater1_SendRollNumber">
<HeaderTemplate>
</HeaderTemplate>
<ItemTemplate>
<table style="width: 615px;" id="Table1">
<tr>
<td>
<b>Roll #:</b>
<asp:Label runat="server" ID="RollIDLabel" Text='<%# Eval("RollID") %>' />
<asp:Label runat="server" ID="RollIDLabelCode" Text='<%# Eval("RollID") %>' Visible="false" />
</td>
</tr>
<tr>
<td>
<b>Address:</b>
<asp:Label runat="server" ID="AddressLabel" Text='<%# Eval("Address") %>' />
</table>
<asp:Label ID="Label1" runat="server"><b>Parties:</b></asp:Label>
<asp:GridView ID="GridView3" runat="server" BackColor="White" BorderColor="#DEDFDE"
BorderStyle="None" BorderWidth="1px" CellPadding="4" ForeColor="Black" GridLines="Vertical"
AllowPaging="True" Width="620px" DataSourceID="AssessmentDetailsFromRollIDDS"
EmptyDataText="None Associated" AutoGenerateColumns="False" ShowFooter="true">
<asp:TemplateField HeaderText="Property Assessment" HeaderStyle-Font-Bold="true"
FooterStyle-BackColor="White">
<ItemTemplate>
<asp:Label ID="PropAssessType" runat="server" Width="90%" Text='<%# Eval("PropertyAssessmentType") %>'></asp:Label>
<asp:Label ID="PropAssessDsc" runat="server" Text='<%# Eval("PropertyAssessmentDesc") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
</FooterTemplate>
</asp:TemplateField>
<RowStyle BackColor="#F7F7DE" />
<FooterStyle BackColor="#CCCC99" />
<PagerStyle BackColor="#F7F7DE" ForeColor="Black" HorizontalAlign="Right" />
<SelectedRowStyle BackColor="#CE5D5A" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#3E4E4E" Font-Bold="True" ForeColor="White" />
<AlternatingRowStyle BackColor="White" />
</asp:GridView>
</ItemTemplate>
</asp:Repeater>
<asp:ObjectDataSource ID="RepeaterDS" runat="server" OldValuesParameterFormatString="original_{0}"
SelectMethod="GetRollNumberbyAppealID" TypeName="BusinessLayer.BSO.Roll_AssessmentDetailsBSO">
<SelectParameters>
<asp:QueryStringParameter Name="AppealID" QueryStringField="appealID" Type="Int32" />
</SelectParameters>
</asp:ObjectDataSource>
<asp:ObjectDataSource ID="AssessmentDetailsFromRollIDDS" runat="server" OldValuesParameterFormatString="original_{0}"
SelectMethod="GetAssessDetailsFromRollID" OnSelecting="AssessmentDetailsFromRollIDDS_Selecting" TypeName="BusinessLayer.BSO.Assessment_DetailsBSO">
<SelectParameters>
<asp:ControlParameter Name="RollID" ControlID="RollIDLabelCode" Type="String" />
</SelectParameters>
</asp:ObjectDataSource>
I've tried to cut out as much code as possible while leaving the guts of the problem in. So I basically want the label control RollIDLabelCode which is located in a repeater to also be an input into my gridview. The problem is that I keep getting errors such as can't find the control RollIDLabelCode. I've heard there is a bug in which you need to specify all naming containers. which I've tried with no luck.
Another route I've tried is doing this in the code behind.
enter code here
public void Repeater1_OnItemDataBound(Object Sender, RepeaterItemEventArgs e)
{
// Execute the following logic for Items and Alternating Items.
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
string test = ((Label)e.Item.FindControl("RollIDLabel")).Text;
}
}
public void AssessmentDetailsFromRollIDDS_OnSelecting(object sender, ObjectDataSourceSelectingEventArgs e)
{
e.InputParameters["RollID"] = "Need the Info here";
}
These functions are called on the repeater being databound and the objectdatasource onselecting function. And these work separately very well. I just need to know how to get the information from the string test in the Repeater1_OnItemDataBound function to the e.InputParameters["RollID"] in the OnSelecting function.
Hopefully someone knows how to do this. I am new to .net programming. I appreciate any help.
Thanks!
The RollIDLabelCode label is set visible=false which means it will not exist when rendered so trying to access the value won't be possible. You'll need to use a different control that is hidden but exists when rendered. For instance a GridView has a datakeys that exist within the control but are not rendered. It is used to retrieve a key value for the row to retreive more data, for example.
Related
I have two dropdown lists inside DetailsView, first dropdown DepartmentDropDown loads the data successfully from code behind using the following datasource
<asp:ObjectDataSource ID="dsDepartments" runat="server" SelectMethod="GetDepartments"
TypeName="MyCode.DepartmentEmployeeAssociations">
</asp:ObjectDataSource>
and the second dropdown EmployeeDropDown uses another datasource based on Department selection in the first dropdown (commented code works and loads the details view but not the control parameter code):
<asp:ObjectDataSource ID="dsEmployees" runat="server" SelectMethod="GetAllEmployees"
TypeName="MyCode.DepartmentEmployeeAssociations" DataObjectTypeName="Employee">
<SelectParameters>
<%--<asp:Parameter Name="deptId" Type="Int32" DefaultValue="7" />--%>
<asp:ControlParameter ControlID="DepartmentDropDown" Name="deptId" PropertyName="SelectedValue" Type="Int32" />
</SelectParameters>
</asp:ObjectDataSource>
Here is the code in my GridView and DetailsView
<asp:Panel ID="AssociationView" runat="server" Visible="false">
<asp:GridView ID="gvAssociations" runat="server" AutoGenerateColumns="False" CssClass="GridViewStyle"
EmptyDataText="No rules defined" Width="100%" AllowPaging="True" GridLines="None"
DataKeyNames="Id" EnableModelValidation="True" DataSourceID="dsAssociations"
OnSelectedIndexChanged="gvAssociations_SelectedIndexChanged">
<Columns>
<asp:CommandField ShowSelectButton="true" SelectText="View" ItemStyle-Width="50px">
<ItemStyle Width="50px"></ItemStyle>
</asp:CommandField>
<asp:BoundField DataField="Id" HeaderText="Id" SortExpression="Id" Visible="False" />
<asp:BoundField DataField="Value1" HeaderText="Employee" SortExpression="Value1" Visible="false" />
<asp:BoundField DataField="Value1Description" HeaderText="Employee" NullDisplayText="*" />
<asp:BoundField DataField="Value2" HeaderText="Department" SortExpression="Value2" Visible="false" />
<asp:BoundField DataField="Value2Description" HeaderText="Department" NullDisplayText="*" />
<asp:CommandField ShowDeleteButton="True" />
</Columns>
</asp:GridView>
<div class="DetailsContainer">
<asp:DetailsView ID="dvAssociations" runat="server" Height="50px" GridLines="None"
CellPadding="5" AutoGenerateRows="False" DataKeyNames="sId" EnableModelValidation="True"
OnItemCreated="dvAssociations_ItemCreated" OnItemUpdating="dvAssociations_ItemUpdating"
OnItemInserting="dvAssociations_ItemInserting">
<Fields>
<asp:BoundField DataField="Id" HeaderText="ID" ReadOnly="True" InsertVisible="False" Visible="false" />
<asp:TemplateField HeaderText="Department">
<ItemTemplate>
<asp:DropDownList ID="DepartmentDropDown" runat="server" SelectedValue='<%# Bind("Value2") %>'
DataSourceID="dsDepartments" DataValueField="DepartmentId" DataTextField="Name"
Enabled="false" AutoPostBack="true">
</asp:DropDownList>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="DepartmentDropDown" runat="server" SelectedValue='<%# Bind("Value2") %>'
DataSourceID="dsDepartments" DataValueField="DepartmentId" DataTextField="Name"
Enabled="true" AutoPostBack="true">
</asp:DropDownList>
</EditItemTemplate>
<InsertItemTemplate>
<asp:DropDownList ID="DepartmentDropDown" runat="server" SelectedValue='<%# Bind("Value2") %>'
DataSourceID="dsDepartments" DataValueField="DepartmentId" DataTextField="Name"
Enabled="true" AutoPostBack="true">
</asp:DropDownList>
</InsertItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Employee">
<ItemTemplate>
<asp:DropDownList ID="EmployeeDropDown" runat="server"
DataSourceID="dsEmployees" DataValueField="EmployeeId" DataTextField="FullName"
Enabled="false">
</asp:DropDownList>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="EmployeeDropDown" runat="server"
DataSourceID="dsEmployees" DataValueField="EmployeeId" DataTextField="FullName"
Enabled="true">
</asp:DropDownList>
</EditItemTemplate>
<InsertItemTemplate>
<asp:DropDownList ID="EmployeeDropDown" runat="server"
DataSourceID="dsEmployees" DataValueField="EmployeeId" DataTextField="FullName"
Enabled="true">
</asp:DropDownList>
</InsertItemTemplate>
</asp:TemplateField>
<asp:CommandField ShowEditButton="True" ShowInsertButton="True" ShowDeleteButton="True" />
</Fields>
</asp:DetailsView>
</div>
</asp:Panel>
and the code behind:
protected void gvAssociations_SelectedIndexChanged(object sender, EventArgs e)
{
dvAssociations.PageIndex = gvAssociations.SelectedRow.DataItemIndex;
}
protected void dvAssociations_ItemCreated(object sender, EventArgs e)
{
if (dvAssociations.DataItem == null)
return;
// Some checks
}
protected void dvAssociations_ItemUpdating(object sender, DetailsViewUpdateEventArgs e)
{
//some code
}
protected void dvAssociations_ItemInserting(object sender, DetailsViewUpdateEventArgs e)
{
e.NewValues["Value1"] = ((DropDownList)((DetailsView)sender).FindControl("EmployeeDropDown")).SelectedValue;
}
public List<Department> GetDepartments()
{
// code to return List<Department> departments
// other code
return departments;
}
public List<Employee> GetAllEmployees(int deptId)
{
// code to return List<Employee> employees
// other code
return employees;
}
I tried various suggestions that were given in other SO articles, but still not able to make this work. My page don't load when I have the control parameter added, but it works if I change it to a normal parameter.
<asp:ControlParameter ControlID="DepartmentDropDown" Name="deptId" PropertyName="SelectedValue" Type="Int32" />
I am not sure what it doesn't like about it, it doesn't seem to bind the data in the details view. I added the AutoPostBack to true to the first dropdown and removed the SelectedValue='<%# Bind("Value1") %>' from the second dropdown as suggested in other posts, but nothing seems to be working.
Any help would be appreciated.
I have finally made it work, it was a silly mistake but again I haven't worked on these asp components before. So, there was some learning here and hope this will help someone having similar issue.
Firstly, make sure that your data in the GridView is correct and the dropdown column has valid value and is in the dropdown list source.
Secondly, I had to move my ObjectDataSource for employees with in the itemtemplate
<asp:TemplateField HeaderText="Employee">
<ItemTemplate>
<asp:DropDownList ID="EmployeeDropDown" runat="server" SelectedValue='<%# Bind("Value1") %>'
DataSourceID="dsEmployees" DataValueField="EmployeeId" DataTextField="FullName" Enabled="false">
</asp:DropDownList>
<asp:ObjectDataSource ID="dsEmployees" runat="server" SelectMethod="GetAllEmployees"
TypeName="MyCode.DepartmentEmployeeAssociations" DataObjectTypeName="Employee">
<SelectParameters>
<asp:ControlParameter ControlID="DepartmentDropDown" Name="deptId" PropertyName="SelectedValue" Type="Int32" />
</SelectParameters>
</asp:ObjectDataSource>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="EmployeeDropDown" runat="server" SelectedValue='<%# DataBinder.Eval (Container.DataItem, "Value1") %>'
DataSourceID="dsEmployees" DataValueField="EmployeeId" DataTextField="FullName"
Enabled="true">
</asp:DropDownList>
<asp:ObjectDataSource ID="dsEmployees" runat="server" SelectMethod="GetAllEmployees"
TypeName="MyCode.DepartmentEmployeeAssociations" DataObjectTypeName="Employee">
<SelectParameters>
<asp:ControlParameter ControlID="DepartmentDropDown" Name="deptId" PropertyName="SelectedValue" Type="Int32" />
</SelectParameters>
</asp:ObjectDataSource>
</EditItemTemplate>
<InsertItemTemplate>
<asp:DropDownList ID="EmployeeDropDown" runat="server" SelectedValue='<%# DataBinder.Eval (Container.DataItem, "Value1") %>'
DataSourceID="dsEmployees" DataValueField="EmployeeId" DataTextField="FullName"
Enabled="true">
</asp:DropDownList>
<asp:ObjectDataSource ID="dsEmployees" runat="server" SelectMethod="GetAllEmployees"
TypeName="MyCode.DepartmentEmployeeAssociations" DataObjectTypeName="Employee">
<SelectParameters>
<asp:ControlParameter ControlID="DepartmentDropDown" Name="deptId" PropertyName="SelectedValue" Type="Int32" />
</SelectParameters>
</asp:ObjectDataSource>
</InsertItemTemplate>
</asp:TemplateField>
Also, I have replaced SelectedValue='<%# Bind("Value1") %>' to SelectedValue='<%# DataBinder.Eval (Container.DataItem, "Value1") %>' in my EmployeeDropDown aspx code to make it simpler. Which means, no need to add this event handler dvAssociations_ItemInserting to the DetailsView.
But, I have another issue related to orphan data in the grid, which doesn't exist in the dropdown - which make the ItemTemplate fail to load. That's for another post, this post is done for now. Hope it helps other.
I have an existing SQL database and a ASP.NET application. My application has two existing GridViews and login functions. I also have an existing Crystal Report designed to automatically create a receipt from my SQL database. This is done by the user filling out 3 specific parameters, and the rest of the data (which are in parallel with those parameters) will automatically fill out the crystal report.
I want to create a print button in my GridView to automatically fill out the 3 parameters in the Crystal Report. This is an attempt to make my application more user friendly. In short, the user would push the print button in its new column in the GridView, and the 3 parameters would be automatically picked up and filled into the Crystal Report.
My parameters are: "EmpID", "KeyControl", and "ControlNumber". My crystal report label is "x.rpt"
Here is my GridView markup:
<asp:GridView ID="gridKeyAndBuildingInformation" runat="server" CssClass="style3"
AllowSorting ="True"
AutoGenerateColumns ="False"
AllowPaging="True"
DataKeyNames="KeyRefId"
OnRowCancelingEdit="gridKeyAndBuildingInformation_RowCancelingEdit"
onPageIndexChanging="gridKeyAndBuildingInformation_PageIndexChanging"
OnRowDataBound="gridKeyAndBuildingInformation_RowDataBound"
OnRowEditing="gridKeyAndBuildingInformation_RowEditing"
OnRowUpdating="gridKeyAndBuildingInformation_RowUpdating"
OnRowCommand="gridKeyAndBuildingInformation_RowCommand"
ShowFooter="True"
OnRowDeleting="gridKeyAndBuildingInformation_RowDeleting"
AlternatingRowStyle-BackColor="#EFEFEF"
EditRowStyle-VerticalAlign="Top"
HeaderStyle-BackColor="#77b218"
OnSorting="gridKeyAndBuildingInformation_Sorting"
BackColor="#CCCCCC"
BorderColor="#999999"
BorderStyle="Solid"
BorderWidth="3px"
CellPadding="4"
EnableModelValidation="True"
ForeColor="Black"
CellSpacing="2">
<Columns>
<asp:TemplateField HeaderText ="EmpID" HeaderStyle-CssClass="HeaderText" sortexpression="EmpID">
<ItemTemplate>
<asp:Label ID="lblEmpID" runat="server" Text='<%# Eval("EmpID") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtEmpID" runat="server" Text='<%# Eval("EmpID") %>' Width="50px"></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtNewEmpID" runat="server" Width="50px"></asp:TextBox>
</FooterTemplate>
<HeaderStyle CssClass="HeaderText" />
</asp:TemplateField>
<asp:TemplateField HeaderText ="ControlNumber" HeaderStyle-CssClass="HeaderText" sortexpression="ControlNumber">
<ItemTemplate>
<asp:Label ID="lblControlNumber" runat="server" Text='<%# Eval("ControlNumber") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtControlNumber" runat="server" Text='<%# Eval("ControlNumber") %>' Width="50px"></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtNewControlNumber" runat="server" Width="50px"></asp:TextBox>
</FooterTemplate>
<HeaderStyle CssClass="HeaderText" />
</asp:TemplateField>
<asp:TemplateField HeaderText ="KeyNumber" HeaderStyle-CssClass="HeaderText" sortexpression="KeyNumber">
<ItemTemplate>
<asp:Label ID="lblKeyNumber" runat="server" Text='<%# Eval("KeyNumber") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtKeyNumber" runat="server" Text='<%# Eval("KeyNumber") %>' Width="50px"></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtNewKeyNumber" runat="server" Width="50px"></asp:TextBox>
</FooterTemplate>
<HeaderStyle CssClass="HeaderText" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Edit" ShowHeader="False">
<EditItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="True" CommandName="Update" Text="Update"></asp:LinkButton>
<asp:LinkButton ID="LinkButton2" runat="server" CausesValidation="False" CommandName="Cancel" Text="Cancel"></asp:LinkButton>
</EditItemTemplate>
<FooterTemplate>
<asp:LinkButton ID="LinkButton2" runat="server" CausesValidation="False" CommandName="AddNew" Text="Add New"></asp:LinkButton>
</FooterTemplate>
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="False" CommandName="Edit" Text="Edit"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:CommandField HeaderText="Delete" ShowDeleteButton="True" ShowHeader="True" />
<asp:ButtonField HeaderText="Print" ShowHeader="True" Text="Print" />
</Columns>
<EditRowStyle VerticalAlign="Top"></EditRowStyle>
<FooterStyle BackColor="#CCCCCC" />
<HeaderStyle BackColor="Black" Font-Bold="True" ForeColor="White"></HeaderStyle>
<PagerStyle BackColor="#CCCCCC" ForeColor="Black" HorizontalAlign="Left" />
<RowStyle BackColor="White" />
<SelectedRowStyle BackColor="#000099" Font-Bold="True" ForeColor="White" />
</asp:GridView>
You could handle the RowCommand event, which would fire when you click that delete button in your ButtonField column. Add this to the end of your GridView declaration markup (after "CellSpacing="2"" but before the ">"):
OnRowCommand="gridKeyAndBuildingInformation_RowCommand"
And then, in your code behind you would need something like this (this is C#, if you need VB.NET let me know - this question isn't tagged with a server-side language):
protected void gridKeyAndBuildingInformation_RowCommand(Object sender, GridViewCommandEventArgs e)
{
// Get your ID for the row you're on
int ID = Convert.ToInt32(e.CommandArgument);
// Get the row the button was clicked in
GridViewRow row = gridKeyAndBuildingInformation.Rows[ID];
// Get the values you need from that row
int EmpID = row.Cells[0];
int ControlNumber = row.Cells[1];
int KeyNumber = row.Cells[2];
// Use those numbers to make your call to the Crystal Report
// I don't know what this part would look like.
}
You can read more about the RowCommand event on MSDN: GridView.RowCommand Event
I am facing little issue in my web application in asp.net.
i am receiving the below error :
Error: Sys.InvalidOperationException: Handler was not added through the Sys.UI.DomEvent.addHandler method.
I have used Updatepanel and this error occurs when i try to do some 2-3 actions very quickly.
and when next time i try to do take some action my web application just hungs up.
Please suggest.
Thanks
In my case this was caused by having the 'Close' control within an Update Panel in the Modal Popup. I fixed it by creating a 'dummy' button outside of the Update Panel, and setting it as the 'CancelControlID' in the MPE attributes:
<asp:Button ID="btnDummyCloseWindow" runat="server" Style="visibility: hidden"/>
<ajaxToolkit:ModalPopupExtender ID="mpeWindow" runat="server" PopupControlID="pnlWindow"
TargetControlID="btnDummyOtherButton" BackgroundCssClass="modalBackground"
DropShadow="false" CancelControlID="btnDummyCloseWindow" />
You'll need to make sure the close button that is present within your Update Panel has actions assigned to it to close the window (e.g. mpeWindow.hide()).
It's also worth noting that I was also making use of the TargetControlID 'fix' too, where a dummy button is referenced, so ignore the TargetControlID attribute there.
I've solved the problem setting ScriptMode property of ScriptManager to Release instead of Debug
By default ScriptManager is set to Debug mode.
I had the same problem and solved by placing the ModalPopupExtender or the user control that uses ModalPopupExtender inside an update panel.
Which ever way you want to look at it, the problem is inherit in what I believe is a bug in AJAX.
The only way I was able to resolve this was to control your Sorting or Paging on the server side where you control or more specifically refresh the UpdatePanel along with making sure the ModalPopup has been kept visible!
The reason for the error is really because once you do a sort of page change on a GridView that's inside an UpdatePanel, the controls have been "lost" to the UpdatePanel.
A better explanation is here.
Here is a column from my GridView...
<asp:GridView ID="gvTETstudents" runat="server" AutoGenerateColumns="False" AllowSorting="True" CellPadding="4" ForeColor="#333333" Font-Size="Small" Width="100%"
DataSourceID="sdsTETstudents"
OnRowCreated="gvTETstudents_RowCreated"
OnRowDataBound="gvTETstudents_RowDataBound"
OnDataBound="gvTETstudents_DataBound">
<Columns>
..
..
<ItemTemplate>
<asp:UpdatePanel ID="upWEF1" runat="server" UpdateMode="Conditional" ChildrenAsTriggers="true">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="btnWEFCLOSE" />
</Triggers>
<ContentTemplate>
...
...
<asp:Panel ID="pnlWEF2" runat="server" style="display:none;">
<table><tr><td>
<asp:Button ID="btnWEFshow" runat="server"
Text="ALL"
Font-Size="Small" Font-Names="Arial"
ToolTip="Click here to see all of this student's work experience feedback on file" />
<ajaxToolkit:ModalPopupExtender ID="mpeWEF" runat="server"
BackgroundCssClass="modalBackground"
OkControlID="btnWEFCLOSE"
PopupControlID="upWEF2"
TargetControlID="btnWEFshow">
</ajaxToolkit:ModalPopupExtender>
<asp:UpdatePanel ID="upWEF2" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:Panel ID="pnlWEF3" runat="server" CssClass="pnlEndorsed">
<div id="Hdr" style="text-align: center">
<asp:Label ID="lblWEFHdr" runat="server">** CONTACT LOG **</asp:Label>
</div>
<div id="Bdy">
<table style="width:100%"><tr><td>
<asp:GridView ID="gvWEFContactLog" runat="server"
Font-Size="X-Small" CellPadding="4" ForeColor="#333333" GridLines="None" AllowPaging="true" PageSize="8" AllowSorting="True" AutoGenerateColumns="False" Width="100%"
DataKeyNames="StudentContactLogID,Private,ApprenticeContactLogID"
DataSourceID="sdsWEF"
OnRowDataBound="gvWEFContactLog_RowDataBound"
OnPageIndexChanging="gvWEFContactLog_PageIndexChanging"
OnSorted="gvWEFContactLog_Sorted">
<Columns>
<asp:TemplateField HeaderText="First Entered" SortExpression="FirstEntered">
<ItemTemplate>
<asp:HiddenField ID="hfWEFStudCLid" runat="server" Value='<%# Eval("StudentContactLogID") %>' />
<asp:HiddenField ID="hfWEFAppCLid" runat="server" Value='<%# Eval("ApprenticeContactLogID") %>' />
<asp:HiddenField ID="hfPrivate" runat="server" Value='<%# Eval("Private") %>' />
<asp:HiddenField ID="hfNotes" runat="server" Value='<%# Eval("ContactNotes") %>' />
<asp:LinkButton ID="lnkWEFCLOG" runat="server"
Text='<%# Eval("FirstEntered","{0:d MMM yyyy HH:mm}") %>'></asp:LinkButton>
<a id="lnkDummy" runat="server" visible=false></a>
<ajaxToolkit:ModalPopupExtender ID="mpeWEFCLOG" runat="server"
OkControlID="btnWEFCLOSEview"
PopupControlID="upWEFCLOG"
TargetControlID="lnkWEFCLOG">
</ajaxToolkit:ModalPopupExtender>
<asp:UpdatePanel ID="upWEFCLOG" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<div id="pnlWEFCLOG" runat="server" class="pnlCLOG">
<asp:TextBox ID="txtWEFCLOG" runat="server"
Wrap="true"
TextMode="MultiLine"
Rows="10"
ReadOnly="true"
Width="98%">
</asp:TextBox>
<br />
<asp:Button ID="btnWEFCLOSEview" runat="server" Text="OK" Width="100%" />
</div>
</ContentTemplate>
</asp:UpdatePanel>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Subject" HeaderText="Subject" SortExpression="Subject" />
<asp:BoundField Visible="False" DataField="StudentContactLogID" HeaderText="LogID"
InsertVisible="False" ReadOnly="True" SortExpression="StudentContactLogID">
<ItemStyle HorizontalAlign="Center" />
<HeaderStyle HorizontalAlign="Center" />
</asp:BoundField>
<asp:BoundField DataField="StaffName" HeaderText="Staff" ReadOnly="True" SortExpression="StaffName" />
<asp:TemplateField HeaderText="Contact Date Time" SortExpression="ContactDateTime">
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Eval("ContactDateTime","{0:d MMM yyyy HH:mm}") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Follow-Up Date" SortExpression="FollowUpDate">
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%# Eval("FollowUpDate","{0:d MMM yyyy}") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Private" HeaderText="Private" SortExpression="Private" />
</Columns>
<EmptyDataTemplate>
No Current Entries
</EmptyDataTemplate>
<FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
<EditRowStyle BackColor="#999999" />
<SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
<PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
<HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
</asp:GridView>
<asp:SqlDataSource ID="sdsWEF" runat="server" ConnectionString="<%$ ConnectionStrings:ATCNTV1ConnectionString %>"
SelectCommand="spTETStudentContactLogView" SelectCommandType="StoredProcedure">
<SelectParameters>
<asp:Parameter Name="StudentID" Type="string" />
<asp:Parameter Name="WEF" Type="string" DefaultValue="%" />
</SelectParameters>
</asp:SqlDataSource>
</td></tr>
<tr style="text-align: center">
<td style="text-align: left">
<asp:Button ID="btnWEFCLOSE" runat="server"
Text="CLOSE"
CausesValidation="false" Font-Bold="True" Width="61px" />
</td>
</tr>
</table>
</div>
</asp:Panel>
</ContentTemplate>
</asp:UpdatePanel>
</td></tr></table>
</asp:Panel>
</ContentTemplate>
</asp:UpdatePanel>
</ItemTemplate>
The major point of the code above is that I have a very deep GridView inside an UpdatePanel that's inside a ModalPopUp.
Now look at what I have inside that GridView:
OnPageIndexChanging
and
OnSorted
Inside the GridView, there is another ModalPopup and TextBox. Ignore that. That's only so the user can see the comments from the student's contact log as another popup window.
So if we now go to the code behind for the above two events:
protected void gvWEFContactLog_Sorted(object sender, EventArgs e)
{
GridView gvWEFCL = (GridView)sender;
GridViewRow gvRow = (GridViewRow)gvWEFCL.NamingContainer;
UpdatePanel upWEF1 = (UpdatePanel)gvRow.FindControl("upWEF1");
if (upWEF1 != null) upWEF1.Update();
AjaxControlToolkit.ModalPopupExtender mpeWEF = (AjaxControlToolkit.ModalPopupExtender)gvRow.FindControl("mpeWEF");
if (mpeWEF != null) mpeWEF.Show();
}
protected void gvWEFContactLog_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView gvWEFCL = (GridView)sender;
GridViewRow gvRow = (GridViewRow)gvWEFCL.NamingContainer;
UpdatePanel upWEF1 = (UpdatePanel)gvRow.FindControl("upWEF1");
if (upWEF1 != null) upWEF1.Update();
AjaxControlToolkit.ModalPopupExtender mpeWEF = (AjaxControlToolkit.ModalPopupExtender)gvRow.FindControl("mpeWEF");
if (mpeWEF != null) mpeWEF.Show();
}
Notice that I am not actually controlling the sorting or the paging itself. I am only forcing the GridView to call upon the main UpdatePanel (upWEF1) to refresh itself via an Update() call. The next step is to grab the ModalPopup I want to keep visible and re-Show() it!
And that's all there is to it!
I am sure there is a cleaner solution using JavaScript itself, but for me this avoids that dread meaningless error and I have a clean set of popups and update panels that can handle both hotlinks, sorting and paging as I want the GridView to perform!
I'm trying to get an ASP.NET 3.5 GridView to show a selected value as string when being displayed, and to show a DropDownList to allow me to pick a value from a given list of options when being edited. Seems simple enough?
My gridview looks like this (simplified):
<asp:GridView ID="grvSecondaryLocations" runat="server"
DataKeyNames="ID" OnInit="grvSecondaryLocations_Init"
OnRowCommand="grvSecondaryLocations_RowCommand"
OnRowCancelingEdit="grvSecondaryLocations_RowCancelingEdit"
OnRowDeleting="grvSecondaryLocations_RowDeleting"
OnRowEditing="grvSecondaryLocations_RowEditing"
OnRowUpdating="grvSecondaryLocations_RowUpdating" >
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="lblPbxTypeCaption" runat="server"
Text='<%# Eval("PBXTypeCaptionValue") %>' />
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="ddlPBXTypeNS" runat="server"
Width="200px"
DataTextField="CaptionValue"
DataValueField="OID" />
</EditItemTemplate>
</asp:TemplateField>
</asp:GridView>
The grid gets displayed OK when not in editing mode - the selected PBX type shows its value in the asp:Label control. No surprise there.
I load the list of values for the DropDownList into a local member called _pbxTypes in the OnLoad event of the form. I verified this - it works, the values are there.
Now my challenge is: when the grid goes into editing mode for a particular row, I need to bind the list of PBX's stored in _pbxTypes.
Simple enough, I thought - just grab the drop down list object in the RowEditing event and attach the list:
protected void grvSecondaryLocations_RowEditing(object sender, GridViewEditEventArgs e)
{
grvSecondaryLocations.EditIndex = e.NewEditIndex;
GridViewRow editingRow = grvSecondaryLocations.Rows[e.NewEditIndex];
DropDownList ddlPbx = (editingRow.FindControl("ddlPBXTypeNS") as DropDownList);
if (ddlPbx != null)
{
ddlPbx.DataSource = _pbxTypes;
ddlPbx.DataBind();
}
.... (more stuff)
}
Trouble is - I never get anything back from the FindControl call - seems like the ddlPBXTypeNS doesn't exist (or can't be found).
What am I missing?? Must be something really stupid.... but so far, all my Googling, reading up on GridView controls, and asking buddies hasn't helped.
Who can spot the missing link? ;-)
Quite easy... You're doing it wrong, because by that event the control is not there:
protected void gv_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow &&
(e.Row.RowState & DataControlRowState.Edit) == DataControlRowState.Edit)
{
// Here you will get the Control you need like:
DropDownList dl = (DropDownList)e.Row.FindControl("ddlPBXTypeNS");
}
}
That is, it will only be valid for a DataRow (the actually row with data), and if it's in Edit mode... because you only edit one row at a time. The e.Row.FindControl("ddlPBXTypeNS") will only find the control that you want.
I am using a ListView instead of a GridView in 3.5. When the user wants to edit I have set the selected item of the dropdown to the exising value of that column for the record. I am able to access the dropdown in the ItemDataBound event. Here's the code:
protected void listViewABC_ItemDataBound(object sender, ListViewItemEventArgs e)
{
// This stmt is used to execute the code only in case of edit
if (((ListView)(sender)).EditIndex != -1 && ((ListViewDataItem)(e.Item)).DisplayIndex == ((ListView)(sender)).EditIndex)
{
((DropDownList)(e.Item.FindControl("ddlXType"))).SelectedValue = ((MyClass)((ListViewDataItem)e.Item).DataItem).XTypeId.ToString();
((DropDownList)(e.Item.FindControl("ddlIType"))).SelectedValue = ((MyClass)((ListViewDataItem)e.Item).DataItem).ITypeId.ToString();
}
}
protected void grvSecondaryLocations_RowEditing(object sender, GridViewEditEventArgs e)
{
grvSecondaryLocations.EditIndex = e.NewEditIndex;
DropDownList ddlPbx = (DropDownList)(grvSecondaryLocations.Rows[grvSecondaryLocations.EditIndex].FindControl("ddlPBXTypeNS"));
if (ddlPbx != null)
{
ddlPbx.DataSource = _pbxTypes;
ddlPbx.DataBind();
}
.... (more stuff)
}
You can use SelectedValue:
<EditItemTemplate>
<asp:DropDownList ID="ddlPBXTypeNS"
runat="server"
Width="200px"
DataSourceID="YDS"
DataTextField="CaptionValue"
DataValueField="OID"
SelectedValue='<%# Bind("YourForeignKey") %>' />
<asp:YourDataSource ID="YDS" ...../>
</EditItemTemplate>
The checked answer from balexandre works great. But, it will create a problem if adapted to some other situations.
I used it to change the value of two label controls - lblEditModifiedBy and lblEditModifiedOn - when I was editing a row, so that the correct ModifiedBy and ModifiedOn would be saved to the db on 'Update'.
When I clicked the 'Update' button, in the RowUpdating event it showed the new values I entered in the OldValues list. I needed the true "old values" as Original_ values when updating the database. (There's an ObjectDataSource attached to the GridView.)
The fix to this is using balexandre's code, but in a modified form in the gv_DataBound event:
protected void gv_DataBound(object sender, EventArgs e)
{
foreach (GridViewRow gvr in gv.Rows)
{
if (gvr.RowType == DataControlRowType.DataRow && (gvr.RowState & DataControlRowState.Edit) == DataControlRowState.Edit)
{
// Here you will get the Control you need like:
((Label)gvr.FindControl("lblEditModifiedBy")).Text = Page.User.Identity.Name;
((Label)gvr.FindControl("lblEditModifiedOn")).Text = DateTime.Now.ToString();
}
}
}
<asp:GridView ID="GridView1" runat="server" PageSize="2" AutoGenerateColumns="false"
AllowPaging="true" BackColor="White" BorderColor="#CC9966" BorderStyle="None"
BorderWidth="1px" CellPadding="4" OnRowEditing="GridView1_RowEditing" OnRowUpdating="GridView1_RowUpdating"
OnPageIndexChanging="GridView1_PageIndexChanging" OnRowCancelingEdit="GridView1_RowCancelingEdit"
OnRowDeleting="GridView1_RowDeleting">
<FooterStyle BackColor="#FFFFCC" ForeColor="#330099" />
<RowStyle BackColor="White" ForeColor="#330099" />
<SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="#663399" />
<PagerStyle BackColor="#FFFFCC" ForeColor="#330099" HorizontalAlign="Center" />
<HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="#FFFFCC" />
<Columns>
<asp:TemplateField HeaderText="SerialNo">
<ItemTemplate>
<%# Container .DataItemIndex+1 %>. 
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="RollNo">
<ItemTemplate>
<%--<asp:Label ID="lblrollno" runat="server" Text='<%#Eval ("RollNo")%>'></asp:Label>--%>
<asp:TextBox ID="txtrollno" runat="server" Text='<%#Eval ("RollNo")%>'></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="SName">
<ItemTemplate>
<%--<asp:Label ID="lblsname" runat="server" Text='<%#Eval("SName")%>'></asp:Label>--%>
<asp:TextBox ID="txtsname" runat="server" Text='<%#Eval("SName")%>'> </asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="C">
<ItemTemplate>
<%-- <asp:Label ID="lblc" runat="server" Text='<%#Eval ("C") %>'></asp:Label>--%>
<asp:TextBox ID="txtc" runat="server" Text='<%#Eval ("C") %>'></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Cpp">
<ItemTemplate>
<%-- <asp:Label ID="lblcpp" runat="server" Text='<%#Eval ("Cpp")%>'></asp:Label>--%>
<asp:TextBox ID="txtcpp" runat="server" Text='<%#Eval ("Cpp")%>'> </asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Java">
<ItemTemplate>
<%-- <asp:Label ID="lbljava" runat="server" Text='<%#Eval ("Java")%>'> </asp:Label>--%>
<asp:TextBox ID="txtjava" runat="server" Text='<%#Eval ("Java")%>'> </asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Edit" ShowHeader="False">
<EditItemTemplate>
<asp:LinkButton ID="lnkbtnUpdate" runat="server" CausesValidation="true" Text="Update"
CommandName="Update"></asp:LinkButton>
<asp:LinkButton ID="lnkbtnCancel" runat="server" CausesValidation="false" Text="Cancel"
CommandName="Cancel"></asp:LinkButton>
</EditItemTemplate>
<ItemTemplate>
<asp:LinkButton ID="btnEdit" runat="server" CausesValidation="false" CommandName="Edit"
Text="Edit"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:CommandField HeaderText="Delete" ShowDeleteButton="True" ShowHeader="True" />
<asp:CommandField HeaderText="Select" ShowSelectButton="True" ShowHeader="True" />
</Columns>
</asp:GridView>
<table>
<tr>
<td>
<asp:Label ID="lblrollno" runat="server" Text="RollNo"></asp:Label>
<asp:TextBox ID="txtrollno" runat="server"></asp:TextBox>
</td>
<td>
<asp:Label ID="lblsname" runat="server" Text="SName"></asp:Label>
<asp:TextBox ID="txtsname" runat="server"></asp:TextBox>
</td>
<td>
<asp:Label ID="lblc" runat="server" Text="C"></asp:Label>
<asp:TextBox ID="txtc" runat="server"></asp:TextBox>
</td>
<td>
<asp:Label ID="lblcpp" runat="server" Text="Cpp"></asp:Label>
<asp:TextBox ID="txtcpp" runat="server"></asp:TextBox>
</td>
<td>
<asp:Label ID="lbljava" runat="server" Text="Java"></asp:Label>
<asp:TextBox ID="txtjava" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>
<asp:Button ID="Submit" runat="server" Text="Submit" OnClick="Submit_Click" />
<asp:Button ID="Reset" runat="server" Text="Reset" OnClick="Reset_Click" />
</td>
</tr>
</table>
I thought this would be simple, but I sure am having a lot of trouble doing this:
The title of this question may be a bit misleading. I don't have to use a gridview. In fact, I know the GridView is probably not the way to go on this. I just didn't know how else to title it. But, for now just consider:
I have a very simple class called Student. It has 4 properties:
int ID
string FirstName
string LastName
string Email
I want to keep a generic collection of these in memory (session state):
List students;
Ok, now the problem:
I want the user to create as many of these Student objects as they want. For displaying these I just want a simple table of some kind with the 3 textboxes on each row. I would like every row to have textboxes insead of labels so that any record can be edited at anytime.
When the user is finished created their student objects, then they proceed on to do other things. But, I am just having trouble finding a way to display the records this way. Do I use the ListView(3.5), html table, gridview, repeater, etc.?
How would you do it?
I would be inclined to use the ListView personally for this, since you can insert Rows with it. Your LayoutTemplate would be a table with a <tr runat="server" ID="itemPlaceHolder" /> in it. Your ItemTemplate would have your TextBox's (and optional a save button per row. Then you could have an InsertItemTemplate if you need inserts as well.
Anywhere on the page you can add a button to Save all items by looping through the ListView.Item collection and calling ListView.Update(itemIndex, validate).
<asp:ListView runat="server" ID="lv" InsertItemPosition="LastItem" DataKeyNames="id">
<LayoutTemplate>
<asp:LinkButton runat="server" OnClick="SaveAll" Text="Save All" />
<table>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Email</th>
</tr>
<tr runat="server" id="itemPlaceHolder" />
</table>
<asp:LinkButton runat="server" OnClick="SaveAll" Text="Save All" />
</LayoutTemplate>
<ItemTemplate>
<tr>
<td><asp:TextBox runat="server" ID="firstName" Text='<%#Bind("firstName") %>' /></td>
<td><asp:TextBox runat="server" ID="firstName" Text='<%#Bind("lastName") %>' /></td>
<td><asp:TextBox runat="server" ID="firstName" Text='<%#Bind("email") %>' /></td>
<td><asp:LinkButton runat="server" CommandName="update" Text="Save" /></td>
</tr>
</ItemTemplate>
<InsertItemTemplate>
<tr>
<td><asp:TextBox runat="server" ID="firstName" Text='<%#Bind("firstName") %>' /></td>
<td><asp:TextBox runat="server" ID="firstName" Text='<%#Bind("lastName") %>' /></td>
<td><asp:TextBox runat="server" ID="firstName" Text='<%#Bind("email") %>' /></td>
<td><asp:LinkButton runat="server" CommandName="insert" Text="Save" /></td>
</tr>
</InsertItemTemplate>
</asp:ListView>
protected void SaveAll(object sender, EventArgs e)
{
lv.Items.ToList().ForEach(li => lv.UpdateItem(li.DataItemIndex, true)_;
}
Yes you could use a grid view to do this.
you could create a custom template for the columns so that they display in a textbox as opposed to a label. you can then capture the 'save' event an loop through the rows and update your data.
Gridview is going to be the easiest way to implement this. You could use an html table, but when the user wants to add more users you're going to have to do a lot more. Create a template for the gridview with your four properties (Id, FirstName, LastName, Email), and then just bind it from the session object like:
public void BindGrid()
{
// assume students is the name of your GridView control
students.DataSource = (List<Student>)Session["StudentList"];
students.DataBind();
}
Yes, this is possible. This is just a code sample for what Victor had posted.
<asp:GridView ID="gvDetails" runat="server" AutoGenerateColumns="False" DataKeyNames="PartNumber" GridLines="Horizontal"
ForeColor="#333333" CellPadding="4" Width="800" PageSize="20" OnDataBound="gvPartDetails_DataBound" OnSelectedIndexChanged="gvPartDetails_SelectedIndexChanged" OnSorting="gvPartDetails_Sorting">
<Columns>
<asp:TemplateField HeaderText="#">
<ItemTemplate>
<asp:Label ID="lblNumber" runat="server" Text='<%# Bind("Number") %>' ToolTip='<%# Bind("Description") %>'></asp:Label>
</ItemTemplate>
<HeaderStyle Wrap="False" />
</asp:TemplateField>
<asp:TemplateField HeaderText="LOC 1">
<ItemTemplate>
<asp:TextBox ID="txt_Qty1" AutoPostBack="false" runat="server" MaxLength="5" Width="50" Text='<%# Bind("Qty1") %>'></asp:TextBox>
</ItemTemplate>
<HeaderStyle Wrap="False" />
</asp:TemplateField>
<asp:TemplateField HeaderText="LOC 2">
<ItemTemplate>
<asp:TextBox ID="txt_Qty2" AutoPostBack="false" runat="server" MaxLength="5" Width="50" Text='<%# Bind("Qty2") %>'></asp:TextBox>
</ItemTemplate>
<HeaderStyle Wrap="False" />
</asp:TemplateField>
</Columns>
<EmptyDataTemplate>
<span id="Empty">No Details For This Such and Such.</span>
<img src="Images/icons/table_add.png" style="border:0px" alt="Add New Part" />
</EmptyDataTemplate>
<FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
<EditRowStyle BackColor="#999999" />
<SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
<PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
<HeaderStyle BackColor="#284775" Font-Bold="True" ForeColor="White" HorizontalAlign="Left" />
<AlternatingRowStyle BackColor="Gainsboro" ForeColor="#284775" />
</asp:GridView>
And then the code behind... this is very rough...
private void ApplyChanges()
{
foreach (GridViewRow row in this.gvDetails.Rows)
{
//do something with cells and data objects
//and then save add to list, save, etc.
}
}
EDIT
Above is where you will get your editing of the data. You can work with DataTables, DataViews, DataSets, and as the other solution shows, you can bind your grid to a list of your object. This should be determined based upon the data object model in your system and how the rows would be generated.