In this article I will explain with an example, how to bind DataGridView using XML data from URL in Windows Forms (WinForms) Application with C# and VB.Net.
XML File
The following XML file will be used in this article.
<?xml version="1.0" standalone="yes" ?>
<Customers>
<Customer>
<Id>1</Id>
<Name>John Hammond</Name>
<Country>United States</Country>
</Customer>
<Customer>
<Id>2</Id>
<Name>Mudassar Khan</Name>
<Country>India</Country>
</Customer>
<Customer>
<Id>3</Id>
<Name>Suzanne Mathews</Name>
<Country>France</Country>
</Customer>
<Customer>
<Id>4</Id>
<Name>Robert Schidner</Name>
<Country>Russia</Country>
</Customer>
</Customers>
Form Design
The Form consists of following control:
DataGridView – For displaying records.
Namespaces
You will need to import the following namespaces.
C#
using System.IO;
using System.Net;
using System.Data;
VB.Net
Imports System.IO
Imports System.Net
Imports System.Data
Binding data to DataGridView from Database using DataTable in C# and VB.Net
Inside the Form_Load event handler, first the Security Protocol is set.
Next, the XML string is downloaded from URL using DownloadString method of the WebClient class.
DownloadString method
It accepts the following parameter:
address – The URL of the file to be downloaded.
Next, the DataSet class object is initialized and the XML string is read using StringReader class.
Then, the read XML string is stored in the DataSet using ReadXML method.
Finally, the DataSet is assigned to the DataSource property of the DataGridView and the DataGridView is populated with XML data.
Note: Though it is not a good practice to use DataSet or DataTable as Model in View in MVC architecture, thus user’s please make a note that this is just an informative article and does not recommend to use DataSet or DataTable as Model in View in ASP.Net MVC.
C#
private void Form1_Load(object sender, EventArgs e)
{
ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;
string xml = (new WebClient()).DownloadString("https://raw.githubusercontent.com/aspsnippets/test/master/Customers.xml");
using (DataSet ds = new DataSet())
{
using (StringReader sr = new StringReader(xml))
{
ds.ReadXml(sr);
dataGridView1.DataSource = ds.Tables[0];
}
}
}
VB.Net
Private Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs)
ServicePointManager.Expect100Continue = True
ServicePointManager.SecurityProtocol = CType(3072,SecurityProtocolType)
Dim xml As String = (New WebClient()).DownloadString("https://raw.githubusercontent.com/aspsnippets/test/master/Customers.xml")
Using ds As DataSet = New DataSet()
Using sr As StringReader = New StringReader(xml)
ds.ReadXml(sr)
DataGridView1.DataSource = ds.Tables(0)
End Using
End Using
End Sub
Screenshot
Downloads