This is my xml file
<ISPChecklist>
<Domain name="Coping Skills">
<Indicator>
Client shows impovement in either 1 of the areas listed below and shows reduction in frequency of inapporiate coping behaviors :
- anger management
- ability to make concrete plans about his/her future
- self percetion/self worth
- expand internal locus of control.
</Indicator>
<AttainmentDate></AttainmentDate>
<Remarks></Remarks>
</Domain>
</ISPChecklist>
This is my grid view
<asp:GridView ID="ISPChecklist" runat="server"
OnRowDataBound="OnDataBound"
onselectedindexchanged="ISPChecklist_SelectedIndexChanged">
<Columns>
<asp:BoundField HeaderText="Domain" DataField= "Domain" />
<asp:BoundField HeaderText="Indicator" DataField="Indicator" />
<asp:TemplateField HeaderText="Date Of Attainment">
<ItemTemplate>
<asp:TextBox runat="server" ID="TB_Date" Columns="5"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Remarks">
<ItemTemplate>
<asp:TextBox runat="server" ID="TB_Remarks" Columns="5"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
This is my .cs file
DataSet checklistDataSet;
string filePath = Server.MapPath("clientISPChecklist.xml");
checklistDataSet = new DataSet();
//Read the contents of the XML file into the DataSet
checklistDataSet.ReadXml(filePath);
ISPChecklist.DataSource = checklistDataSet.Tables[0].DefaultView;
ISPChecklist.DataBind();//errors occurs here
Whenever i run this set of codes, i would receive an error message that states that "A field or property with the name 'Coping Skills' was not found on the selected data source". Does anyoen knows how to solve it? if not are there any tutorials or guides available
Use XMLDataSource and XPath() method.
I guess the Linq-XML is better option.
XDocument doc = XDocument.Load(MapPath("~/filename.xml"));
var result = from n in doc.Descendants("Domain")
select new
{
Domain = n.HasAttributes ? n.Attribute("name").Value : "",
Indicator=n.Element("Indicator").Value,
AttainmentDate = n.Element("AttainmentDate").Value,
Remark=n.Element("AttainmentDate").Value
};
ISPChecklist.DataSource = result.ToList();
ISPChecklist.DataBind();
Related
I have a table with headers(example): Group, DisplayName, EditableData, description.
I have been trying for the last few days to learn repeaters to sort the information based on the Group so I can get something that looks like the following layout. This is a user control I am trying to put together.
Group1
------------------
Name1 EditableData Some Description
Name2 EditableData Some Description
Group2
------------------
Name3 EditableData Some Description
Name4 EditableData Some Description
I have looked a the following other examples online:
Nested repeaters - grouping data and
Nested Repeaters in ASP.NET
I believe I do not properly understand how repeaters work enough to deal with nesting or datasource.
<asp:Repeater ID="Repeater1" runat="server">
<ItemTemplate>
Group: <%#Eval("Group")%><br />
<%--Nested Repeater would go here for all the children info for each "Group"--%>
</ItemTemplate>
</asp:Repeater>
Using DISTINCT in my SQL to just retrieve "Group" leaves me with the proper groups without repeats and I guess I could just instead set the groups in labels and then later make repeaters for each specific label... This seems terrible when I may later update editableData back to the database.
What I really want I guess is at least a link to a walkthrough that explains how repeaters work along with Eval() and datasources. I mean, code to do everything I need to complete this first step in my project would be perfect ;P But I also want to be able to understand these better as I am probably going to be using them often in the near future.
I once encountered the same issue where I was to sort the data by group and I had to display the common items in a grouped segment.
There are of-course multiple ways of how you retrieve data, for example, you can get Distinct Group Names and bind it to the repeater and then on ItemDataBound event you can execute and get other elements like this:
<asp:Repeater runat="server" ID="rptrGroups" OnItemDataBound="rptrGroups_ItemDataBound">
<ItemTemplate>
<asp:Label runat="server" ID="lblGroupName" Text='<%# Eval("GroupName") %>' />
<asp:GridView runat="server" ID="gv">
</asp:GridView>
</ItemTemplate>
</asp:Repeater>
protected void rptrGroups_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item)
{
var lblGroupName = (Label)e.Item.FindControl("lblGroupName");
GridView gv = (GridView)e.Item.FindControl("table");
var dataTable = FetchDataWithGroupName(lblGroupName.Text); // Method that fetches data with groupname.
gv.DataSource = dataTable;
gv.DataBind();
}
}
This is not a recommended way because it goes to database, runs query, and then fetches data for each item (if you are fetching this data from db). If you have thousands of Groups then it will make db calls for thousands of times which is a bad thing.
The second solution is, you design a model and feed a custom model that will do the job. Let me explain it by a sample model:
public class GroupedModel
{
public string GroupName {get; set;}
public List<NestedData> TableData {get; set;}
}
public class NestedData
{
public string Id {get; set;}
// Your columns here...
}
Then query and initialize list of GroupedModel class then feed it to the repeater. Let me do it with some dummy data.
var tableData = new List<NestedData>();
var nestedData1 = new NestedData { Id = "1" };
var nestedData2 = new NestedData { Id = "2" };
tableData.Add(nestedData1);
tableData.Add(nestedData2);
var groupedModel = new GroupedModel
{
GroupName = "Group1",
TableData = tableData
};
var listGroupedModel = new List<GroupedModel>();
listGroupedModel.Add(groupedModel);
rptrGroups.DataSource = listGroupedModel;
Then modify the markup like this:
<asp:Repeater runat="server" ID="rptrGroups">
<ItemTemplate>
<asp:Label runat="server" ID="lblGroupName" Text='<%# Eval("GroupName") %>' />
<asp:GridView runat="server" ID="gv" DataSource='<%# ((GroupedModel)Container.DataItem).TableData %>'>
</asp:GridView>
</ItemTemplate>
</asp:Repeater>
I find that just using a gridview or list view works rather nice. However, DO NOT attempt to use the grouping feature - as it is for placing items across the page, not down.
Lets make this really simple!
Ok, so I have a list of Hotels, but I want to group by city.
So, you build a query like this:
Dim strSQL As String =
"SELECT ID, FirstName, LastName, HotelName, City FROM tblHotels ORDER BY City, HotelName"
GridView1.DataSource = Myrst(strSQL)
GridView1.DataBind()
Ok, so that fills out our grid view. We get this:
So far, two lines of code!
But, we want to group by City.
So at the forms class level, add simple var:
Public Class HotelGroupGrid
Inherits System.Web.UI.Page
Dim LastCity As String <----- this one
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If IsPostBack = False Then
LastCity = ""
Call LoadGrid()
End If
End Sub
Ok, so now on the data item bind event, simply add a NEW row.
The code looks like this:
If e.Row.RowType = DataControlRowType.DataRow Then
' if grouping = 1 then create a new row!
Dim gvRow As DataRowView = DirectCast(e.Row.DataItem, DataRowView)
If gvRow("City") <> LastCity Then
LastCity = gvRow("City")
' insert a new row for grouping header
Dim MyRow As New GridViewRow(-1, -1, DataControlRowType.DataRow, DataControlRowState.Normal)
Dim MyCel As New TableCell()
'MyCel.Width = Unit.Percentage(100)
Dim MyTable As Table = e.Row.Parent
MyCel.ColumnSpan = MyTable.Rows(0).Controls.Count
Dim MyLable As New Label
MyLable.Text = "<h2>" & gvRow("City") & "</h2>"
MyCel.Controls.Add(MyLable)
MyRow.Cells.Add(MyCel)
MyTable.Rows.AddAt(MyTable.Rows.Count - 1, MyRow)
End If
End If
Now, above is a "bit" of a chunk to chew on - but still not a lot of code.
So, now when we run above, we get this:
Our grid view markup looks like this:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="ID">
<Columns>
<asp:BoundField DataField="City" HeaderText="City" InsertVisible="False" ReadOnly="True" SortExpression="ID" />
<asp:BoundField DataField="ID" HeaderText="ID" InsertVisible="False" ReadOnly="True" SortExpression="ID" />
<asp:BoundField DataField="FirstName" HeaderText="FirstName" SortExpression="FirstName" />
<asp:BoundField DataField="LastName" HeaderText="LastName" SortExpression="LastName" />
<asp:BoundField DataField="HotelName" HeaderText="HotelName" SortExpression="HotelName" />
</Columns>
</asp:GridView>
So, not too bad.
If you decide to use a listview? Then the code becomes quite a bit less, but the markup for listview is quite a handfull.
All we do is create a row that is our heading, and now show, or hide that row based on the start of new grouping.
So, if one decides to use a list view? Then we get this:
(I assume you use the databind wizards - your not possibly typing in the markup by hand - right? - saving world poverty here)
So, for a list view (and I think the list view is BETTER, since the layout options for that heading row is wide open to any kind markup and extra controls you dream up.
So, the markup (generated - and then chopped out the fat) is this:
<asp:ListView ID="ListView1" runat="server" DataKeyNames="ID">
<EmptyDataTemplate>
<table runat="server" style="">
<tr><td>No data was returned.</td></tr>
</table>
</EmptyDataTemplate>
<ItemTemplate>
<tr id="GroupHeading" runat="server" style="display:none">
<td colspan="4">
<h2><asp:Label ID="City" runat="server" Text='<%# Eval("City") %>' /></h2>
</td>
</tr>
<tr>
<td><asp:Label ID="IDLabel" runat="server" Text='<%# Eval("ID") %>' /></td>
<td><asp:Label ID="FirstNameLabel" runat="server" Text='<%# Eval("FirstName") %>' /></td>
<td><asp:Label ID="LastNameLabel" runat="server" Text='<%# Eval("LastName") %>' /></td>
<td><asp:Label ID="HotelNameLabel" runat="server" Text='<%# Eval("HotelName") %>' /></td>
</tr>
</ItemTemplate>
<LayoutTemplate>
<table id="itemPlaceholderContainer" runat="server" border="0" style="">
<tr runat="server">
<th runat="server">ID</th>
<th runat="server">FirstName</th>
<th runat="server">LastName</th>
<th runat="server">HotelName</th>
</tr>
<tr id="itemPlaceholder" runat="server">
</tr>
</table>
</LayoutTemplate>
</asp:ListView>
Now no question that the listview spits out a lot more markup - but we now have a full row for the heading. So we get this:
But, now our code simply will hide or show that "extra" row we have in the marketup.
And it quite simple now:
If e.Item.GetType = GetType(ListViewDataItem) Then
Dim MyRow As HtmlTableRow = e.Item.FindControl("GroupHeading")
Dim lblCity As Label = MyRow.FindControl("City")
If lblCity.Text <> LastCity Then
LastCity = lblCity.Text
' Hide/show group heading
MyRow.Style("display") = "normal"
Else
MyRow.Style("display") = "none"
End If
End If
So the trick in most cases is to simply layout that extra row item, and then on the item data bound event you simply hide or show that heading part.
I am trying to bind an ASP DataList control with the values returned from an XML file. What's somewhat unique is that I'm not loading the XML from a file, but rather using XMLTextReader() to load it as a string. The reason for this is that the XML will be built from values read from the database. Here's the code which takes (in this case a hard-coded) XML string, adds it to a DataSet and then binds the DataList control...
StringBuilder xml = new StringBuilder();
xml.Append("<product>");
xml.Append("<sku>241</sku>");
xml.Append("<prodID>2SIDED</prodID>");
xml.Append("<name>Product Name</name>");
xml.Append("<price>6.99</price>");
xml.Append("<description>Product Description</description>");
xml.Append("<standalone>1</standalone>");
xml.Append("<sellable>1</sellable>");
xml.Append("<product-type>10</product-type>");
xml.Append("<customization>");
xml.Append("<option1></option1>");
xml.Append("<option2></option2>");
xml.Append("<option3></option3>");
xml.Append("</customization>");
xml.Append("</product>");
using (XmlTextReader tr = new XmlTextReader(new StringReader(xml.ToString())))
{
var document = XElement.Load(tr);
string source = document.ToString();
DataSet dsProdList = new DataSet();
dsProdList.ReadXml(new StringReader(source));
prodDetail.DataSource = dsProdList;
prodDetail.DataBind();
}
Here's the DataList control...
<asp:DataList ID="prodDetail" runat="server" OnItemDataBound="prodDetail_ItemDataBound">
<ItemTemplate>
<div class="proddetail">
<asp:Image ID="Image" runat="server" width="480" height="325" AlternateText='<%#DataBinder.Eval(Container.DataItem, "name") %>'/>
<asp:HiddenField ID="hdnStandalone" runat="server" Value='<%#DataBinder.Eval(Container.DataItem, "standalone") %>' Visible="false" />
<asp:HiddenField ID="hdnSellable" runat="server" Value='<%#DataBinder.Eval(Container.DataItem, "sellable") %>' Visible="false" />
<asp:HiddenField ID="hdnTypeId" runat="server" Value='<%#DataBinder.Eval(Container.DataItem, "product-type") %>' Visible="false" />
<asp:HiddenField ID="hdnOption1" runat="server" Value='<%# DataBinder.Eval(Container.DataItem, "option1") %>' Visible="false" />
<asp:HiddenField ID="hdnOption2" runat="server" Value='<%#DataBinder.Eval(Container.DataItem, "option2") %>' Visible="false" />
<asp:HiddenField ID="hdnOption3" runat="server" Value='<%#DataBinder.Eval(Container.DataItem, "option3") %>' Visible="false" />
<asp:Label ID="lblDescription" runat="server" Text='<%#DataBinder.Eval(Container.DataItem, "description") %>'>
</div>
</ItemTemplate>
</asp:DataList>
This seems to be working fine until the code attempts to bind "option1" at that point I get the following exception:
DataBinding: 'System.Data.DataRowView' does not contain a property with the name 'option1'.
From what I can work out this definitely seems to be an issue with "option1" being a child of "customization". If I simply comment out the opening and closing "customization" tags, which effectively leaves the "option(s)" as children of "product" the code runs fine and I get the output I'm expecting.
Is there any way I can format the DataBinder.Eval() to see the child item? If so, I can't figure it out and hours of searching having been unsuccessful. Or should I be tackling this differently? Perhaps not using a DataSet? Any help is appreciated. Thanks.
You can try with xDoc and linq and anonymous type as,
prodDetail.DataSource = from item in xDoc.Descendants("product")
from needThis in item.Descendants("customization")
select new
{ ProductName = item.Element("sku").Value,
ID = item.Element("prodID").Value,
//----other properties----
Option1 = needThis.Element("option1").Value,
Option2 = needThis.Element("option2").Value,
//---and some more properties----
};
you have to make sure you give the property names of the anonymous object same as the property names you are expecting in the databind in datalist.
I am pulling data from an access database to show in a GridView control on a ASP.NET project. It works fine but I want to see if I can format the data that is being pulled. Currently any currency is being truncated from xx.xx to just the dollar amounts. Also the dates are displaying mm/dd/yyyy hh/mm/ss AM/PM
I tried editing the database itself to the right values (I set the currency field to "Currency" and the date field to "Short Date" but when I pull that date it still shows them not formatted.
EDIT: Sorry, had to take the code down
Any ideas?
Thank you
in the grid view of yours add the property called DataFormatString
DataFormatString examples:
{0:dd MMMM yyyy} - gives 24 February 2006
{0:MMM dd} - gives Feb 24 (substitue MMM with MMMM for the full month name
instead of abbreviation)
{0:dd/MM/yy} - gives 24/02/06
{0:dd/MM/yyyy} - gives 24/02/2006
Sample Code
<asp:BoundField HeaderText="Date"
DataField="SampleDate"
DataFormatString="{0:MM/dd/yyyy}" >
MSDN BoundField.DataFormatString Property
You just need to set the dataformatstring with how you want it to be populated.
As exemplified on the MSDN page:
Money:
<asp:BoundColumn HeaderText="Price" DataField="Price"
DataFormatString="{0:c}" />
With the {0:c}, placing a number after the c value (such as {0:c2}) will give you that many decimal places.
Date:
<asp:boundfield datafield="MyDate" dataformatstring="{0:MM/dd/yyyy}" />
One solution would be:
<asp:GridView ID="gvLEmployees" runat="server" AutoGenerateColumns="false" >
<Columns>
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<%# Eval("Name") %>
</asp:TemplateField>
<asp:TemplateField HeaderText="Date">
<ItemTemplate>
<%# Convert.ToDateTime(Eval("JoinDate")).ToShortDateString() %>
OR
<%# Convert.ToDateTime(Eval("JoinDate")).ToString("d") %>
</ItemTemplate>
</asp:TemplateField>
</Column>
</Gridview>
You have to Create a BoundField, set its properties including the property dataformatstring which you can use to set format of the field appear in the GridView, and add it to the GridView control.
here below some code
public GridView Cr_GridView(string[] ColNames,string[] ColLable, string[] ColFormat)
{
GridView GV = new GridView();
int x = ColNames.GetUpperBound(0);
for (int i = 0; i < x; i++)
{
BoundField GvField = new BoundField();
GvField.DataField = ColNames[i];
GvField.HeaderText = ColLable[i];
GvField.DataFormatString = ColFormat[i];// for example "{0:dd/MM/yyyy}" for a date field
GV.Columns.Add(GvField);
}
return GV;
}
You can also check if you are using Template Field:
<asp:TemplateField HeaderText="last_modified_date">
<ItemTemplate>
<asp:Label ID="lblModyDate" runat="server" Font-Size="10px" CssClass="ControlStyleUpperCase"
Text='<%# Bind("last_modified_date","{0:dd/MM/yyyy HH:mm:tt}") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
Hi ,
I have added a new value EncrypedStatusId in DataNavigateUrlFields
And i am getting error as
"A field or property with the name'EncrypedStatusId' was not found on the selected data source."
but my list do has the property EncrypedStatusId which contain value
How to solve this?
ASPX:
<asp:HyperLinkField HeaderText="Status" DataTextField="AppStatus" DataNavigateUrlFields="NavigateUrl,Id,EncrypedStatusId"
SortExpression="AppStatus" DataNavigateUrlFormatString="{0}?Id={1}"></asp:HyperLinkField>
<asp:TemplateField>
<ItemTemplate>
<asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl='<%# Eval("NavigateUrl","{0}").Replace(":", Server.UrlEncode(":")) %>'
DataTextField="AppStatus"></asp:HyperLink>
</ItemTemplate>
</asp:TemplateField>
CODE BEHIND :
List<DTO> listDto;
IApplication engine;
engine = new Engine();
listDto = engine.ReadHistory(Session["UserID"].ToString());
this.dvHistory.DataSource = listDto;
this.dvHistory.DataBind();
do you have it in the gridview property datakeynames=[EncrypedStatusId,...]
Check that the column EncrypedStatusId column exists in your datasource.
So I've got the following column defined in my radgrid:
<telerik:GridTemplateColumn DataField="Payment.Customer.FirstName" DataType="System.String"
HeaderText="First Name" SortExpression="Payment.Customer.FirstName" UniqueName="FirstName">
<ItemTemplate>
<asp:HyperLink ID="hypFirstName" runat="server" Target="_blank" Text='<%# ((PaymentIssue)Container.DataItem).Payment.Customer.FirstName %>'
NavigateUrl='<%# string.Format("~/CustomerAdmin/Customer_View.aspx?customerId={0}", ((PaymentIssue)Container.DataItem).Payment.CustomerId) %>'></asp:HyperLink>
</ItemTemplate>
</telerik:GridTemplateColumn>
Now, if I use the RadGrid MasterTableView.ExportToExcel() function; all is well. However; if I try MasterTableView.ExportToCSV(), the column is blank.
Any ideas on what could be causing this?
OK; I figured this out. Turns out I need to set the Text property on the GridDataItems before exporting.
Sample code below:
Export Buttons Click Method
protected void lnkExport_Click(object sender, EventArgs e)
{
var linkButton = (LinkButton)sender;
switch (linkButton.CommandArgument)
{
case "Excel":
rgPaymentIssues.MasterTableView.ExportToExcel();
break;
case "CSV":
PrepareRadGridForExport();
rgPaymentIssues.MasterTableView.ExportToCSV();
break;
default:
break;
}
}
PrepareRadGridForExport snippet
foreach (GridDataItem gi in rgPaymentIssues.MasterTableView.Items)
{
var hypFirstName = (HyperLink) gi.FindControl("hypFirstName");
gi["FirstName"].Text = hypFirstName.Text;
}
Setting ExportOnlyData to 'False' solves this issue.
See the following link for the details.
http://www.telerik.com/help/aspnet-ajax/grid-csv-export.html
Just in case someone arrives here as I did, you could solve it another way, put another column with Readonly="true" so it doesn't appear in editing mode and the original column with Display="false" so it doesn't appear in view mode, then Export is all good, here's the extract:
<telerik:GridBoundColumn DataField="Email2" HeaderText="Email" UniqueName="Email2a" ReadOnly="true" Exportable="true" />
<telerik:GridTemplateColumn DataField="Email2" HeaderText="Email" UniqueName="Email2" Display="false" Exportable="false">
<EditItemTemplate>
...
</EditItemTemplate>
</telerik:GridTemplateColumn>
Happy coding!