Friday, April 29, 2011

How to create a XML File from Datagridview control in Windows Form application?

I am creating a XML file in Windows application, In the form I have DataGridView control, user clicks on the row and enter text or select values from Combo boxes. I create rows programatically, say after 10 rows have been created, i want to save that information to a XML file so that next time my application runs, the datagridview is populated again... What is the best way to do this?

From stackoverflow
  • Got the nice solution:

        private void saveItemDatabase_Click(object sender, EventArgs e)
        {
            DataTable dt = new DataTable("itemstable"); 
    
            for(int i=0; i<itemDataGridView.ColumnCount; i++){
                dt.Columns.Add(itemDataGridView.Columns[i].Name,typeof(System.String));
            }
    
            DataRow myrow ;
            int icols = itemDataGridView.Columns.Count; 
            foreach (DataGridViewRow drow in this.itemDataGridView.Rows) { 
                myrow = dt.NewRow(); 
                for (int i = 0; i <= icols - 1; i++) { 
    
                    myrow[i] = drow.Cells[i].Value; 
                } 
                dt.Rows.Add(myrow); 
            } 
    
            dt.WriteXml("items.xml");
    
        }
    
    Nano HE : It works quite well. Thanks.

0 comments:

Post a Comment