Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I am currently creating and reading a DataTable with the following code in my Page_Load

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;
    }
}

I would like to know how to convert this code so that it reads from a SQL query? I am experimenting with the code below but I'm not sure how to connect them so that datatable in my page load fills with the SQL command below.

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

I am stuck at:

table = (DataTable)Session["AllFeatures1"]; 

I would like it to be t1 = (DataTable)Session["AllFeatures1];

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
212 views
Welcome To Ask or Share your Answers For Others

1 Answer

The SqlDataReader is a valid data source for the DataTable. As such, all you need to do its this:

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;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...