MỘT SỐ ĐOẠN CODE THAM KHẢO
1. Hàm hiển thị dữ liệu trên GridView (ví dụ grvUser)
private void ListUsers()
{
String connStr;
String strSQL;
SqlConnection myConnection;
SqlCommand myCommand;
SqlDataAdapter myAdapter;
DataTable myTable = new DataTable();
//Mở kết nối
connStr = "Server = ; Initial Catalog = ; User Id = ; Password = ";
myConnection = new SqlConnection(connStr);
myConnection.Open();
//Câu lệnh SQL
strSQL = "Select Id,Username,Fullname,Password,Sex,Email From [User]";
//Lấy Dữ liệu
myCommand = new SqlCommand(strSQL, myConnection);
myAdapter = new SqlDataAdapter();
myAdapter.SelectCommand = myCommand;
myAdapter.Fill(myTable);
myConnection.Close();
}
grvUser.DataSource = myTable;
grvUser.DataBind();
2. Thực thi một câu lệnh SQL
String connStr;
String strSQL;
SqlConnection connection;
SqlCommand cmd;
connStr = "Server = ; Initial Catalog = ; User Id = ; Password = ";
connection = new SqlConnection(connStr);
connection.Open();
// Câu lệnh SQL: Insert/Update/Delete
strSQL = " ";
cmd = new SqlCommand(strSQL, connection);
cmd.ExecuteNonQuery();
connection.Close();
3. Code trang UserAdmin.aspx
using
using
using
using
System;
System.Collections.Generic;
System.Linq;
System.Web;
using
using
using
using
System.Web.UI;
System.Web.UI.WebControls;
System.Data.SqlClient;
System.Data;
namespace Student1.Admin
{
public partial class UserAdmin : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack) ListUsers();
}
private void ListUsers()
{
String connStr;
String strSQL;
SqlConnection myConnection;
SqlDataAdapter myAdapter;
DataTable myTable = new DataTable();
//Mở kết nối
connStr = "Server = TRUONG-PC\\SQLEXPRESS; Initial Catalog = TESTDATA; User Id =
truongxuan; Password = 123456";
myConnection = new SqlConnection(connStr);
myConnection.Open();
//Câu lệnh SQL
strSQL = "Select Id,Username,Fullname,Password,Sex,Email From [User]";
//Lấy Dữ liệu
myAdapter = new SqlDataAdapter(strSQL, connStr);
myAdapter.Fill(myTable);
myConnection.Close();
grvUser.DataSource = myTable;
grvUser.DataBind();
}
public string str_bool(object obj)
{
bool b = bool.Parse(obj.ToString());
if (b)
return "Nam";
else
return "Nữ";
}
protected void grvUser_RowEditing(object sender, GridViewEditEventArgs e)
{
grvUser.EditIndex = e.NewEditIndex;
ListUsers();
}
protected void grvUser_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
grvUser.EditIndex = -1;
ListUsers();
}
protected void grvUser_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
//Lấy id của dòng cần sửa
int id = int.Parse(grvUser.DataKeys[e.RowIndex].Value.ToString());
//Cells[vitri]: Đây là vị trí của cột đánh số thứ tự 0 – n
//Controls[vitri]: Xét trong Cells xử lý control thứ bao nhiêu cũng đánh số từ 0 – n,
ở đây trong mỗi field đều có 1 control nên đánh số là 0.
string sUsername = ((TextBox)grvUser.Rows[e.RowIndex].Cells[1].Controls[0]).Text;
string sFullname = ((TextBox)grvUser.Rows[e.RowIndex].Cells[2].Controls[0]).Text;
string sSex =
((DropDownList)grvUser.Rows[e.RowIndex].FindControl("ddlSex")).SelectedValue;
string sEmail = (grvUser.Rows[e.RowIndex].Cells[4].Controls[0] as TextBox).Text;
//Thực thi lệnh Sửa
String connStr;
String strSQL;
SqlConnection connection;
SqlCommand cmd;
connStr = "Server = TRUONG-PC\\SQLEXPRESS; Initial Catalog = TESTDATA; User Id =
truongxuan; Password = 123456";
connection = new SqlConnection(connStr);
connection.Open();
strSQL = "Update [User] Set Username = '" + sUsername + "', Fullname = N'" +
sFullname + "', Sex = " + sSex + ", Email = '" + sEmail + "' Where Id = " + id.ToString();
cmd = new SqlCommand(strSQL, connection);
cmd.ExecuteNonQuery();
connection.Close();
//gvSinhVien.EditIndex = -1: Thoát khỏi tình trạng Edit.
grvUser.EditIndex = -1;
//Nạp lại dữ liệu
ListUsers();
}
protected void grvUser_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
//Lấy id của dòng cần xóa
int id = int.Parse(grvUser.DataKeys[e.RowIndex].Value.ToString());
//Thực thi lệnh Xóa
String connStr;
String strSQL;
SqlConnection connection;
SqlCommand cmd;
connStr = "Server = TRUONG-PC\\SQLEXPRESS; Initial Catalog = TESTDATA; User Id =
truongxuan; Password = 123456";
connection = new SqlConnection(connStr);
connection.Open();
// Câu lệnh SQL: Insert/Update/Delete
strSQL = "Delete From [User] Where Id = " + id.ToString();
cmd = new SqlCommand(strSQL, connection);
cmd.ExecuteNonQuery();
connection.Close();
}
//Nạp lại dữ liệu
ListUsers();
protected void grvUser_SelectedIndexChanging(object sender, GridViewSelectEventArgs e)
{
int id = int.Parse(grvUser.DataKeys[e.NewSelectedIndex].Value.ToString());
Response.Redirect("UserDetail.aspx?id=" + id.ToString());
}
index 2
protected void grvUser_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow && grvUser.EditIndex == -1)
{
//There are 3 buttons and the second one is Delete button, that's why we use the
//indexing goes as 0 is button #1, 1 Literal (Space between buttons), 2 button
#2, 3 Literal (Space) etc.
((LinkButton)e.Row.Cells[5].Controls[2]).OnClientClick = "return confirm('Do you
really want to delete?');";
}
}
protected void btnAdd_Click(object sender, EventArgs e)
{
Response.Redirect("UserAdd.aspx");
}
}
}
4. Code trang UserDetail.aspx
using System;
using System.Data.SqlClient;
using System.Data;
namespace Student.Admin
{
public partial class UserDetail : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//Bắt id trên URL
int id = int.Parse(Request.QueryString["id"].ToString());
//Câu lệnh JavaScript để đưa kiểm tra id vừa lấy, không cần thiết phải có dòng này.
System.Web.HttpContext.Current.Response.Write("LANGUAGE=\"JavaScript\">alert(\"Đã bắt được Id = " + id.ToString() + "\")</SCRIPT>");
String connStr;
String strSQL;
SqlConnection myConnection;
SqlDataAdapter myAdapter;
DataTable myTable = new DataTable();
//Mở kết nối
connStr = "Server = TRUONG-PC\\SQLEXPRESS; Initial Catalog = TESTDATA; User Id =
truongxuan; Password = 123456";
myConnection = new SqlConnection(connStr);
myConnection.Open();
//Câu lệnh SQL
strSQL = "Select Username,Fullname,Sex,Email From [User] Where Id = " +
id.ToString();
//Lấy Dữ liệu
myAdapter = new SqlDataAdapter(strSQL, connStr);
myAdapter.Fill(myTable);
}
}
}
lbUsername.Text = myTable.Rows[0][0].ToString();
lbFullname.Text = myTable.Rows[0][1].ToString();
lbSex.Text = bool.Parse(myTable.Rows[0][2].ToString()) == true ? "Nam" : "Nữ";
lbEmail.Text = myTable.Rows[0][3].ToString();