Aha*_*ves 14 .net c# sql datatable
我目前正在使用Page_Load中的以下代码创建和读取DataTable
protected void Page_Load(object sender, EventArgs e)
{
if (Session["AllFeatures1"] == null)
{
Session["AllFeatures1"] = GetData();
}
table = (DataTable)Session["AllFeatures1"];
DayPilotCalendar1.DataSource = Session["AllFeatures1"];
DayPilotNavigator1.DataSource = Session["AllFeatures1"];
if (!IsPostBack)
{
DataBind();
DayPilotCalendar1.UpdateWithMessage("Welcome!");
}
if (User.Identity.Name != "")
{
Panel1.Visible = true;
}
}
Run Code Online (Sandbox Code Playgroud)
我想知道如何转换此代码,以便从SQL查询中读取?我正在尝试下面的代码,但我不知道如何连接它们,以便我的页面加载数据表填充下面的SQL命令.
SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["BarManConnectionString"].ConnectionString);
conn.Open();
string query = "SELECT * FROM [EventOne]";
SqlCommand cmd = new SqlCommand(query, conn);
DataTable t1 = new DataTable();
using (SqlDataAdapter a = new SqlDataAdapter(cmd))
{
a.Fill(t1);
}
Run Code Online (Sandbox Code Playgroud)
Hen*_*ang 34
这SqlDataReader是一个有效的数据源DataTable.因此,您只需要这样做:
public DataTable GetData()
{
SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["BarManConnectionString"].ConnectionString);
conn.Open();
string query = "SELECT * FROM [EventOne]";
SqlCommand cmd = new SqlCommand(query, conn);
DataTable dt = new DataTable();
dt.Load(cmd.ExecuteReader());
conn.Close();
return dt;
}
Run Code Online (Sandbox Code Playgroud)
您可以创建返回给定sql查询的数据表的方法:
public DataTable GetDataTable()
{
SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["BarManConnectionString"].ConnectionString);
conn.Open();
string query = "SELECT * FROM [EventOne] ";
SqlCommand cmd = new SqlCommand(query, conn);
DataTable t1 = new DataTable();
using (SqlDataAdapter a = new SqlDataAdapter(cmd))
{
a.Fill(t1);
}
return t1;
}
Run Code Online (Sandbox Code Playgroud)
现在可以像这样使用:
table = GetDataTable();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
165168 次 |
| 最近记录: |