开发者

Method returning DataTable with using

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()?


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


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
}


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


    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);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