Showing posts sorted by relevance for query asp. Sort by date Show all posts
Showing posts sorted by relevance for query asp. Sort by date Show all posts

Friday, March 22, 2013

Sửa, cập nhật record trong Database

ASP.NET

Lab 01: Sửa, cập nhật record trong Database

Bước 1: Tạo Form:
Bước 2:
2.1: Sử dụng thư viên
          using System.Data;
using System.Data.SqlClient;

2.2: Load dữ liệu DataGrid
Khởi tạo các biến:
    SqlConnection sqlConnect;
    SqlDataAdapter sqlAdapter;
    SqlCommand sqlCommand;
    string strSql;
    DataSet dataSet;
    protected void Page_Load(object sender, EventArgs e)
    {
sqlConnect = new SqlConnection("server=.;uid=sa;pwd=HoangDungPro;database=QLSinhVien");
        if (!IsPostBack)
        {
            this.BindData();
        }
    }
    protected void BindData()
    {
        DataGrid1.DataSource = GetData("select * from MON_HOC");
        DataGrid1.DataBind();
    }
    DataSet GetData(string sql)
    {
        sqlAdapter = new SqlDataAdapter(sql, sqlConnect);
        dataSet = new DataSet();
        sqlAdapter.Fill(dataSet);
        return dataSet;
    }
Bước 3:

3.1: Click vào DataGrid sau đó chọn xuống sự kiện: ItemCommand

    protected void FillTheData(string Ma_mon, string Ten_mon)
    {
        txtMa_mon.Text = Ma_mon;
        txtTen_mon.Text = Ten_mon;
    }
    protected void DataGrid1_ItemCommand(object source, DataGridCommandEventArgs e)
    {
        if (e.CommandName == "Edit")
        {
            FillTheData(e.Item.Cells[1].Text, e.Item.Cells[2].Text);
            lblMessage.Text = "";
        }
    }

Bước 4: Sau khi lấy được dữ liệu ra thì ta sẽ cập nhật dữ liệu vào database

    protected void btnUpdate_Click(object sender, EventArgs e)
    {
        try
        {
            strSql = "update MON_HOC set Ten_mon = @Ten_mon where Ma_mon = @Ma_mon";
            sqlCommand = new SqlCommand(strSql, sqlConnect);
            sqlCommand.Parameters.Add(new SqlParameter("@Ten_mon", SqlDbType.NVarChar, 50));
            sqlCommand.Parameters.Add(new SqlParameter("@Ma_mon", SqlDbType.NChar, 2));
            sqlCommand.Parameters["@Ten_mon"].Value = txtTen_mon.Text;
            sqlCommand.Parameters["@Ma_mon"].Value = txtMa_mon.Text;
            if(sqlConnect.State == ConnectionState.Closed)
                sqlConnect.Open();
            sqlCommand.ExecuteNonQuery();
            this.BindData();
            lblMessage.Text = "Cập nhật thành công";
        }
        catch (Exception ex)
        {
            lblMessage.Text = ex.Message;
        }
        finally
        {
            sqlConnect.Close();
        }
    }


Bài tập: Tương tự như vậy bạn hãy phát triển thêm các chức năng: thêm, xóa nữa nhé!