Linq 2 SQL - Manual Databinding not working - asp.net

I'm using linq2sql in my asp.net app. When using it with linq2sqldatasource object everything works, i mean i bind it without no code to a detailsview control.
My idea is when i click a row in the detailscontrol e will load/add to the same page a customwebcontrol that will permit edit the data.
For that i need to load some items to fill the dropdowns in that customcontrol, and in its load event i have the follwoing code that doesn't work and i can't see why. It raises a object null reference exception.
example:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
//loads combobox with organizations
using (MyDataContext cdc = new MyDataContext())
{
var queryOrgs = from p in cdc.orgUnits
select p;
//Organizations
dropDownOrgs.DataSource = queryOrgs.ToList();
dropDownOrgs.DataValueField = "orgUnitID";
dropDownOrgs.DataTextField = "orgUnitName";
dropDownOrgs.DataBind();
}
}
}
Anyone know what is happenning? Looks like when i want to bind all by myself manually something do not work :(
Hope you can help me.
Thanks.
Teixeira

#Chalkey is correct. I have run into this error myself, where due to the fact that LINQ to SQL does "lazy" querying, it waits till the last minute to actually perform the query.
This means that it may wait until after the page_load function to do the query (and therefore outside of the using statement).
Therefore, return the data as a list with .ToList() to force it to run the query immediately.
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
//loads combobox with organizations
using (MyDataContext cdc = new MyDataContext())
{
List<orgUnit> queryOrgs = (
from p in cdc.orgUnits
select p
).ToList();
//Organizations
dropDownOrgs.DataSource = queryOrgs.ToList();
dropDownOrgs.DataValueField = "orgUnitID";
dropDownOrgs.DataTextField = "orgUnitName";
dropDownOrgs.DataBind();
}
}
}

Related

How is this explained with ASP.NET page life cycle?

I have the following code, which simply inserts a record into the database, based on some text fields and a dropdown. The dropdown gets bound in the Page Load Event.
protected void btnAdd_Click(object sender, EventArgs e)
{
try
{
Personeel p = new Personeel();
p.achternaam = txtNaam.Text;
p.naam = txtVoornaam.Text;
p.fk_afdeling_id = Convert.ToInt16(cmbAfdeling.SelectedValue);
BLLpersoneel BLLp = new BLLpersoneel();
BLLp.insert(p);
lblFeedback.Text = "Done and done!";
rptPersoneel.DataBind();
}
catch (Exception err)
{
lblFeedback.Text = err.Message;
}
}
protected void Page_Load(object sender, EventArgs e)
{
if(Page.IsPostBack == false)
{
BLLafdeling BLLa = new BLLafdeling();
cmbAfdeling.DataSource = BLLa.selectAll();
cmbAfdeling.DataTextField = "naam";
cmbAfdeling.DataValueField = "afdeling_id";
cmbAfdeling.DataBind();
}
}
My question is about IsPostBack.
On first load, the page has no PostBack, so it will bind the data to the dropdown "cmbAfdeling".
Then, when submitting the form, there IS a postback, so we don't reach the code inside the if statement. To me, that would mean that ASP.NET would NOT bind the data to the combo box.
However, the data is still there after submitting (and thus having a postback).
How is this explained?
This is due to the ViewState. The data in the ComboBox is stored in the ViewState and is sent back & forth during postback.
This might be worth reading to understand what is happening: http://msdn.microsoft.com/en-us/library/ms972976.aspx
It's explained by a concept called viewstate:
If you examine the code produced by your asp, you will find some hidden fields, one of which is the "viewstate". The viewstate saves the important values of your asp in order to be able to populate the elements every time the pages gets loaded, even if it's after a postback.
The data is maintained during postback, as you don't clear the data during postback or on load it will persist.

How can I retrieve a subset of data from entity object data source and pass to another page

