views:

319

answers:

1

I want my LINQ query to count the number of instances a member is present in a table based on what the user enters into a textbox.

As a result, I have the following

protected void btnSubmit_Click(object sender, EventArgs e)
{
    LoginDataContext lg = new LoginDataContext();

    int logincheck = (from r in lg.tblOnlineReportingLogins
                      where r.MemberID == tbxMember.Text.ToString()
                      select r).Count();

When I debug this, the value appears as 0 when I know this is not the case.

Can someone point out where I am going wrong?

+3  A: 

I suppose the MemberId property is an integer. So you cannot compare it against a string value. Text.ToString() is redundant anyway, since Text is already a string.

where r.MemberId.ToString() == tbxMember.Text

should work.

A cleaner solution would be to parse the Text property into an int value (together with some validity checking) and do the comparison using ints, like

int targetId;
if (Int32.TryParse(tbxMember.Text, out targetId)) {
    int logincheck = (from r in lg.tblOnlineReportingLogins
                  where r.MemberID == tbxMember.Text.ToString()
                  select r).Count();
    // ...
} else {
    MessageBox.ShowMessage("Invalid Id");
}

EDIT: Sorry, perhaps I was too quick, I assumed MemberId was an integer. But in this case, your code shouldn't even have compiled. I'm just wondering about the upvotes :-) ...

MartinStettner
The latter should be more efficient.
Jagd
That has worked a treat - potentially the MemberID may also be a string however... (Lots of up votes up for grabs : D ) eg. member ID = MM12345 or simply just 123
Ricardo Deano
i.e. the type is nvarcharPS: I really appreciate the help, I'm feeling so dense at the moment. I know what I want to do, I just don't know how to go about doing it.
Ricardo Deano
I would do the following: what gives `lg.tblOnlineReportingLogings.Count()`, what can you see with `from r in lg.tblOnlineReportingLogins select (r => MessageBox.ShowMessage("'"+r.MemberId+"'='"+tbxMember.Text))` and so on (supposing, you've got an winforms app. If not, verify the contents of the table *as seen by your application* in some ASP.NET output or some log file)
MartinStettner
Ok cool - yeah I'll take it one step at a time. Thanks for the advice.
Ricardo Deano