Jonathan
Jonathan

Reputation: 651

Assign variables from data table results

I have a query like:

 var table = db.GetTableBySQL($"EXEC usp_User_OldPassword_Check  @UserName = '{txtUserName.Text}'");

it returns two values into datatable. So I want to assign that values into two variables so I do:

 bool isOldPassword = false;
 var currentEmpGuid = string.Empty;

then:

 var test = (from DataRow dr in table.Rows
                        select new
                        {
                            isOldPassword = (bool)dr["IsOldPassword"],
                            CurrentEmpGuid = (Guid)dr["EmpGuid"]
                        });

Data comes correctly in table.Rows but values are not assigned to my variables. Any one seeing anything wrong? Regards

Upvotes: 0

Views: 70

Answers (1)

Josh Part
Josh Part

Reputation: 2164

This:

 var test = (from DataRow dr in table.Rows
             select new
             {
                  isOldPassword = (bool)dr["IsOldPassword"],
                  CurrentEmpGuid = (Guid)dr["EmpGuid"]
             });

Creates a collection of anonymous objects, one for each row of your datatable, each one containing 2 properties: isOldPassword and CurrentEmpGuid. So if you do for example test.First.CurrentEmpGuid or test.First.IsOldPassword you'll be accesing the values from your datatable.

But you don't need LINQ for what you want to do; you can just simply do:

isOldPassword = (bool)table.Rows[0]["IsOldPassword"],
CurrentEmpGuid = (Guid)table.Rows[0]["EmpGuid"]

to assign your variables the values of the first row of your datatable.

This is of course assuming your query always returns one row...

Upvotes: 1

Related Questions