This is a migrated thread and some comments may be shown as answers.

RadGrid with XmlDataSource

4 Answers 395 Views
Grid
This is a migrated thread and some comments may be shown as answers.
smith spd
Top achievements
Rank 1
smith spd asked on 08 Jun 2010, 07:13 AM

Hi,

I am trying to figure this out for past couple of days.

I would like to know how to implement RadGrid with xmldatasource. It's pretty easy to bind it in the front end. But I would like to bind the xml to gridview from serverside. I would like to use XPath and DOM model to select the nodes/attributes from my Xml to be displayed as columns in the Gridview and content accordingly. My Xml looks something similar to this:

<structure>
<headers>
<headertext text="Product Name">
<headertext text="Product ID">
<headertext text="Product No.">
</headers>
<content>
<row value="Apple">
<row value="123">
<row value="354367">
</row>
</row>

I would like to populate HeaderText (Product Name, Product ID ....  as column header) from server side using XPath and DOM and rows for each of the columns. Basically, there can be many columns and I have to iterate through each of them and display all column with all data.

Secondly, I am not able to create an instance of XmlDocument to load the xml from the server side, causing couple of errors.

Would be great if someone can help me in this issue.

Thanks.

4 Answers, 1 is accepted

Sort by
0
Daniel
Telerik team
answered on 11 Jun 2010, 02:33 PM
Hello Smith,

RadGrid can be bound (through XmlDataSource) to flat XML structures. Sample XML code:
<books>
   <book name="Book1" available="6" published="2006" />
   <book name="Book2" available="4" published="2007" />
</books>

Output:
name
 available published
Book1  6  2006
Book2  4  2007

Each node will become a row and each attribute represents a column. The name of the attribute is the header text of the given column.

Regards,
Daniel
the Telerik team

Do you want to have your say when we set our development plans? Do you want to know when a feature you care about is added or when a bug fixed? Explore the Telerik Public Issue Tracking system and vote to affect the priority of the items.
0
Zura Chikhladze
Top achievements
Rank 1
answered on 13 Jun 2011, 03:00 PM
Hi,

I have bound XMLdatasource to rad grid and when i am inserting/editing or deleting the data it gives these exceptions:

on Insert:
Item has already been added. Key in dictionary: 'ID'  Key being added: 'ID'

on Update:
Object reference not set to an instance of an object.

on Delete:
Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index

Could you please help me out. Thank you. Z.

Code file:


<
telerik:RadGrid ID="RadGrid1" runat="server" AllowFilteringByColumn="True" AllowPaging="True"
            AllowSorting="True" DataSourceID="XmlDataSource1" GridLines="None" 
            OnInsertCommand="RadGrid1_InsertCommand" OnUpdateCommand="RadGrid1_UpdateCommand"
                OnDeleteCommand="RadGrid1_DeleteCommand">
            <MasterTableView CommandItemDisplay="Top" AutoGenerateColumns="False" DataSourceID="XmlDataSource1">
                <CommandItemSettings ExportToPdfText="Export to Pdf"></CommandItemSettings>
                <RowIndicatorColumn>
                    <HeaderStyle Width="20px"></HeaderStyle>
                </RowIndicatorColumn>
                <ExpandCollapseColumn>
                    <HeaderStyle Width="20px"></HeaderStyle>
                </ExpandCollapseColumn>
                <Columns>
                    <telerik:GridEditCommandColumn>
                    </telerik:GridEditCommandColumn>
                    <telerik:GridButtonColumn CommandName="Delete" Text="Delete" 
                        UniqueName="column">
                    </telerik:GridButtonColumn>
                    <telerik:GridBoundColumn DataField="ID" HeaderText="ID" SortExpression="ID" UniqueName="ID">
                    </telerik:GridBoundColumn>
                    <telerik:GridBoundColumn DataField="Name" HeaderText="Name" SortExpression="Name"
                        UniqueName="Name">
                    </telerik:GridBoundColumn>
                    <telerik:GridBoundColumn DataField="LastName" HeaderText="LastName" SortExpression="LastName"
                        UniqueName="LastName">
                    </telerik:GridBoundColumn>
                </Columns>
  
<EditFormSettings>
<EditColumn UniqueName="EditCommandColumn1"></EditColumn>
</EditFormSettings>
            </MasterTableView>
        </telerik:RadGrid>
        <br />
        <asp:XmlDataSource ID="XmlDataSource1" runat="server" DataFile="~/App_Data/Curatio.xml" />
        <asp:Label ID="lblMsg" runat="server" Text="Label"></asp:Label>

___________________________________________________________________________________________________

Code behind file:

protected

 

void RadGrid1_UpdateCommand(object source, Telerik.Web.UI.GridCommandEventArgs e)

 

 

{

 

 

GridEditFormItem gridEditFormItem = (GridEditFormItem)e.Item;

 

 

 

Hashtable ht = new Hashtable();

 

 

gridEditFormItem.ExtractValues(ht);

 

 

 

 

String customerID = e.Item.OwnerTableView.Items[e.Item.ItemIndex]["ID"].ToString();

 

 

 

XmlNode node =

 

 

XmlDataSource1.GetXmlDocument().SelectSingleNode(

 

 

String.Format("Employees/Employee[@ID='{0}']", customerID));

 

 

node.Attributes[

"Name"].Value = ConvertNullToEmpty(ht["Name"]);

 

 

node.Attributes[

"LastName"].Value = ConvertNullToEmpty(ht["LastName"]);

 

 

 

try

 

{

XmlDataSource1.Save();

}

 

catch (Exception ex)

 

 

{

 

lblMsg.Text = ex.Message;

 

}

 

RefreshXmlFile();

 

}

 

 

