阅读本文档后,我觉得以下代码可以工作:
using (SqlConnection con = new SqlConnection(Properties.Settings.Default.C_Str))
{
try
{
using (SqlCommand cmd = new SqlCommand("PerformSearch", con))
{
cmd.CommandType = CommandType.StoredProcedure;
string SearchString = textBoxSearchSting.Text;
cmd.Parameters.Add("SearchString", SqlDbType.VarChar).Value = SearchString;
con.Open();
dataGridView1.DataSource = cmd.ExecuteReader(CommandBehavior.CloseConnection);
}
}
catch (Exception) { throw; }
finally { con.Close(); }
}
或者我至少可以使用以下内容:
using (SqlConnection con = new SqlConnection(Properties.Settings.Default.C_Str))
{
try
{
using (SqlCommand cmd = new SqlCommand("PerformSearch", con))
{
cmd.CommandType = CommandType.StoredProcedure;
string SearchString = textBoxSearchSting.Text;
cmd.Parameters.Add("SearchString", SqlDbType.VarChar).Value = SearchString;
con.Open();
SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
dataGridView1.DataSource = reader;
}
}
catch (Exception) { throw; }
finally { con.Close(); }
}
但上述工作都没有。使用下面的代码确实有效,具有相同的搜索值,下面是用我的查询填充我的 datagridview 的最佳方法吗?为什么上述任何一个都不起作用?
using (SqlConnection con = new SqlConnection(Properties.Settings.Default.C_Str))
{
try
{
using (SqlCommand cmd = new SqlCommand("PerformSearch", con))
{
cmd.CommandType = CommandType.StoredProcedure;
string SearchString = textBoxSearchSting.Text;
cmd.Parameters.Add("SearchString", SqlDbType.VarChar).Value = SearchString;
con.Open();
DataTable dt = new DataTable();
dt.Load(cmd.ExecuteReader(CommandBehavior.CloseConnection));
if (dt.Rows.Count > 0 && dt != null)
{
dataGridView1.DataSource = dt;
}
}
}
catch (Exception) { throw; }
finally { con.Close(); }
}
下面也可以,出于任何原因,我会更好地使用数据适配器吗?
using (SqlConnection con = new SqlConnection(Properties.Settings.Default.C_Str))
{
try
{
using (SqlCommand cmd = new SqlCommand("PerformSearch", con))
{
cmd.CommandType = CommandType.StoredProcedure;
string SearchString = textBoxSearchSting.Text;
cmd.Parameters.Add("SearchString", SqlDbType.VarChar).Value = SearchString;
DataTable dt = new DataTable();
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
con.Open();
da.Fill(dt);
if (dt.Rows.Count > 0 && dt != null)
{
dataGridView1.DataSource = dt;
}
}
}
}
catch (Exception) { throw; }
finally { con.Close(); }
}