How can I put the values of database in array in ASP.NET MVC C# ?
If I am getting it right you are trying to create a List of the same data-type, after fetching data from database, you can try this
First, create a class of data-type which you want, example
public class Student
{
public int ID { get; set; }
public string Name { get; set; }
public DateTime DateOfBirth { get; set; }
}
then get data from the database and save it in a List
of Student type
List<Student> student = new List<Student>();
SqlConnection conn = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=Student.mdf;Integrated Security=True;User Instance=True");
SqlCommand cmd = new SqlCommand("select * from Student", conn);
SqlDataReader dr;
try
{
conn.Open();
dr = cmd.ExecuteReader();
while (dr.Read())
{
student.Add(new Student()
{
ID = dr.GetInt32(dr.GetOrdinal("ID")),
Name = dr.GetString(dr.GetOrdinal("Name")),
DateOfBirth = dr.GetDateTime(dr.GetOrdinal("DateOfBirth"))
});
}
dr.Close();
}
catch (Exception exp)
{
throw;
}
finally
{
conn.Close();
}
That's it, let me know if this helps you
Subscribe to our weekly Newsletter & Keep getting latest article/questions in your inbox weekly