考虑以下示例:
public static DataTable GetDataTable()
{
using(DataTable dt = new DataTable())
{
// fill DataTable logic
return dt;
}
}
public void main()
{
DataTable dt = GetDataTable();
// contine using dt
}
我应该期望dt
可以使用main()
,还是DataTable
处理GetDataTable()
?
答案 0 :(得分:7)
是的,DataTable
阻止using
阻止GetDataTable
。
答案 1 :(得分:5)
是的,当代码退出using范围时,DataTable
将被处理。
您应该将using
移至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
}
答案 2 :(得分:2)
你必须替换
public void main()
到
public static void Main()
public static DataTable GetDataTable()
{
using(DataTable dt = new DataTable())
{
// fill DataTable logic
return dt;
}
}
一旦您的代码离开,GetDataTable
dt
将被处理掉。因为using
调用IDisposible
答案 3 :(得分: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;
}
}
在文本框中搜索,然后获得结果! :)快乐C#Codding
dataGridView1.DataSource = GetValue(textBox1.Text);