Click here to Skip to main content
15,892,575 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello Guys,

I am pretty new to c#, thus need your advice - I am trying to figure out the ways to write data from textboxes and datagridview on a form to a file.

Tried to search for a similar things thru net, but unfortunately found info about writing either textboxes (serialization) or datagridview data (xml) separately.

What I need is to combine the data coming from all textboxes and a datagridview into a single file, so that later could read it back to them.

Textboxes controls as well as datagridview may contain multiline texts. The datgridview is unbound.

Please help...
Any info is appreciated :)
Posted

You can do it in many ways, one way is use dataset
For Example

//Declare a table
DataTable dtbl = new DataTable("TextBoxValues");
//Add columns for each text box
dtbl.Columns.Add("Textbox1", typeof(string));
//Declare data row
DataRow dr = dtbl.NewRow();
//Assign column values
dr["Textbox1"] = Textbox1.Text;
//Addd row to datatable
dtbl.Rows.Add(dr);
//Declare a dataset
DataSet ds = new DataSet();
//Add table to dataset
ds.Tables.Add(dtbl);
//Add grid bound table to dataset
//Assume your datasource is a datatable
ds.Tables.Add((DataTable)DataGridview1.DataSource);
//Write data with schema to xml file
ds.WriteXml("C:\\test\\test.xml", XmlWriteMode.WriteSchema);
 
Share this answer
 
v2
Comments
Bratec_Lis 29-Sep-14 7:27am    
Thanks! Will try your way :)
Bratec_Lis 29-Sep-14 7:52am    
This row
ds.Tables.Add(DataGridview1.DataSource);

throws error:
Argument '1': cannot convert from 'object' to 'System.Data.DataTable'

Could you please help me with this?
Abdul Samad KP 29-Sep-14 11:47am    
How you are binding your DataGrid?
If you are binding from datatable try this
ds.Tables.Add((DataTable)DataGridview1.DataSource);
Bratec_Lis 30-Sep-14 2:03am    
Hello Abdul,

My data is not from DB - all the grid is fulfilled manually as well as the textboxes.
I have already found the way to fix this and currently able to write data from textboxes as well as datagrid.

Now, I am trying to find a solution of how to retrieve the data back from xml to the form.
The way of writing is as follows:
1. Combine data from textboxes to datatable: 1 row with strings from textboxes as well as # of columns = number of boxes on the form
2. Add the datatable (namely i.e. "txtDataTable" to created DataSet)
3. Take data from datagridview to newly created datatable (namely i.e. "dgvDataTable" where # of columns and rows = # of them in the dgv)
4. Add the "dgvDataTable" to the DataSet
5. Writing the DataSet to XML file using XmlWriteMode.WriteSchema
...
6. Now I am trying to find a way to read the schema from XML back to the form (textboxes and dgv). Any suggestions?
Thx!
Abdul Samad KP 30-Sep-14 4:57am    
Just reverse the process
1. Declare the dataset
2. Read xml (ds.ReadXml("your xml filepath", XmlReadMode.ReadSchema);)
3. Get dgvDataTable from the ds and bind to grid
(If you have given a name to the datattable while declaring it(before saving) then you can get it by name like ds.Tables["dgvDataTable "]; or you can use index)
4. Get txtDataTable from the ds
5. Get textbox value from the txtDataTable
If you have marked "# of columns" as primary key then you can find the row by txtDataTable.Rows.Find(<column number="">)(this will return datarow) else you can use txtDataTable.Select("[# of columns]=<column number="">") (this will return datarow array)

6. Assign values to textbox
Finally got it working (below is the code for anyone might be interested in - could appear not ideal, but at least works for me:)):

//Writing script to file
        private void SaveToFile()
        {

            DataTable dtbl = new DataTable("TestScriptHeader");
            dtbl.Columns.Add("TestScriptDescription", typeof(string));
            dtbl.Columns.Add("TestScriptPre-Cond", typeof(string));
            DataRow dr = dtbl.NewRow();
            dr["TestScriptDescription"] = DescriptionText.Text;
            dr["TestScriptPre-Cond"] = PreliminaryConditionsText.Text;
            dtbl.Rows.Add(dr);
            DataSet DS = new DataSet();
            DS.Tables.Add(dtbl);

            ////
            DataTable tsgDataTable = new DataTable("TestScriptGridDataTable");

            foreach (DataGridViewColumn column in TestScriptGrid.Columns)
            {
                if (column.Visible)
                {
                    tsgDataTable.Columns.Add(column.HeaderText);
                }
            }

            object[] cellValues = new object[TestScriptGrid.Columns.Count];
            foreach (DataGridViewRow row in TestScriptGrid.Rows)
            {
                for (int i = 0; i < row.Cells.Count; i++)
                {
                    cellValues[i] = row.Cells[i].Value;
                }
                tsgDataTable.Rows.Add(cellValues);
            }
            DS.Tables.Add(tsgDataTable);
            ////

            DS.WriteXml(@"C:\temp\1111111111.xml", XmlWriteMode.WriteSchema);
        }
        
        //Open script file
        private void FileOpen_Click(object sender, EventArgs e)
        {
            if (opnFileDialog.ShowDialog() == DialogResult.OK)
            {
                fileName = opnFileDialog.FileName;

                DataSet DSFromXML = new DataSet();
                DSFromXML.ReadXml(fileName, XmlReadMode.ReadSchema);

                DataRow dr = DSFromXML.Tables["TestScriptHeader"].Rows[0];
                DescriptionText.Text = dr["TestScriptDescription"].ToString();
                PreliminaryConditionsText.Text = dr["TestScriptPre-Cond"].ToString();

                //////Retrieving data from xml to TestScriptGrid
                DataTable DTFromXMLtoGrid = DSFromXML.Tables["TestScriptGridDataTable"];
                object[] columnCellValues = new object[DTFromXMLtoGrid.Columns.Count];
                TestScriptGrid.Rows.Clear();

                foreach (DataRow DRdgv in DTFromXMLtoGrid.Rows)
                {
                    if (DTFromXMLtoGrid.Rows.IndexOf(DRdgv) == DTFromXMLtoGrid.Rows.Count - 1)
                        break;
                    for (int c = 0; c < DRdgv.ItemArray.Count(); c++)
                    {
                        columnCellValues[c] = DRdgv.ItemArray[c];
                    }
                    TestScriptGrid.Rows.Add(columnCellValues);
                }
            }
        }
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900