// 从数据库中查询数据,返回DataTable
DataTable Query(OleDbConnection conn, string sql)
{
OleDbDataAdapter adapter = new OleDbDataAdapter(sql, conn);
DataSet ds = new DataSet();
try
{
adapter.Fill(ds, "factors");
}
catch (Exception ex)
{
_log.Error("GetFactorsInfo() fail: ", ex);
}
return ds.Tables[0];
}
// 将DataTable中的数据显示到DataGridView中
void ShowData(DataTable dt, DataGridview dgv)
{
dgv.Columns.Clear();
if (dt != null)
{
dgv.AutoGenerateColumns = true;
dgv.DataSource = dt;
}
}
SqlConnection con=new SqlConnection("Server=.;database=Test;uid=sa;pwd=sa");
SqlDataAdapter sda=new SqlDataAdapter("Select * from News",con);
Datatable dt=new DataTable();
sda.Fill(dt);
con.Close();
dt为所要的
public static DataTable ExecuteTable(CommandType cmdType, string cmdText, params SqlParameter[] pn)
{
SqlConnection con = new SqlConnection(connectionstring);
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandType = cmdType;
cmd.CommandText = cmdText;
if (pn != null)
{
foreach (SqlParameter p in pn)
{
cmd.Parameters.Add(p);
}
}
SqlDataAdapter sda = new SqlDataAdapter();
sda.SelectCommand = cmd;
DataTable dt=new DataTable();
sda.Fill(ds);
return dt;
}
DataGridView1.DataSource=dt;
DataGridView1.DataBind();
dataset.tables[]