Reputation: 13
I Want to fetch 1 record based on the name of the logged in User and show these values in txt boxes (c#) I am a bit stuck on how to handle this, any help would be welcome.
Currently I am trying to fetch it using LINQ:
DAL.VindjekindjeDataContext dc = new DAL.VindjekindjeDataContext();
public object GetCompleteOuder(string p)
{
//var query = (from TOUD in dc.TOUDs where TOUD.Ouderid == p select TOUD).Single();
return (from TOUD in dc.TOUDs where TOUD.Voornaam.Equals(p) select TOUD ).First();
}
protected void Page_Load(object sender, EventArgs e)
{
string naam = User.Identity.Name;
object parent = new object();
parent = Ouder.GetCompleteOuder(naam);
Type typB = parent.GetType();
NaamTxt.Text = (string)typB.GetField("Naam").GetValue(parent);
}
However I get the following error:
System.NullReferenceException: Object reference not set to an instance of an object.
Upvotes: 0
Views: 51
Reputation: 13
Final working code:
DAL.VindjekindjeDataContext dc = new DAL.VindjekindjeDataContext();
public bool GetCompleteOuder(out DAL.TOUD user, string p)
{
user = new DAL.TOUD();
try
{
dc.TOUDs.SingleOrDefault(t => t.Voornaam == p);
user = (from TOUD in dc.TOUDs where TOUD.Voornaam.Equals(p) select TOUD).Single();
return true;
}
catch
{
return false;
}
}
//page load behind aspx page
OuderDAL Ouder = new OuderDAL();
protected void Page_Load(object sender, EventArgs e)
{
string naam = User.Identity.Name;
DAL.TOUD user;
if(Ouder.GetCompleteOuder(out user, naam))
{
/*vullen van de velden met de gegevens voor de ingelogde gebruiker*/
NaamTxt.Text = user.Naam;
Upvotes: 0
Reputation: 7176
Perhaps something like this
public bool GetCompleteOuder(out TOUD user, string p)
{
user = new TOUD();
try
{
db.TOUDS.SingleOrDefault(t => t.Voornaam == p);
return true;
}
catch
{
return false;
}
}
protected void Page_Load(object sender, EventArgs e)
{
string naam = User.Identity.Name;
TOUD user;
if(GetCompleteOuder(out user, naam))
{
NaamTxt.Text = user.<fieldname>;
}
else
{
NaamTxt.Text = string.empty;
}
}
Upvotes: 0
Reputation: 156948
There is just too much going wrong here.
null
value for Voornaam
)parent
which is useless since you overwrite it the next line.parent
variable should be strongly typed. That will prevent you to need reflection to get the Naam
property. This, by the way, is another possible source for your NullReferenceException
.Upvotes: 1