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,530
  • 3
  • 39
  • 44
Theofanis Pantelides
  • 4,556
  • 7
  • 27
  • 49

4 Answers4

7

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

LukeH
  • 252,910
  • 55
  • 358
  • 405
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,530
  • 3
  • 39
  • 44
il_guru
  • 8,043
  • 2
  • 41
  • 50
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,041
  • 2
  • 32
  • 46
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,530
  • 3
  • 39
  • 44