10

I try to put up an if statement to check if a table is already created. I only want to create one table, but as it is now I create a table every time I click the button to store the info. Any suggestions?

    DataTable dt;

    private void InitDataTable()
    {

        if () { 

        }

        dt = new DataTable();
        DataSet ds = new DataSet();
        ds.ReadXml("gjesteInfo.xml");
        ds.Tables.Add(dt);

        DataColumn dc1 = new DataColumn("Fullt navn");
        DataColumn dc2 = new DataColumn("Start dato");
        DataColumn dc3 = new DataColumn("Antall dager");

        dt.Columns.Add(dc1);
        dt.Columns.Add(dc2);
        dt.Columns.Add(dc3);

        dt.Rows.Add(gjestenavnInput.Text, datoInnsjekk.Text, antallDager.Text);

        ds.Merge(dt);

        ds.WriteXml("gjesteInfo.xml");

    }



    private void lagre_Click(object sender, EventArgs e)
    {

        InitDataTable();

        gjesterutenrom.Items.Add(gjestenavnInput.Text);

        gjestenavnInput.Text = "";
        datoInnsjekk.Text = "";
        antallDager.Text = "";

        DataSet onClick = new DataSet();
        onClick.ReadXml("gjesteInfo.xml");
        lagredeGjester.DataSource = onClick.Tables[0];

    }

I try to get out the info stored in the XLM with a DataGridView named lagredeGjester as seen over.

UPDATED QUESTION :

Now I wrote the code like this :

    DataTable dt;

    DataSet ds = new DataSet();

    private void InitDataTable()
    {


         if( ds.Tables.Contains("Gjester")   )
        {
            dt.Rows.Add(gjestenavnInput.Text, datoInnsjekk.Text, antallDager.Text);
            ds.Merge(dt);

            ds.WriteXml("gjesteInfo.xml");

        }
        else {

            dt = new DataTable("Gjester");

            ds.ReadXml("gjesteInfo.xml");
            ds.Tables.Add(dt);

            DataColumn dc1 = new DataColumn("Fullt navn");
            DataColumn dc2 = new DataColumn("Start dato");
            DataColumn dc3 = new DataColumn("Antall dager");

            dt.Columns.Add(dc1);
            dt.Columns.Add(dc2);
            dt.Columns.Add(dc3);

            dt.Rows.Add(gjestenavnInput.Text, datoInnsjekk.Text, antallDager.Text);
            ds.Merge(dt);

            ds.WriteXml("gjesteInfo.xml");

        }

    }

On my first run I entered two different infomations and pressed my button. Both info got in the same table as I wanted it to. But I can't seem to write my if statement correctly. When I run the code above it works with an empty XML (with no tables), but as long as "Gjester" table is created it says "A DataTable named 'Gjester' already belongs to this DataSet." But isn't this what my if statement should prevent? As I wrote it now, should it not just add the info and not try to create a new table?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Praise
  • 557
  • 2
  • 8
  • 23

3 Answers3

15

Can Check via:

if(ds.Tables.Contains("tablename"))

OR

 if(dt.Rows.Count == 0)

OR

int flag=0;
try
{

    if(ds.Tables["tablename"].Rows.Count>0)
    {
      // execute something
    }
}
catch(Exception ex)
{
 flag=1;
}

if(flag==1)
{
  messagebox.show("Table does not exists");
}
Freelancer
  • 9,008
  • 7
  • 42
  • 81
  • I tried you last suggestion, but all I get is "Cannot implicitly convert type System.Data.DataTable to Bool" – Praise Apr 22 '13 at 12:17
  • if(ds.Tables["tablename"]) { // execute something } – Praise Apr 22 '13 at 12:20
  • I just ran it and got "NullReferenceException was unhandled. Object reference not set to an instance of an object." – Praise Apr 22 '13 at 12:26
  • Now I just seem to get Table does not exists. So I set the flag to 1. – Praise Apr 22 '13 at 12:38
  • No. It does not create the info I want to get stored in the XML. Take a look at my edited question. I posted what I did there. – Praise Apr 22 '13 at 12:45
  • voted up for ds.Tables.Contains("tablename") that way we can check for table name instead for the exact table number. – Sijav Jan 18 '15 at 13:29
4

You can also Extend DataSet to add a method FetchOrCreate()

  public static DataTable FetchOrCreate(this DataSet ds, string tableName)
  {
       if (ds.Tables.Contains(tableName)) 
           return ds.Tables[tableName];
       // -------------------------------
       var dt = new Datatable(tableName);
       ds.Tables.Add(dt);
       return dt;          
  }
Charles Bretana
  • 143,358
  • 22
  • 150
  • 216
  • Please explain more, do I put this method inside the function? And then what? – Praise Apr 22 '13 at 14:59
  • No, once you have added the FetchOrCreate extension method somewhere else, in your code instead of storing the datatable dt as a variable, store the Dataset ds, and then where you would initialize the variable ds, use this FetchOrCreate instead.... var myds = ds.FetchorCreate("TableName"). Then the FetchorCreate() method will either return the existing dataset or create a new one for you. – Charles Bretana Mar 12 '21 at 14:53
3

A possible solution would be to define the DataSet out of the function. Then check number of tables in the dataset.

DataSet ds = new DataSet();

private void InitDataTable()
{
    DataTable dt;

    if(ds.Tables.Count > 0 )
    {
        dt = ds.Tables[0];
    }

    dt = new DataTable();

    //your code
}
Hossein Narimani Rad
  • 31,361
  • 18
  • 86
  • 116