3

Consider the following example:

public static DataTable GetDataTable()
{
    using(DataTable dt = new DataTable())
    {
        // fill DataTable logic
        return dt;
    }
}

public void main()
{
    DataTable dt = GetDataTable();

    // contine using dt
}

Should I expect dt to be usable in main(), or was the DataTable disposed of in GetDataTable()?

Juan
  • 4,910
  • 3
  • 37
  • 46
Theofanis Pantelides
  • 4,724
  • 7
  • 29
  • 49

4 Answers4

7

Yes, the DataTable will have been disposed when leaving the using block in GetDataTable.

LukeH
  • 263,068
  • 57
  • 365
  • 409
5

Yes, the DataTable will be disposed when the code exit the using scope.

You should move the using to your main()

public static DataTable GetDataTable()
{
    DataTable dt = new DataTable()

    // fill DataTable logic
    return dt;
}

public void main()
{
  using(DataTable dt = GetDataTable())
  {
  // contine using dt
  }//here the table is disposed
}
Juan
  • 4,910
  • 3
  • 37
  • 46
il_guru
  • 8,383
  • 2
  • 42
  • 51
2

you have to replace

public  void main()

to

public static void Main()

public static DataTable GetDataTable()
{
  using(DataTable dt = new DataTable())
  {
    // fill DataTable logic
    return dt;
  }
}

once your code leave GetDataTable dt will be disposed. Because using calls IDisposible

anishMarokey
  • 11,279
  • 2
  • 34
  • 47
0
    public DataTable GetValue(string name)
    {
        string connection = @"Data Source=DESKTOP-M5TQV9A;Initial Catalog=ALLTEST;Integrated Security=True";
        DataTable dt;
        SqlConnection con = new SqlConnection(connection);
        con.Open();
        using (SqlCommand cmd = new SqlCommand("up_searchUsers", con))
        {
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.Add("@SearchName", SqlDbType.VarChar).Value = name;
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            dt = new DataTable();
            da.Fill(dt);
            con.Close();
            return dt;
        }
    }

search in the textbox then get your results! :) Happy C# Codding

dataGridView1.DataSource = GetValue(textBox1.Text);
Juan
  • 4,910
  • 3
  • 37
  • 46