How to set data from SQL Server in C#.
My Class Student:
public class student
{
public int StudentID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
And I want to Set Data From SQL
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"]}
// ...
}
And My Code Set Data
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
text. Also, what is your question here. "Help me", isn't a question. Have a look at How do I ask a good question? and edit your question to help us help you.Studentand populate it in a loop (but in that case, you might want to use the more lightweight DataReader than a DataSet).