Đối tượng data adapter
Thuộc tính:
Phương thức:
5.3.5 Đối tượng DataSet hoặc DataTable
Trên thực tế các đối tượng xử lý trên web form như Grid, DropDownList, ListBox đều yêu cầu dữ liệu được lưu dưới dạng DataTable hoặc DataView, vì vậy việc đọc dữ liệu và từ cơ sở dữ liệu và lưu trên các đối tượng này là tất yếu.
Sau đây là đoạn mã lấy dữ liệu và gán vào một DataSet.
string select = "SELECT * FROM SINH_VIEN";
SqlConnection conn = new SqlConnection(source);
SqlDataAdapter da = new SqlDataAdapter(select, conn);
DataSet ds = new DataSet();
da.Fill(ds, "SINH_VIEN");
GridView.SetDataBinding(ds, "SINH_VIEN");
Ta có thể viết hàm dùng chung như sau:
/*get DataSet*/
public DataSet DocDL_DataSet(string query)
{
if (MoKetNoi())
{
DataSet ds = new DataSet();
SqlDataAdapter command = new SqlDataAdapter(sql, con);
command.Fill(ds, query);
return ds;
}
DongKetNoi();
return null;
}
Hoặc hàm dùng chung lấy dữ liệu vào DataTable
/*get DataTable*/
public DataTable DocDL_DataTable(string query)
{
if (MoKetNoi()){
DataSet ds = new DataSet();
SqlDataAdapter command = new SqlDataAdapter(query, con);
command.Fill(ds, query);
return ds.Tables[query];
}
DongKetNoi();
return null;
}//end getDataTable
Ví dụ sau đây sẽ lấy dữ liệu danh sách lớp đưa vào biến DataTable
DataTable dt = DocDL_DataTable("SELECT * FROM LOP");
» Tin mới nhất:
» Các tin khác: