C# - Using the DataGrid Control - Sử dụng dataGird COntrol với ADO.Net

Discussion in 'C & C++' started by Mickey, Dec 6, 2017.

  1. Mickey

    Mickey Hacking For Hacker Staff Member

    Introduction

    This small application for DataGrid allows users to:


    • add a new row in the DataGrid.
    • save or update a row of the DataGrid.
    • delete an existing row from the DataGrid.
    • read the data from an XML file.
    • copy the current data of the DataSet to three files on C:\ root directory:
      1. MyXMLText.txt (text file)
      2. MyXMLdata.xml (XML file)
      3. MyXMLschema.xsd (schema file)
    • write the current data of the table to a text file on C:\.

    The DataGrid control in the "DataGrid Application" binds to a single DataSet object. The DataSet object of the "DataGrid Application" is initially populated from a database using an OleDbDataAdapter object.
    What is a DataGrid?

    The Windows Forms DataGrid control provides a user interface to ADO.NET datasets, displays ADO.NET tabular data in a scrollable grid, and allows for updates to the data source. In cases where the DataGrid is bound to a data source with a single table containing no relationships, the data appears in simple rows and columns, as in a spreadsheet. The DataGrid control is one of the most useful and flexible controls in Windows Forms. As soon as the DataGrid control is set to a valid data source, the control is automatically populated, by creating columns and rows based on the structure of the data. The DataGrid control can be used to display either a single table or the hierarchical relationships between a set of tables.
    For example: if you bind the DataGrid to data with multiple related tables, and if you enable navigation on the DataGrid, the DataGrid displays so called 'expanders' in each row.
    [​IMG]



    With an expander, you can navigate from a parent table to a child table. If you click a node in the DataGrid, it displays the child table. If you click the Back button, it displays the original parent table. In this fashion, the grid displays the hierarchical relationships between tables.
    [​IMG]

    Bear in mind that only one table can be shown in the DataGrid at a time. Valid data sources for the DataGrid include:


    • DataTable
    • DataView
    • DataSet
    • DataViewManager
    • A single dimension array
    • Any component that implements the IListSource interface.

    How to display data in the DataGrid programmatically?

    If you want to display data in a DataGrid, you need to define a DataGrid object. There are, of course, different ways to populate the data in the DataGrid. For example:
    Define first a DataGrid and declare a new DataGrid, and then set some properties of the DataGrid (location, name, size etc..).
    PHP:
    :
    [
    COLOR=#000000][COLOR=#007700]private [/COLOR][COLOR=#0000BB]System[/COLOR][COLOR=#007700].[/COLOR][COLOR=#0000BB]Windows[/COLOR][COLOR=#007700].[/COLOR][COLOR=#0000BB]Forms[/COLOR][COLOR=#007700].[/COLOR][COLOR=#0000BB]DataGrid dataGrid1[/COLOR][COLOR=#007700];
       
    [/COLOR][COLOR=#0000BB]this[/COLOR][COLOR=#007700].[/COLOR][COLOR=#0000BB]dataGrid1 [/COLOR][COLOR=#007700]= new [/COLOR][COLOR=#0000BB]System[/COLOR][COLOR=#007700].[/COLOR][COLOR=#0000BB]Windows[/COLOR][COLOR=#007700].[/COLOR][COLOR=#0000BB]Forms[/COLOR][COLOR=#007700].[/COLOR][COLOR=#0000BB]DataGrid[/COLOR][COLOR=#007700]();
       
    [/COLOR][COLOR=#0000BB]this[/COLOR][COLOR=#007700].[/COLOR][COLOR=#0000BB]dataGrid1[/COLOR][COLOR=#007700].[/COLOR][COLOR=#0000BB]Location [/COLOR][COLOR=#007700]= new [/COLOR][COLOR=#0000BB]System[/COLOR][COLOR=#007700].[/COLOR][COLOR=#0000BB]Drawing[/COLOR][COLOR=#007700].[/COLOR][COLOR=#0000BB]Point[/COLOR][COLOR=#007700]([/COLOR][COLOR=#0000BB]16[/COLOR][COLOR=#007700], [/COLOR][COLOR=#0000BB]40[/COLOR][COLOR=#007700]);
       
    [/COLOR][COLOR=#0000BB]this[/COLOR][COLOR=#007700].[/COLOR][COLOR=#0000BB]dataGrid1[/COLOR][COLOR=#007700].[/COLOR][COLOR=#0000BB]Name [/COLOR][COLOR=#007700]= [/COLOR][COLOR=#DD0000]"dataGrid1"[/COLOR][COLOR=#007700];
       
    [/COLOR][COLOR=#0000BB]this[/COLOR][COLOR=#007700].[/COLOR][COLOR=#0000BB]dataGrid1[/COLOR][COLOR=#007700].[/COLOR][COLOR=#0000BB]Size [/COLOR][COLOR=#007700]= new [/COLOR][COLOR=#0000BB]System[/COLOR][COLOR=#007700].[/COLOR][COLOR=#0000BB]Drawing[/COLOR][COLOR=#007700].[/COLOR][COLOR=#0000BB]Size[/COLOR][COLOR=#007700]([/COLOR][COLOR=#0000BB]256[/COLOR][COLOR=#007700], [/COLOR][COLOR=#0000BB]176[/COLOR][COLOR=#007700]);  [/COLOR][/COLOR]


    Now we can put all the commands needed into a method "fnDisplayDataInDataGrid()", to display data in the DataGrid.

    PHP:

    :
    [
    COLOR=#000000] [COLOR=#007700]private [/COLOR][COLOR=#0000BB]void fnDisplayDataInDataGrid[/COLOR][COLOR=#007700]()
    {
       [/
    COLOR][COLOR=#0000BB]string conStr [/COLOR][COLOR=#007700]=[/COLOR][COLOR=#DD0000]"Integrated Security=SSPI;" [/COLOR][COLOR=#007700]+
       
    [/COLOR][COLOR=#DD0000]"Initial Catalog=Northwind;" [/COLOR][COLOR=#007700]+
       
    [/COLOR][COLOR=#DD0000]"Data Source=SONY\\MYSQLSERVER;"[/COLOR][COLOR=#007700];
       
    [/COLOR][COLOR=#0000BB]SqlConnection conn [/COLOR][COLOR=#007700]= new [/COLOR][COLOR=#0000BB]SqlConnection[/COLOR][COLOR=#007700]([/COLOR][COLOR=#0000BB]conStr[/COLOR][COLOR=#007700]);
       
    [/COLOR][COLOR=#FF8000]// Open the connection

       
    [/COLOR][COLOR=#0000BB]conn[/COLOR][COLOR=#007700].[/COLOR][COLOR=#0000BB]Open[/COLOR][COLOR=#007700]();
       
    [/COLOR][COLOR=#FF8000]// Create a data adapter object

       
    [/COLOR][COLOR=#0000BB]SqlDataAdapter adapter [/COLOR][COLOR=#007700]= new [/COLOR][COLOR=#0000BB]SqlDataAdapter[/COLOR][COLOR=#007700]([/COLOR][COLOR=#DD0000]"SELECT * FROM MyTable"[/COLOR][COLOR=#007700], [/COLOR][COLOR=#0000BB]conn[/COLOR][COLOR=#007700]);
       
    [/COLOR][COLOR=#FF8000]// Create a DataSet object

       
    [/COLOR][COLOR=#0000BB]DataSet ds [/COLOR][COLOR=#007700]= new [/COLOR][COLOR=#0000BB]DataSet[/COLOR][COLOR=#007700]();
       
    [/COLOR][COLOR=#FF8000]// filling the DataSet

       
    [/COLOR][COLOR=#0000BB]adapter[/COLOR][COLOR=#007700].[/COLOR][COLOR=#0000BB]Fill[/COLOR][COLOR=#007700]([/COLOR][COLOR=#0000BB]ds[/COLOR][COLOR=#007700],[/COLOR][COLOR=#DD0000]"MyTable"[/COLOR][COLOR=#007700]);
       
    [/COLOR][COLOR=#FF8000]// you can use one of the followings.Both works fine.

       // this.dataGrid1.SetDataBinding(ds,"MyTable"); or

       
    [/COLOR][COLOR=#0000BB]this[/COLOR][COLOR=#007700].[/COLOR][COLOR=#0000BB]dataGrid1[/COLOR][COLOR=#007700].[/COLOR][COLOR=#0000BB]DataSource[/COLOR][COLOR=#007700]=[/COLOR][COLOR=#0000BB]ds[/COLOR][COLOR=#007700].[/COLOR][COLOR=#0000BB]DefaultViewManager[/COLOR][COLOR=#007700];

    [/
    COLOR] [/COLOR]
    How It Works

    After you get connected to the MS Access database, all records are displayed on the DataGrid.
    When you run the application first time, the method "fnRefresh()" will be called. It clears the contents of the DataSet, fills the DataAdapter, and displays the data from the data source in the DataGrid. After that, all the buttons are ready to be used. Here is the code snippet of the method "fnRefresh()":

    PHP:
    :
    [
    COLOR=#000000] [COLOR=#007700]private [/COLOR][COLOR=#0000BB]void fnRefresh[/COLOR][COLOR=#007700]()
    {
       [/
    COLOR][COLOR=#0000BB]this[/COLOR][COLOR=#007700].[/COLOR][COLOR=#0000BB]dataSet11[/COLOR][COLOR=#007700].[/COLOR][COLOR=#0000BB]Clear[/COLOR][COLOR=#007700]();
       
    [/COLOR][COLOR=#0000BB]this[/COLOR][COLOR=#007700].[/COLOR][COLOR=#0000BB]oleDbDataAdapter1[/COLOR][COLOR=#007700].[/COLOR][COLOR=#0000BB]Fill[/COLOR][COLOR=#007700]([/COLOR][COLOR=#0000BB]this[/COLOR][COLOR=#007700].[/COLOR][COLOR=#0000BB]dataSet11[/COLOR][COLOR=#007700],[/COLOR][COLOR=#DD0000]"MyContactsTable"[/COLOR][COLOR=#007700]);
       
    [/COLOR][COLOR=#0000BB]this[/COLOR][COLOR=#007700].[/COLOR][COLOR=#0000BB]dataGrid1[/COLOR][COLOR=#007700].[/COLOR][COLOR=#0000BB]DataSource[/COLOR][COLOR=#007700]=[/COLOR][COLOR=#0000BB]this[/COLOR][COLOR=#007700].[/COLOR][COLOR=#0000BB]dataSet11[/COLOR][COLOR=#007700].[/COLOR][COLOR=#0000BB]Tables[/COLOR][COLOR=#007700][[/COLOR][COLOR=#DD0000]"MyContactsTable"[/COLOR][COLOR=#007700]].[/COLOR][COLOR=#0000BB]DefaultView[/COLOR][COLOR=#007700];

    [/
    COLOR] [/COLOR]
    Insert a new row

    If you click the "Insert" button to add a new record, the last row on the DataGrid is selected and the previous clicked row is unselected. After entering the data for that row, you click the 'Save/Update'-button to save the new row. Here is the method for inserting a new row:

    PHP:
        [COLOR=#000000] [COLOR=#007700]private [/COLOR][COLOR=#0000BB]void fnInsertNew[/COLOR][COLOR=#007700]()
    {
       [/
    COLOR][COLOR=#FF8000]//keep in mind the previous clicked row to unselect

       
    [/COLOR][COLOR=#0000BB]int iPrevRowindex[/COLOR][COLOR=#007700]=[/COLOR][COLOR=#0000BB]this[/COLOR][COLOR=#007700].[/COLOR][COLOR=#0000BB]iRowIndex[/COLOR][COLOR=#007700];
       
    [/COLOR][COLOR=#0000BB]MessageBox[/COLOR][COLOR=#007700].[/COLOR][COLOR=#0000BB]Show[/COLOR][COLOR=#007700]([/COLOR][COLOR=#DD0000]"Enter the new record at the end" [/COLOR][COLOR=#007700]+
        
    [/COLOR][COLOR=#DD0000]" of the DataGrid and click 'Save/Update'-button"[/COLOR][COLOR=#007700], [/COLOR][COLOR=#DD0000]"Stop"[/COLOR][COLOR=#007700]);
       
    [/COLOR][COLOR=#0000BB]this[/COLOR][COLOR=#007700].[/COLOR][COLOR=#0000BB]btInsertnew[/COLOR][COLOR=#007700].[/COLOR][COLOR=#0000BB]Enabled[/COLOR][COLOR=#007700]=[/COLOR][COLOR=#0000BB]false[/COLOR][COLOR=#007700];
       
    [/COLOR][COLOR=#FF8000]//get how many records in the table

       
    [/COLOR][COLOR=#0000BB]this[/COLOR][COLOR=#007700].[/COLOR][COLOR=#0000BB]iRowIndex[/COLOR][COLOR=#007700]=[/COLOR][COLOR=#0000BB]this[/COLOR][COLOR=#007700].[/COLOR][COLOR=#0000BB]dataSet11[/COLOR][COLOR=#007700].[/COLOR][COLOR=#0000BB]Tables[/COLOR][COLOR=#007700][[/COLOR][COLOR=#DD0000]"MyContactsTable"[/COLOR][COLOR=#007700]].[/COLOR][COLOR=#0000BB]Rows[/COLOR][COLOR=#007700].[/COLOR][COLOR=#0000BB]Count[/COLOR][COLOR=#007700];
       
    [/COLOR][COLOR=#FF8000]//select the last row

       
    [/COLOR][COLOR=#0000BB]this[/COLOR][COLOR=#007700].[/COLOR][COLOR=#0000BB]dataGrid1[/COLOR][COLOR=#007700].[/COLOR][COLOR=#0000BB]Select[/COLOR][COLOR=#007700]([/COLOR][COLOR=#0000BB]this[/COLOR][COLOR=#007700].[/COLOR][COLOR=#0000BB]iRowIndex[/COLOR][COLOR=#007700]);
       
    [/COLOR][COLOR=#FF8000]//unselect the previous row

       
    [/COLOR][COLOR=#0000BB]this[/COLOR][COLOR=#007700].[/COLOR][COLOR=#0000BB]dataGrid1[/COLOR][COLOR=#007700].[/COLOR][COLOR=#0000BB]UnSelect[/COLOR][COLOR=#007700]([/COLOR][COLOR=#0000BB]iPrevRowindex[/COLOR][COLOR=#007700]);

    [/
    COLOR] [/COLOR]
    Save or Update the new/changed row(s)

    The code snippet for the method "fnSaveUpdate()" saves the changes that are made to the DataSet back to the database. The 'GetChanges' method of dataSet11 will return a new DataSet which is called 'myChangedDataset' containing all the rows that have been modified (updated, deleted or inserted). If no changes have been made, the method 'GetChanges' returns a 'null' DataSet.
    If any sort of error occurs while updating the database, the 'Update' method of OleDbDataAdapter will generate an exception. This logic is held in a try/catch block. If an exception occurs, you get a message box informing you of the error. And the "RejectChanges" method is then called to discard the changes you made. If any changes are made, the user is told how many rows were affected/changed, and the "AcceptChanges()" method will mark the changes made as permanent in the DataSet. Now we need to invoke refreshing the DataSet with the method "fnRefresh()". I think this is a 'simple' and robust technique when updating the database.
    Here is the code snippet for the 'fnSaveUpdate()' method:
    PHP:
    :
    [
    COLOR=#000000] [COLOR=#007700]private [/COLOR][COLOR=#0000BB]void fnSaveUpdate[/COLOR][COLOR=#007700]()
    {
       try
       {
         [/
    COLOR][COLOR=#FF8000]//put the modified DataSet into a new DataSet(myChangedDataset)

         
    [/COLOR][COLOR=#0000BB]DataSet myChangedDataset[/COLOR][COLOR=#007700]= [/COLOR][COLOR=#0000BB]this[/COLOR][COLOR=#007700].[/COLOR][COLOR=#0000BB]dataSet11[/COLOR][COLOR=#007700].[/COLOR][COLOR=#0000BB]GetChanges[/COLOR][COLOR=#007700]();
         
    if ([/COLOR][COLOR=#0000BB]myChangedDataset [/COLOR][COLOR=#007700]!= [/COLOR][COLOR=#0000BB]null[/COLOR][COLOR=#007700])
        
    {
           [/
    COLOR][COLOR=#FF8000]//get how many rows changed

           
    [/COLOR][COLOR=#0000BB]int modifiedRows [/COLOR][COLOR=#007700]= [/COLOR][COLOR=#0000BB]this[/COLOR][COLOR=#007700].[/COLOR][COLOR=#0000BB]oleDbDataAdapter1[/COLOR][COLOR=#007700].[/COLOR][COLOR=#0000BB]Update[/COLOR][COLOR=#007700]([/COLOR][COLOR=#0000BB]myChangedDataset[/COLOR][COLOR=#007700]);
           
    [/COLOR][COLOR=#0000BB]MessageBox[/COLOR][COLOR=#007700].[/COLOR][COLOR=#0000BB]Show[/COLOR][COLOR=#007700]([/COLOR][COLOR=#DD0000]"Database has been updated successfully: " [/COLOR][COLOR=#007700]+
                         
    [/COLOR][COLOR=#0000BB]modifiedRows [/COLOR][COLOR=#007700]+ [/COLOR][COLOR=#DD0000]" Modified row(s) "[/COLOR][COLOR=#007700], [/COLOR][COLOR=#DD0000]"Success"[/COLOR][COLOR=#007700]);
           
    [/COLOR][COLOR=#0000BB]this[/COLOR][COLOR=#007700].[/COLOR][COLOR=#0000BB]dataSet11[/COLOR][COLOR=#007700].[/COLOR][COLOR=#0000BB]AcceptChanges[/COLOR][COLOR=#007700](); [/COLOR][COLOR=#FF8000]//accept the all changes

           
    [/COLOR][COLOR=#0000BB]fnRefresh[/COLOR][COLOR=#007700]();
        
    }
        else
        }
           [/
    COLOR][COLOR=#0000BB]MessageBox[/COLOR][COLOR=#007700].[/COLOR][COLOR=#0000BB]Show[/COLOR][COLOR=#007700]([/COLOR][COLOR=#DD0000]"Nothing to save"[/COLOR][COLOR=#007700], [/COLOR][COLOR=#DD0000]"No changes"[/COLOR][COLOR=#007700]);
         
    }[/COLOR][COLOR=#FF8000]//if-else

       
    [/COLOR][COLOR=#007700]}
       
    catch([/COLOR][COLOR=#0000BB]Exception ex[/COLOR][COLOR=#007700])
      
    {
        [/
    COLOR][COLOR=#FF8000]//if something somehow went wrong

       
    [/COLOR][COLOR=#0000BB]MessageBox[/COLOR][COLOR=#007700].[/COLOR][COLOR=#0000BB]Show[/COLOR][COLOR=#007700]([/COLOR][COLOR=#DD0000]"An error occurred updating the database: " [/COLOR][COLOR=#007700]+
         
    [/COLOR][COLOR=#0000BB]ex[/COLOR][COLOR=#007700].[/COLOR][COLOR=#0000BB]Message[/COLOR][COLOR=#007700], [/COLOR][COLOR=#DD0000]"Error"[/COLOR][COLOR=#007700],  [/COLOR][COLOR=#0000BB]MessageBoxButtons[/COLOR][COLOR=#007700].[/COLOR][COLOR=#0000BB]OK[/COLOR][COLOR=#007700], [/COLOR][COLOR=#0000BB]MessageBoxIcon[/COLOR][COLOR=#007700].[/COLOR][COLOR=#0000BB]Error[/COLOR][COLOR=#007700]);
       
    [/COLOR][COLOR=#0000BB]this[/COLOR][COLOR=#007700].[/COLOR][COLOR=#0000BB]dataSet11[/COLOR][COLOR=#007700].[/COLOR][COLOR=#0000BB]RejectChanges[/COLOR][COLOR=#007700](); [/COLOR][COLOR=#FF8000]//cancel the changes

      
    [/COLOR][COLOR=#007700]}[/COLOR][COLOR=#FF8000]//try-catch

      
    [/COLOR][COLOR=#0000BB]fnEnableDisableAllButtons[/COLOR][COLOR=#007700]([/COLOR][COLOR=#0000BB]true[/COLOR][COLOR=#007700]);

    [/
    COLOR] [/COLOR]
    Delete the current row

    It is always a good practice to ask the user before deleting a row. After clicking 'Yes', the current row on the DataGrid is deleted, updated and refreshed. The method for deleting a row is as below:

    PHP Code:
    Mã:
    private void fnDelete()
    {
    //ask user if wanting to delete

    DialogResult dr=MessageBox.Show("Are you sure you want to delete this row ? ",
    "Confirm deleting", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
    if (
    dr ==DialogResult.Yes)
    {
    DataTable tbl=new DataTable("MyContactsTable");
    tbl=this.dataSet11.Tables[0];
    int i=this.iRowIndex;//get the index of the row you clicked

    tbl.Rows[i].Delete(); //delete the row

    this.oleDbDataAdapter1.Update(tbl); //update the table

    this.fnRefresh(); //refresh the table

    }
    }

    Reading the data from an XML file
    [/PHP]

    Sometimes you have to read the data from an XML file and display it in a DataGrid. In order to do this, I pass the XML file to the method; if the file exists, I clear the DataSet and read the XML data into the DataSet using the specified file. The following code snippet shows this:
    PHP:
    :
    [
    COLOR=#000000] [COLOR=#007700]private [/COLOR][COLOR=#0000BB]void fnDataReadingFromXMLFile[/COLOR][COLOR=#007700]([/COLOR][COLOR=#0000BB]string filename[/COLOR][COLOR=#007700])
    {
      [/
    COLOR][COLOR=#FF8000]//check if the file exists

      
    [/COLOR][COLOR=#007700]if ( [/COLOR][COLOR=#0000BB]File[/COLOR][COLOR=#007700].[/COLOR][COLOR=#0000BB]Exists[/COLOR][COLOR=#007700]([/COLOR][COLOR=#0000BB]filename[/COLOR][COLOR=#007700]))
      
    {
       [/
    COLOR][COLOR=#FF8000]//clear the DataSet contents

       
    [/COLOR][COLOR=#0000BB]this[/COLOR][COLOR=#007700].[/COLOR][COLOR=#0000BB]dataSet11[/COLOR][COLOR=#007700].[/COLOR][COLOR=#0000BB]Clear[/COLOR][COLOR=#007700]();
       
    [/COLOR][COLOR=#0000BB]MessageBox[/COLOR][COLOR=#007700].[/COLOR][COLOR=#0000BB]Show[/COLOR][COLOR=#007700]([/COLOR][COLOR=#DD0000]"Data reading from "[/COLOR][COLOR=#007700]+[/COLOR][COLOR=#0000BB]filename[/COLOR][COLOR=#007700]+[/COLOR][COLOR=#DD0000]" -file"[/COLOR][COLOR=#007700]);
       
    [/COLOR][COLOR=#0000BB]this[/COLOR][COLOR=#007700].[/COLOR][COLOR=#0000BB]dataSet11[/COLOR][COLOR=#007700].[/COLOR][COLOR=#0000BB]ReadXml[/COLOR][COLOR=#007700]([/COLOR][COLOR=#0000BB]filename[/COLOR][COLOR=#007700]);
       
    } [/COLOR][COLOR=#FF8000]//if

       
    [/COLOR][COLOR=#007700]else {
       
    [/COLOR][COLOR=#0000BB]MessageBox[/COLOR][COLOR=#007700].[/COLOR][COLOR=#0000BB]Show[/COLOR][COLOR=#007700]([/COLOR][COLOR=#0000BB]filename [/COLOR][COLOR=#007700]+ [/COLOR][COLOR=#DD0000]" does NOT exist; Please click" [/COLOR][COLOR=#007700]+
          
    [/COLOR][COLOR=#DD0000]" first the button 'CopyToXML' "[/COLOR][COLOR=#007700], [/COLOR][COLOR=#DD0000]"File Error"[/COLOR][COLOR=#007700],
          
    [/COLOR][COLOR=#0000BB]MessageBoxButtons[/COLOR][COLOR=#007700].[/COLOR][COLOR=#0000BB]OK[/COLOR][COLOR=#007700], [/COLOR][COLOR=#0000BB]MessageBoxIcon[/COLOR][COLOR=#007700].[/COLOR][COLOR=#0000BB]Error [/COLOR][COLOR=#007700]);
      
    }[/COLOR][COLOR=#FF8000]//else

    [/COLOR][COLOR=#007700]} 
    [/COLOR] [/COLOR]
    Copy the DataSet to the Text / XML / Schema file


    Clicking the 'CopyToXML' button invokes the 'fnCopyToXMLandTextFile()' method. As you can guess from its name, it writes the current data of the DataSet to three files on the C:\ root directory:


    1. Text file: MyXMLdataText.txt.
    2. XML file: XMLdata.xml.
    3. Schema file: MyXMLschema.xsd.

    If you wish to use another path instead of 'C:\', you have to change the code accordingly. The following code snippet demonstrates this feature:
    PHP:
    :
    [
    COLOR=#000000] [COLOR=#007700]private [/COLOR][COLOR=#0000BB]void fnCopyToXMLandTextFile[/COLOR][COLOR=#007700]()
    {
       if ([/
    COLOR][COLOR=#0000BB]this[/COLOR][COLOR=#007700].[/COLOR][COLOR=#0000BB]dataSet11 [/COLOR][COLOR=#007700]== [/COLOR][COLOR=#0000BB]null[/COLOR][COLOR=#007700])
       
    {
           return; [/
    COLOR][COLOR=#FF8000]//cancel

       
    [/COLOR][COLOR=#007700]}
       
    [/COLOR][COLOR=#0000BB]files[/COLOR][COLOR=#007700]. [/COLOR][COLOR=#0000BB]this[/COLOR][COLOR=#007700].[/COLOR][COLOR=#0000BB]dataSet11[/COLOR][COLOR=#007700].[/COLOR][COLOR=#0000BB]WriteXml[/COLOR][COLOR=#007700]([/COLOR][COLOR=#DD0000]"C:\\MyXMLText.txt"[/COLOR][COLOR=#007700]);
       
    [/COLOR][COLOR=#0000BB]this[/COLOR][COLOR=#007700].[/COLOR][COLOR=#0000BB]dataSet11[/COLOR][COLOR=#007700].[/COLOR][COLOR=#0000BB]WriteXml[/COLOR][COLOR=#007700]([/COLOR][COLOR=#DD0000]"C:\\MyXMLdata.xml"[/COLOR][COLOR=#007700], [/COLOR][COLOR=#0000BB]XmlWriteMode[/COLOR][COLOR=#007700].[/COLOR][COLOR=#0000BB]WriteSchema[/COLOR][COLOR=#007700]);
       
    [/COLOR][COLOR=#0000BB]this[/COLOR][COLOR=#007700].[/COLOR][COLOR=#0000BB]dataSet11[/COLOR][COLOR=#007700].[/COLOR][COLOR=#0000BB]WriteXmlSchema[/COLOR][COLOR=#007700]([/COLOR][COLOR=#DD0000]"C:\\MyXMLschema.xsd"[/COLOR][COLOR=#007700]);
       
    [/COLOR][COLOR=#0000BB]string s[/COLOR][COLOR=#007700]=[/COLOR][COLOR=#DD0000]"The current data of the DataSet coppied on C:\\ as: \n"[/COLOR][COLOR=#007700];
       
    [/COLOR][COLOR=#0000BB]s [/COLOR][COLOR=#007700]+=[/COLOR][COLOR=#DD0000]"* Text file: MyXMLdataText.txt\n"[/COLOR][COLOR=#007700];
       
    [/COLOR][COLOR=#0000BB]s [/COLOR][COLOR=#007700]+=[/COLOR][COLOR=#DD0000]"* XML file: XMLdata.xml\n"[/COLOR][COLOR=#007700];
       
    [/COLOR][COLOR=#0000BB]s [/COLOR][COLOR=#007700]+=[/COLOR][COLOR=#DD0000]"* Schema file: MyXMLschema.xsd"[/COLOR][COLOR=#007700];
       
    [/COLOR][COLOR=#0000BB]MessageBox[/COLOR][COLOR=#007700].[/COLOR][COLOR=#0000BB]Show[/COLOR][COLOR=#007700]([/COLOR][COLOR=#0000BB]s[/COLOR][COLOR=#007700], [/COLOR][COLOR=#DD0000]"Copy to XML/Text/Schema file"[/COLOR][COLOR=#007700]);

    [/
    COLOR] [/COLOR]
    Writing the current data of the table into a text file on hard disk (C:\)

    Because ExecuteReader requires an open and available connection, first we have to open the database connection. If the connection's current state is Closed, you get an error message. After opening the connection, we create an instance of OleDbCommand, a CommandText for the SQL statement, an OleDbDataReader and an instance of StreamWriter. And then, in a while-loop, the OleDbDataReader reads through the data rows and writes them out to the text file. Finally, it closes the OleDbDataReader. In StreamWriter writer = new StreamWriter("C:\\MyTextFile.txt", false), we pass the the text file and set the bool value to 'false'. If the file doesn't exist, in any case a new text file will be created. If the file exists and it the second parameter is 'false', the file will be overwritten because of 'false'. If the value is 'true', then the file won't be overwritten and the data will then be appended to the file. Here is the code snippet for writing to the text file:

    PHP:
    :
    [
    COLOR=#000000] [COLOR=#007700]private [/COLOR][COLOR=#0000BB]void fnWriteToTextFile[/COLOR][COLOR=#007700]()
    {
      [/
    COLOR][COLOR=#0000BB]OleDbDataReader reader[/COLOR][COLOR=#007700];
      
    [/COLOR][COLOR=#0000BB]OleDbCommand cmd[/COLOR][COLOR=#007700]=new [/COLOR][COLOR=#0000BB]OleDbCommand[/COLOR][COLOR=#007700](); 
      
    [/COLOR][COLOR=#0000BB]this[/COLOR][COLOR=#007700].[/COLOR][COLOR=#0000BB]oleDbConnection1[/COLOR][COLOR=#007700].[/COLOR][COLOR=#0000BB]Open[/COLOR][COLOR=#007700](); [/COLOR][COLOR=#FF8000]//open the connection

      
    [/COLOR][COLOR=#0000BB]cmd[/COLOR][COLOR=#007700].[/COLOR][COLOR=#0000BB]CommandText[/COLOR][COLOR=#007700]=[/COLOR][COLOR=#DD0000]"SELECT Address, City, Country, Email," [/COLOR][COLOR=#007700]+
         
    [/COLOR][COLOR=#DD0000]" FirstName, LastName, Message, Phone FROM MyContactsTable"[/COLOR][COLOR=#007700];
      
    [/COLOR][COLOR=#0000BB]cmd[/COLOR][COLOR=#007700].[/COLOR][COLOR=#0000BB]Connection[/COLOR][COLOR=#007700]=[/COLOR][COLOR=#0000BB]this[/COLOR][COLOR=#007700].[/COLOR][COLOR=#0000BB]oleDbConnection1[/COLOR][COLOR=#007700];
      
    [/COLOR][COLOR=#0000BB]reader[/COLOR][COLOR=#007700]=[/COLOR][COLOR=#0000BB]cmd[/COLOR][COLOR=#007700].[/COLOR][COLOR=#0000BB]ExecuteReader[/COLOR][COLOR=#007700]();
     
    [/COLOR][COLOR=#FF8000]//the "using" statement causes the close method to be called internally.

     //if "using" not used, use "writer.Close()" in try-catch-finally explicitly

      
    [/COLOR][COLOR=#0000BB]using [/COLOR][COLOR=#007700]([/COLOR][COLOR=#0000BB]StreamWriter writer [/COLOR][COLOR=#007700]= new [/COLOR][COLOR=#0000BB]StreamWriter[/COLOR][COLOR=#007700]([/COLOR][COLOR=#DD0000]"C:\\MyTextFile.txt"[/COLOR][COLOR=#007700],[/COLOR][COLOR=#0000BB]false[/COLOR][COLOR=#007700]))
      
    {
      [/
    COLOR][COLOR=#FF8000]//false means: textfile is overwritten

      
    [/COLOR][COLOR=#007700]try
      
    {
       while ([/
    COLOR][COLOR=#0000BB]reader[/COLOR][COLOR=#007700].[/COLOR][COLOR=#0000BB]Read[/COLOR][COLOR=#007700]())
       
    {
         [/
    COLOR][COLOR=#0000BB]writer[/COLOR][COLOR=#007700].[/COLOR][COLOR=#0000BB]Write[/COLOR][COLOR=#007700]([/COLOR][COLOR=#0000BB]reader[/COLOR][COLOR=#007700][[/COLOR][COLOR=#DD0000]"LastName"[/COLOR][COLOR=#007700]]);
         
    [/COLOR][COLOR=#0000BB]writer[/COLOR][COLOR=#007700].[/COLOR][COLOR=#0000BB]Write[/COLOR][COLOR=#007700]([/COLOR][COLOR=#DD0000]"#"[/COLOR][COLOR=#007700]); [/COLOR][COLOR=#FF8000]//separator

         
    [/COLOR][COLOR=#0000BB]writer[/COLOR][COLOR=#007700].[/COLOR][COLOR=#0000BB]Write[/COLOR][COLOR=#007700]([/COLOR][COLOR=#0000BB]reader[/COLOR][COLOR=#007700][[/COLOR][COLOR=#DD0000]"FirstName"[/COLOR][COLOR=#007700]]);
         
    [/COLOR][COLOR=#0000BB]writer[/COLOR][COLOR=#007700].[/COLOR][COLOR=#0000BB]Write[/COLOR][COLOR=#007700]([/COLOR][COLOR=#DD0000]"#"[/COLOR][COLOR=#007700]);
         
    [/COLOR][COLOR=#0000BB]writer[/COLOR][COLOR=#007700].[/COLOR][COLOR=#0000BB]Write[/COLOR][COLOR=#007700]([/COLOR][COLOR=#0000BB]reader[/COLOR][COLOR=#007700][[/COLOR][COLOR=#DD0000]"Address"[/COLOR][COLOR=#007700]]);
         
    [/COLOR][COLOR=#0000BB]writer[/COLOR][COLOR=#007700].[/COLOR][COLOR=#0000BB]Write[/COLOR][COLOR=#007700]([/COLOR][COLOR=#DD0000]"#"[/COLOR][COLOR=#007700]);
         
    [/COLOR][COLOR=#0000BB]writer[/COLOR][COLOR=#007700].[/COLOR][COLOR=#0000BB]Write[/COLOR][COLOR=#007700]([/COLOR][COLOR=#0000BB]reader[/COLOR][COLOR=#007700][[/COLOR][COLOR=#DD0000]"City"[/COLOR][COLOR=#007700]]);
         
    [/COLOR][COLOR=#0000BB]writer[/COLOR][COLOR=#007700].[/COLOR][COLOR=#0000BB]Write[/COLOR][COLOR=#007700]([/COLOR][COLOR=#DD0000]"#"[/COLOR][COLOR=#007700]);
         
    [/COLOR][COLOR=#0000BB]writer[/COLOR][COLOR=#007700].[/COLOR][COLOR=#0000BB]Write[/COLOR][COLOR=#007700]([/COLOR][COLOR=#0000BB]reader[/COLOR][COLOR=#007700][[/COLOR][COLOR=#DD0000]"Country"[/COLOR][COLOR=#007700]]);
         
    [/COLOR][COLOR=#0000BB]writer[/COLOR][COLOR=#007700].[/COLOR][COLOR=#0000BB]Write[/COLOR][COLOR=#007700]([/COLOR][COLOR=#DD0000]"#"[/COLOR][COLOR=#007700]);
         
    [/COLOR][COLOR=#0000BB]writer[/COLOR][COLOR=#007700].[/COLOR][COLOR=#0000BB]Write[/COLOR][COLOR=#007700]([/COLOR][COLOR=#0000BB]reader[/COLOR][COLOR=#007700][[/COLOR][COLOR=#DD0000]"Email"[/COLOR][COLOR=#007700]]);
         
    [/COLOR][COLOR=#0000BB]writer[/COLOR][COLOR=#007700].[/COLOR][COLOR=#0000BB]Write[/COLOR][COLOR=#007700]([/COLOR][COLOR=#DD0000]"#"[/COLOR][COLOR=#007700]);
         
    [/COLOR][COLOR=#0000BB]writer[/COLOR][COLOR=#007700].[/COLOR][COLOR=#0000BB]Write[/COLOR][COLOR=#007700]([/COLOR][COLOR=#0000BB]reader[/COLOR][COLOR=#007700][[/COLOR][COLOR=#DD0000]"Message"[/COLOR][COLOR=#007700]]);
         
    [/COLOR][COLOR=#0000BB]writer[/COLOR][COLOR=#007700].[/COLOR][COLOR=#0000BB]Write[/COLOR][COLOR=#007700]([/COLOR][COLOR=#DD0000]"#"[/COLOR][COLOR=#007700]);
         
    [/COLOR][COLOR=#0000BB]writer[/COLOR][COLOR=#007700].[/COLOR][COLOR=#0000BB]Write[/COLOR][COLOR=#007700]([/COLOR][COLOR=#0000BB]reader[/COLOR][COLOR=#007700][[/COLOR][COLOR=#DD0000]"Phone"[/COLOR][COLOR=#007700]]);
         
    [/COLOR][COLOR=#0000BB]writer[/COLOR][COLOR=#007700].[/COLOR][COLOR=#0000BB]WriteLine[/COLOR][COLOR=#007700](); [/COLOR][COLOR=#FF8000]//next new line

       
    [/COLOR][COLOR=#007700]}[/COLOR][COLOR=#FF8000]//while

      
    [/COLOR][COLOR=#007700]}catch ([/COLOR][COLOR=#0000BB]Exception excp[/COLOR][COLOR=#007700])
      
    {
       [/
    COLOR][COLOR=#0000BB]MessageBox[/COLOR][COLOR=#007700].[/COLOR][COLOR=#0000BB]Show[/COLOR][COLOR=#007700]([/COLOR][COLOR=#0000BB]excp[/COLOR][COLOR=#007700].[/COLOR][COLOR=#0000BB]Message[/COLOR][COLOR=#007700]);
      
    }[/COLOR][COLOR=#0000BB]finally [/COLOR][COLOR=#007700]{
       
    [/COLOR][COLOR=#0000BB]reader[/COLOR][COLOR=#007700].[/COLOR][COLOR=#0000BB]Close[/COLOR][COLOR=#007700](); [/COLOR][COLOR=#FF8000]//close the OleDbDataReader

      
    [/COLOR][COLOR=#007700]}[/COLOR][COLOR=#FF8000]//try-catch-finally

     
    [/COLOR][COLOR=#007700]}[/COLOR][COLOR=#FF8000]//using

       
    [/COLOR][COLOR=#0000BB]MessageBox[/COLOR][COLOR=#007700].[/COLOR][COLOR=#0000BB]Show[/COLOR][COLOR=#007700]([/COLOR][COLOR=#DD0000]"Data of table writtten into" [/COLOR][COLOR=#007700]+
         
    [/COLOR][COLOR=#DD0000]" C:\\MyTextFile.txt file"[/COLOR][COLOR=#007700],[/COLOR][COLOR=#DD0000]"Writing completed"[/COLOR][COLOR=#007700]);

    [/
    COLOR] [/COLOR]
    And Finally

    I think the code is quite simple to understand because I tried to make comments to almost every line of code. I hope you can find something useful here for your projects. As ever, all feedback is welcome. Happy coding!

    Theo Kist
     

Share This Page