Get XML of DataSource from (DataGrid, DataTable, ListBox, DropDown)

Posted by Neeks under C# category on | Views : 3793
Get the static method to get the XML data for the table like data (i.e. DataType that can be converted to DataTable).

Create static method in class so we can use it in multiple classes where we want the XML string.

class clsStatic
public static string XMLString(object obj)

DataTable dt = new DataTable("XMLData");//We have to provide the name of the node
dt = (DataTable)obj;
DataSet ds = new DataSet("XMLDs"); //We have to provide the name of Root NOde
return ds.GetXml();
throw new Exception("Cannot convert to DataTable");


Now, we can call the method like

DataTable dt = new DataTable("DtTable");
dt.Columns.Add(new DataColumn("Col1", typeof(String)));
dt.Columns.Add(new DataColumn("Col2", typeof(String)));

DataRow dr = null;
dr = dt.NewRow();
dr["Col1"] = "1";
dr["Col2"] = "Test1";

dr = dt.NewRow();
dr["Col1"] = "2";
dr["Col2"] = "Test2";

listBox1.DataSource = dt;
listBox1.DisplayMember = "Col1";
listBox1.DisplayMember = "Col2";

MessageBox.Show(clsStatic.XMLString(listBox1.DataSource)); //This will return the XML string
MessageBox.Show(clsStatic.XMLString(10)); //This will throw Error

Comments or Responses

Login to post response