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)
{
try
{
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
ds.Tables.Add(dt);
return ds.GetXml();
}
catch
{
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";
dt.Rows.Add(dr);
dr = dt.NewRow();
dr["Col1"] = "2";
dr["Col2"] = "Test2";
dt.Rows.Add(dr);
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