Reputation: 453
My Class Student:
public class student
{
public int StudentID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["conStr"].ConnectionString);
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "Select * From Student";
cmd.Connection = con;
DataTable datatable = new DataTable();
con.Open();
SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(cmd);
sqlDataAdapter.Fill(datatable);
con.Close();
sqlDataAdapter.Dispose();
foreach (DataRow dr in datatable.Rows)
{
//Set Data: ex: student[] students=new student[];
//students=new students{StudentID=dr["ID"],FirstName=dr["FirstName"]}
// ...
}
namespace WebApi2.myapi
{
public class StudentController : ApiController
{
student[] students = new student[]
{
new student { StudentID = 1, FirstName = "Jishan", LastName = "Siddique" },
new student { StudentID = 2, FirstName = "Bharat", LastName = "Darji" },
new student { StudentID = 3, FirstName = "Ravi", LastName = "Mori" },
new student { StudentID = 4, FirstName = "Jay", LastName = "Singh" }
};
public IEnumerable<student> GetStudents()
{
return students;
}
}
}
Finally: I would like 1 result like: student.StudentID = dr ["ID"]; student.FirstName = dr ["FirstName"]
Thank you all watch. Sorry for my bad english.
I'm searched result to google but not found
Upvotes: 3
Views: 588
Reputation: 38209
You can do it by getting value from the DataRow
:
List<student> students = new List<student>();
foreach (DataRow dataRow in datatable.Rows)
{
students.Add(new student(){
StudentID =dataRow["StudentID"];
FirstName = dataRow["FirstName"] ;
LastName = dataRow["LastName"] ;
})
}
So, students
collection will have all your students.
Upvotes: 3