Click here to Skip to main content
15,888,351 members
Please Sign up or sign in to vote.
1.00/5 (3 votes)
See more:
I want the result "select vmId from tblRate where userId=2" into array form.

What I have tried:

select vmId from tblRate where userId=2
Posted
Updated 2-Aug-17 19:22pm

Rows of DataTable can be accessed as a two dimensional array already (have some indexers for that), like dt.Rows[0]["column1"], so you probably need not convert it, but...
C#
dt.Rows.Cast<DataRow>().Select(r => r.ItemArray).ToArray();
 
Share this answer
 
Like below example you have to try man.
public class ClassName
{
    public string Col1 { get; set; }
    public int Col2 { get; set; }
}
Now you can use a loop to fill a list and ToArray if you really need an array:

ClassName[] allRecords = null;
string sql = @"SELECT col1,col2
               FROM  some table";
using (var command = new SqlCommand(sql, con))
{
    con.Open();
    using (var reader = command.ExecuteReader())
    {
        var list = new List<ClassName>();
        while (reader.Read())
            list.Add(new ClassName { Col1 = reader.GetString(0), Col2 = reader.GetInt32(1) });
        allRecords = list.ToArray();
    }
}
 
Share this answer
 
You need to create Model with same attribute as column name of query result and assign result to that query file executing query.

For Example:

Query:
Select * from Employee

C# Model:
public class Employee{
public Employee_id;
public Employee_Name;
.
.
.
So on...
}

and now assign Employee object to result of query.

Hope it will helpful for you, please don't forget to mark my good rating. :)
 
Share this answer
 
Comments
[no name] 3-Aug-17 2:37am    
My sample Code:

List<employee> emp = new List<employee>();
var ds = new DataSet();
var conn = DACUtil.GetConnection();
try
{
SqlCommand cmd = new SqlCommand("Select * from Employee", conn);
SqlConnection con = cmd.Connection;
con.Open();
using (con)
{
SqlDataReader dr = cmd.ExecuteReader();
if (dr.HasRows)
{
while (dr.Read())
{
Employee et = new Employee();
et.Employee_ID = Convert.ToInt32(dr["Employee_ID"]);
et.Employee_Name = Convert.ToString(dr["Employee_Name"]);
et.Employee_Phone =
Convert.ToString(dr["Employee_Phone"]);
et.Employee_Salary = Convert.ToInt32(dr["Employee_Salary"]);
et.Employee_Designation = Convert.ToString(dr["Employee_Designation"]);
emp.Add(et);
}
}
}

}
catch (Exception ex) {
}

return emp;
}

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900