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];
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;
}
You can make method which return the datatable of given sql query:
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;
}
and now can be used like this:
table = GetDataTable();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With