I am playing about just now trying to teach myself a little bit about the entity framework.
I have a Gridview data bound to a Entity Date Source using the Entity Framework. If I select certain items in that list I then wish to redirect another page and populate another gridview with just the items selected (but with more detail, different includes/navigation properties)
This is probably the most simple thing but I have spent 2 hours banging my head on the wall trying to get this to work.
Essentially I have a continue button which when clicked should identify all the UIDs (a column in the gridview) of the rows and allow me to subset to just these rows and pass them to another page to be rebound to another datagrid
Any ideas???
Well, the big picture is that you should get those IDs, pass them to the other page, and then use a query with Contains; see this question for an idea of how to use it:
How search LINQ with many parametrs in one column?
Assuming you haven't used DataKeys in your GridView, this would be my approach.
Page 1
protected void Button1_Click(object sender, EventArgs e)
{
var checkedItems = new List<int>();
foreach (GridViewRow row in GridView1.Rows)
{
var checkbox = (CheckBox)row.FindControl("CheckBox1");
if (checkbox.Checked)
{
checkedItems.Add(int.Parse(row.Cells[1].Text));
}
}
Session["checkedItems"] = checkedItems;
Response.Redirect("Page2.aspx");
}
Page 2
protected void Page_Load(object sender, EventArgs e)
{
var checkedItems = (List<int>)Session["checkedItems"];
Session["checkedItems"] = null;
foreach (var checkedItem in checkedItems)
{
Response.Write(checkedItem);
}
}
Using the IDs in the checkedItems List you can now query those from you DB and finally assign the Result to your GridView on the second page.
Instead of using Session you could pass the IDs via QueryString.

how to get value of hidden field value?

I have an asp.net application in which i want to get the value of hidden field value in to my code behind page.
Actually its executing code first and after that its executing javascript.
That's why i am not getting the value. Please tell me how can i get the value.
Javascript
function changeCSS(colr,wd)
{
chooseStyle(colr, wd)
var CssTitle = document.getElementById('<%= hdCssTitle.ClientID %>');
CssTitle.value = colr;
}
and code behind page is
protected void Page_Load(object sender, EventArgs e)
{
string CssTitle = hdCssTitle.Value;
}
Values changed in Javascript won't be reflected in your server side script. You would have to make an Ajax post to your code-behind to obtain it.
Get hidden field and access that value like this string s = hidden.Text

Count Number of Visitors in WebSite using ASP.Net and C#

I want to keep track of the number of visitors to my site.
I tried the following code in the Global.asax class,
<script runat="server">
public static int count = 0;
void Application_Start(object sender, EventArgs e)
{
Application["myCount"] = count;
}
void Session_Start(object sender, EventArgs e)
{
count = Convert.ToInt32(Application["myCount"]);
Application["myCount"] = count + 1;
}
</script>
I am retrieving the value in the aspx page as follows:
protected void Page_Load(object sender, EventArgs e)
{
int a;
a = Convert.ToInt32((Application["myCount"]));
Label4.Text = Convert.ToString(a);
if (a < 10)
Label4.Text = "000" + Label4.Text ;
else if(a<100)
Label4.Text = "00" + Label4.Text;
else if(a<1000)
Label4.Text = "0" + Label4.Text;
}
The above coding works fine. It generates the Visitors properly but the problem is when I restart my system, the count variable again starts from 0 which logically wrong.
I want the value of count to be incremented by 1 from the last count value.
So can anyone tell me how to accomplish this task?
Please help me out!
Thanks in advance!
If you want the count to keep incrementing over application restarts, you'll need to store the value somewhere - in a database or a file somewhere, and load that value up when the application starts.
Also, you can use the following to ensure your displayed count is always at least 4 characters:
int a;
a = Convert.ToInt32(Application["myCount"]);
Label4.Text = a.ToString("0000");
See Custom Numeric Format Strings for more info.
Edit to respond to comment
Personally, I'd recommend using a database over writing to the file system, for at least the following reasons:
Depending on your host, setting up a database may well be a lot easier than enabling write access to your file system.
Using a database will allow you to store it as an int rather than a string.
Under heavy traffic, you'll have issues with multiple threads trying to open a text file for write access - which will cause a lock on the file, and cause a bottle neck you don't need.
Various resources will tell you how to connect to a database from your code, a good place to start would be this How To: Connect to SQL Server, and looking into the methods under "What are the alternatives" for details on how to query and update the database.
C# code is show below:
protected void Page_Load(object sender, EventArgs e)
{
this.countMe();
enter code here
DataSet tmpDs = new DataSet();
tmpDs.ReadXml(Server.MapPath("~/counter.xml"));
lblCounter.Text = tmpDs.Tables[0].Rows[0]["hits"].ToString();
}
private void countMe()
{
DataSet tmpDs = new DataSet();
tmpDs.ReadXml(Server.MapPath("~/counter.xml"));
int hits = Int32.Parse(tmpDs.Tables[0].Rows[0]["hits"].ToString());
hits += 1;
tmpDs.Tables[0].Rows[0]["hits"] = hits.ToString();
tmpDs.WriteXml(Server.MapPath("~/counter.xml"));
}
Then you need to have an xml file in the root directory to make the code work as well. The XML file will look like this:
<?xml version="1.0" encoding="utf-8" ?>
<counter>
<count>
<hits>0</hits>
</count>
</counter>
In First Answer U had declare count variable globally,that's why in every new session count starts with 0.for better result ,increment application[] variable inside session_start method.
Usually you use other Tools for that Task (weblog analyser).
As you store your value in Memory (Application["myCount"]) this value will not survive a server restart. So you have to store it in a
database
plain textfile
whatever