protected void RadGrid1_InsertCommand(object source, GridCommandEventArgs e)

 

 

{

 

 

GridEditFormItem gridEditFormItem = (GridEditFormItem)e.Item;

 

 

 

Hashtable ht = new Hashtable();

 

 

gridEditFormItem.ExtractValues(ht);

 

 

int maxCustomerId = 0;

 

 

 

foreach (XmlNode selectedNode in XmlDataSource1.GetXmlDocument().SelectNodes("Employees/Employee"))

 

 

{

 

 

int customerId = int.Parse("0" + selectedNode.Attributes["ID"].Value);

 

 

 

if (customerId > maxCustomerId)

 

 

maxCustomerId = customerId;

 

}

 

ht.Add(

"ID", maxCustomerId + 1);

 

 

 

XmlNode node = XmlDataSource1.GetXmlDocument().CreateElement("Employee");

 

 

 

foreach (DictionaryEntry entry in ht)

 

 

{

 

 

XmlAttribute attribute = XmlDataSource1.GetXmlDocument().CreateAttribute(entry.Key.ToString());

 

 

attribute.Value = ConvertNullToEmpty(entry.Value);

 

node.Attributes.Append(attribute);

 

}

 

XmlDataSource1.GetXmlDocument().SelectSingleNode(

"Employees").AppendChild(node);

 

 

 

try

 

{

XmlDataSource1.Save();

}

 

catch (Exception ex)

 

 

{

 

lblMsg.Text = ex.Message;

 

}

 

RefreshXmlFile();

 

}

 

 

 

 

private void RefreshXmlFile()

 

 

{

 

 

if (Application["UpdateXmlCounter"] == null)

 

 

{

 

Application[

"UpdateXmlCounter"] = 0;

 

 

 

return;

 

 

}

 

 

Int32 count = (Int32)Application["UpdateXmlCounter"];

 

 

count++;

 

 

if (count > 5)

 

 

{

 

 

try

 

{

 

File.Copy(

 

 

Server.MapPath(

"~/App_Data/Curatio.xml"),

 

 

Server.MapPath(

"~/App_Data/Curatio.xml"),

 

 

 

true);

 

 

 

File.SetAttributes(Server.MapPath("~/~/App_Data/Curatio.xml"), FileAttributes.Normal);

 

 

count = 0;

 

}

 

 

catch (IOException ex)

 

 

{

 

Trace.Write(ex.Message);

 

}

 

lblMsg.Text =

"The xml data file was refreshed!";

 

 

}

 

Application[

"UpdateXmlCounter"] = count;

 

 

}

 

 

 

 

protected void RadGrid1_DeleteCommand(object source, GridCommandEventArgs e)

 

 

{

 

 

GridDataItem gridDataItem = (GridDataItem)e.Item;

 

 

 

Hashtable ht = new Hashtable();

 

 

gridDataItem.ExtractValues(ht);

 

 

String ID = e.Item.OwnerTableView.DataKeyValues[e.Item.ItemIndex]["ID"].ToString();

 

 

 

XmlNode node =

 

 

XmlDataSource1.GetXmlDocument().SelectSingleNode(

 

 

String.Format("Employees/Employee[@ID='{0}']", ID));

 

 

 

XmlNode parent = node.ParentNode;

 

 

parent.RemoveChild(node);

 

 

try

 

{

XmlDataSource1.Save();

}

 

catch (Exception ex)

 

 

{

 

lblMsg.Text = ex.Message;

 

}

 

RefreshXmlFile();

 

}

 

 

private String ConvertNullToEmpty(Object obj)

 

 

{

 

 

if (obj == null)

 

 

{

 

 

return String.Empty;

 

 

}

 

 

else

 

{

 

return obj.ToString();

 

 

}

 

}


____________________________________________________________________________________________

XML FILE:

<

 

Employees>

 

 

<

 

Employee ID="1" Name="A" LastName="B" />

 

 

<

 

Employee ID="2" Name="C" LastName="D" />

 

 

<

 

Employee ID="3" Name="E" LastName="F" />

 

 

</

 

Employees>

 








0
Daniel
Telerik team
answered on 16 Jun 2011, 10:40 AM
Hello Zura,

Straight onto your questions:

1) Update:
You have to get the cell text via the Text property.
String customerID = e.Item.OwnerTableView.Items[e.Item.ItemIndex]["ID"].Text;

2) Insert:
You are trying to add a key with the same name (it already exists). You can modify your code this way if you need to change the value of ID key:
ht["ID"] = maxCustomerId + 1;

3) Delete:
Add ID to the DataKeyNames collection if you want to be able to extract it.
<MasterTableView ... DataKeyNames="ID">

Regards,
Daniel
the Telerik team

Browse the vast support resources we have to jump start your development with RadControls for ASP.NET AJAX. See how to integrate our AJAX controls seamlessly in SharePoint 2007/2010 visiting our common SharePoint portal.

0
Zura Chikhladze
Top achievements
Rank 1
answered on 20 Jun 2011, 10:37 AM
Daniel, thank you so much.
Tags
Grid
Asked by
smith spd
Top achievements
Rank 1
Answers by
Daniel
Telerik team
Zura Chikhladze
Top achievements
Rank 1
Share this question
or