javascript timer

I am developing an online exam application using asp.net. In the start exam page I have created a javascript countdown timer.
How can I move to the next page automatically after the timer reaches 00?
Here is my code:
long timerStartValue = 1000 ;
private int TimerInterval
{
get
{
int o =(int) ViewState["timerInterval"];
if(o==0)
{
return (o);
}
return 50 ;
}
set
{
ViewState["timerInterval"] = value;
}
}
protected void Page_PreInit(object sender,EventArgs e)
{
string timerVal = Request.Form["timerData"];
if(! String.IsNullOrEmpty(timerVal))
{
timerVal = timerVal.Replace(",", String.Empty) ;
this.timerStartValue = long.Parse(timerVal);
}
}
protected void Page_Load(object sender, EventArgs e)
{
if(! IsPostBack)
{
this.timerStartValue = 10000; //3599000;//14400000;
this.TimerInterval = 500;
}
}
protected void Button1_Click(object sender, EventArgs e)
{
this.timerStartValue = 3599000;
}
protected void Page_PreRender(object sender, EventArgs e)
{
System.Text.StringBuilder bldr=new System.Text.StringBuilder();
bldr.AppendFormat("var Timer = new myTimer({0},{1},'{2}','timerData');", this.timerStartValue, this.TimerInterval, this.lblTimerCount.ClientID);
bldr.Append("Timer.go()");
ClientScript.RegisterStartupScript(this.GetType(), "TimerScript", bldr.ToString(), true);
ClientScript.RegisterHiddenField("timerData", timerStartValue.ToString());
}
Thanks in advance,
sangita
It sounds like when you click the "Next" button, you are loading an entirely new page. This of course changes all the content and resets all the javascript. You can't maintain state across pages without a bit of work.
The solution to this could be to save the timer state when the next button is pressed, and pass it to the next stage. You could do this by saving the timer state to a hidden form input and submitting it along with the Next button.
The other option would be to load your questions via AJAX. Instead of moving to a new page every time the next button is clicked, you could simply replace the question portion of the page with a new question, and leave the timer intact. This is probably the solution I would use.
Are u reloading the entire page when clicking on the next button ? That may leads to realod the java script file also.So the variable values will reset.May be you can think about showing the questions /answers via Ajax.You need not reload the entire page when showing the next question.the part when you show the quiz will only be updated.so you can maintain the global variables in your java script too. Check the below link to know about partial page updating using jQuery.
http://www.west-wind.com/presentations/jquery/jquerypart2.aspx
Hope this helps.
You can put the timer in an iframe if you can't get rid of the postback.
You need a way to persist information between pages, and there's really only one possibility: To make it part of the next page request.
Now, this could be subdivided into 2 categories:
1) As part of the url: http://www.example.com/page?timer=123;
2) As part of the headers;
And number 2 opens new possibilities:
a) As part of POST data;
b) As a client-side cookie only;
c) As a cookie tied to information on the server;
Number 1, 2a and 2b can be manipulated by the user. So what you can do is store some value in a cookie, a hash for example or a database row ID, that you'll use to fetch information on the server.
tl;dr? Use a asp "Session object". It lets you keep things on the server-side and users will have no idea what they are.

Resources