Hiển thị các bài đăng có nhãn C#. Hiển thị tất cả bài đăng
Hiển thị các bài đăng có nhãn C#. Hiển thị tất cả bài đăng

Code C#: Hướng dẫn sử dụng Stored Procedures trong Visual Studio 2013

Người đăng: share-nhungdieuhay on Thứ Sáu, 12 tháng 12, 2014

1. Tạo Stored Procedures với chức năng thêm mới một sinh viên:
2. Trong màn hình bên phải, ta viết mã cho Stored Procedures:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author: Hien, Nguyen Minh
-- Create date: 12h 55m, 12-13-2014
-- Description:   Stored Procedures Insert SinhVien
-- =============================================
CREATE PROCEDURE spThemSV
      -- Add the parameters for the stored procedure here
      @MaSVvarchar(50),
      @TenSVvarchar(50)
AS
BEGIN
      -- SET NOCOUNT ON added to prevent extra result sets from
      -- interfering with SELECT statements.
      SETNOCOUNT ON;
      INSERTINTO tblSinhVien(MaSV,TenSV)
      VALUES(@MaSV,@TenSV)
    -- Insert statements for procedure here     
END

3. Thiết kế giao diện trang Thêm mới sinh viên:

4. Trong VS, viết mã nguồn cho sự kiện của nút Thêm (sử dụng Stored Procedures)

private voidbtnThem_Click(object sender, EventArgse){
  SqlConnectionconn = new SqlConnection(chuoikn);
  SqlCommandcmd = new SqlCommand();
  cmd.CommandType = CommandType.StoredProcedure;
  cmd.CommandText = "spThemSV";

  cmd.Parameters.Add("@MaSV", SqlDbType.VarChar).Value = txtMaSV.Text.Trim();
  cmd.Parameters.Add("@TenSV", SqlDbType.VarChar).Value = txtTenSV.Text.Trim();

  cmd.Connection = conn;
  try{
       conn.Open();
       cmd.ExecuteNonQuery();
  }
  catch(Exception ex){
       throwex;
  }
  finally{
       conn.Close();
  }
} 

5. Trong sự kiện Click của nút Thoat ta viết mã xử lý như sau:
private voidbtnThoat_Click(object sender, EventArgse)
        {
            this.Close();
        }

Tag: C#, Lập trình windows, lập trình windows nâng cao, lập trình giao diện, lập trình ado.net, Stored Procedures, Visual Studio 2013
More about

Code C#: Hướng dẫn tạo Form đăng nhập đơn giản

Người đăng: share-nhungdieuhay

1. Thiết kế giao diện form:

2. Tạo bảng CSDL tblTaiKhoan:


3. Trong sự kiện Click của nút Đăng nhập, viết mã xử lý sau:
private void btnDangNhap_Click(object sender, EventArgs e)
        {
            SqlConnection conn = new SqlConnection(chuoikn);
            string sqlSelect = "Select * from tblTaiKhoan where TaiKhoan = '" + txtTaiKhoan.Text + "' and MatKhau = '" + txtMatKhau.Text + "'";
            conn.Open();
            SqlCommand cmd = new SqlCommand(sqlSelect, conn);
            SqlDataReader reader = cmd.ExecuteReader();
            if (reader.Read() == true)
            {               
                this.Hide();
                Form main = new Frm_Main();
                main.Show();
            }
            else
            {
                MessageBox.Show("Ban dang nhap khong thanh cong !");
                txtTaiKhoan.Text = "";
                txtMatKhau.Text = "";
                txtTaiKhoan.Focus();               
            }
        }
4. Trong sự kiện Click của nút Thoat, viết mã xử lý sau:
private void btnThoat_Click(object sender, EventArgs e)
        {
            this.Close();
        }

Tag: C#, Lập trình windows, lập trình windows nâng cao, lập trình giao diện, lập trình ado.net
More about

ASP.NET: Thêm mới, cập nhật, xóa dữ liệu trên GridView

Người đăng: share-nhungdieuhay on Thứ Hai, 3 tháng 11, 2014


1. Tạo bảng customers trong cơ sở dữ liệu CustomerManage với các trường và kiểu dữ liệu sau:

2. Cấu hình tập tin web.config:
<configuration>
    <system.web>
      <compilation debug="true" targetFramework="4.5"/>
      <httpRuntime targetFramework="4.5"/>
    </system.web>
  <connectionStrings>
    <add  name="conn" connectionString="Data Source=hiennm;Initial Catalog=CustomerManage;Integrated Security=True"/>
  </connectionStrings>
</configuration>

3. Tập tin Default.aspx (Thiết kế giao diện)
<head runat="server">
    <title></title>
</head>
<body>
<form id="form1" runat="server">
<div id="dvGrid" style="padding:10px; width:550px">
<asp:GridView ID="GridView1" runat="server"  Width = "550px"
AutoGenerateColumns = "false" Font-Names = "Arial"
Font-Size = "11pt" AlternatingRowStyle-BackColor = "#C2D69A"
HeaderStyle-BackColor = "blue" AllowPaging ="true"  ShowFooter = "true"
OnPageIndexChanging = "OnPaging" onrowediting="EditCustomer"
onrowupdating="UpdateCustomer"  onrowcancelingedit="CancelEdit"
PageSize = "10" >
<Columns>
<asp:TemplateField ItemStyle-Width = "30px"  HeaderText = "CustomerID">
    <ItemTemplate>
        <asp:Label ID="lblCustomerID" runat="server"
        Text='<%#Eval("CustomerID")%>'></asp:Label>
    </ItemTemplate>
    <FooterTemplate>
        <asp:TextBox ID="txtCustomerID" Width = "40px"
            MaxLength = "5" runat="server"></asp:TextBox>
    </FooterTemplate>
</asp:TemplateField>
<asp:TemplateField ItemStyle-Width = "100px"  HeaderText = "Name">
    <ItemTemplate>
        <asp:Label ID="lblContactName" runat="server"
                Text='<%#Eval("ContactName")%>'></asp:Label>
    </ItemTemplate>
    <EditItemTemplate>
        <asp:TextBox ID="txtContactName" runat="server"
            Text='<%#Eval("ContactName")%>'></asp:TextBox>
    </EditItemTemplate>
    <FooterTemplate>
        <asp:TextBox ID="txtContactName" runat="server"></asp:TextBox>
    </FooterTemplate>
</asp:TemplateField>
<asp:TemplateField ItemStyle-Width = "150px"  HeaderText = "Company">
    <ItemTemplate>
        <asp:Label ID="lblCompany" runat="server"
            Text='<%#Eval("CompanyName")%>'></asp:Label>
    </ItemTemplate>
    <EditItemTemplate>
        <asp:TextBox ID="txtCompany" runat="server"
            Text='<%#Eval("CompanyName")%>'></asp:TextBox>
    </EditItemTemplate>
    <FooterTemplate>
        <asp:TextBox ID="txtCompany" runat="server"></asp:TextBox>
    </FooterTemplate>
</asp:TemplateField>
<asp:TemplateField>
    <ItemTemplate>
        <asp:LinkButton ID="lnkRemove" runat="server"
            CommandArgument = '<%#Eval("CustomerID")%>'
         OnClientClick = "return confirm('Do you want to delete?')"
        Text = "Delete" OnClick = "DeleteCustomer"></asp:LinkButton>
    </ItemTemplate>
    <FooterTemplate>
        <asp:Button ID="btnAdd" runat="server" Text="Add"
            OnClick = "AddNewCustomer" />
    </FooterTemplate>
</asp:TemplateField>
<asp:CommandField  ShowEditButton="True" />
</Columns>
<AlternatingRowStyle BackColor="#C2D69A"  />
</asp:GridView>
</div>
</form>
</body>
</html>

4. File Default.aspx.cs (Mã nguồn C#)
usingSystem;
usingSystem.Collections.Generic;
usingSystem.Linq;
usingSystem.Web;
usingSystem.Web.UI;
usingSystem.Web.UI.WebControls;
usingSystem.Data;
usingSystem.Data.SqlClient;
usingSystem.Configuration;

public partial class Insert_Update_Delete: System.Web.UI.Page
{
    private StringstrConnString = ConfigurationManager.ConnectionStrings["conn"].ConnectionString;
    private voidBindData(){
        stringstrQuery = "select CustomerID,ContactName,CompanyName" +
                           " from customers";
        SqlCommandcmd = new SqlCommand(strQuery);
        GridView1.DataSource = GetData(cmd);
        GridView1.DataBind();
    }
    private DataTableGetData(SqlCommand cmd){
        DataTabledt = new DataTable();
        SqlConnectioncon = new SqlConnection(strConnString);
        SqlDataAdaptersda = new SqlDataAdapter();
        cmd.CommandType = CommandType.Text;
        cmd.Connection = con;
        con.Open();
        sda.SelectCommand = cmd;
        sda.Fill(dt);
        returndt;
    }
  
    protected voidPage_Load(object sender, EventArgse){
        if(!IsPostBack)
        {
            BindData();
        }
    }
    protected voidAddNewCustomer(object sender, EventArgse){
        stringCustomerID = ((TextBox)GridView1.FooterRow.FindControl("txtCustomerID")).Text;
        stringName = ((TextBox)GridView1.FooterRow.FindControl("txtContactName")).Text;
        stringCompany = ((TextBox)GridView1.FooterRow.FindControl("txtCompany")).Text;
        SqlConnectioncon = new SqlConnection(strConnString);
        SqlCommandcmd = new SqlCommand();
        cmd.CommandType = CommandType.Text;
        cmd.CommandText = "insert into customers(CustomerID, ContactName, CompanyName) "+
        "values(@CustomerID, @ContactName, @CompanyName);" +
        "select CustomerID,ContactName,CompanyName from customers";
        cmd.Parameters.Add("@CustomerID", SqlDbType.VarChar).Value = CustomerID;
        cmd.Parameters.Add("@ContactName", SqlDbType.VarChar).Value = Name;
        cmd.Parameters.Add("@CompanyName", SqlDbType.VarChar).Value = Company;
        GridView1.DataSource = GetData(cmd);
        GridView1.DataBind();
    }
    protected voidEditCustomer(object sender, GridViewEditEventArgse)
    {
        GridView1.EditIndex = e.NewEditIndex;
        BindData();
    }
    protected voidCancelEdit(object sender, GridViewCancelEditEventArgse)
    {
        GridView1.EditIndex = -1;
        BindData();
    }
    protected voidUpdateCustomer(object sender, GridViewUpdateEventArgse)
    {
        stringCustomerID = ((Label)GridView1.Rows[e.RowIndex]
                            .FindControl("lblCustomerID")).Text;
        stringName = ((TextBox)GridView1.Rows[e.RowIndex]
                            .FindControl("txtContactName")).Text;
        stringCompany = ((TextBox)GridView1.Rows[e.RowIndex]
                            .FindControl("txtCompany")).Text;
        SqlConnectioncon = new SqlConnection(strConnString);
        SqlCommandcmd = new SqlCommand();
        cmd.CommandType = CommandType.Text;
        cmd.CommandText = "update customers set ContactName=@ContactName," +
         "CompanyName=@CompanyName where CustomerID=@CustomerID;" +
         "select CustomerID,ContactName,CompanyName from customers";
        cmd.Parameters.Add("@CustomerID", SqlDbType.VarChar).Value = CustomerID;
        cmd.Parameters.Add("@ContactName", SqlDbType.VarChar).Value = Name;
        cmd.Parameters.Add("@CompanyName", SqlDbType.VarChar).Value = Company;
        GridView1.EditIndex = -1;
        GridView1.DataSource = GetData(cmd);
        GridView1.DataBind();
    }
    protected voidDeleteCustomer(object sender, EventArgse)
    {
        LinkButtonlnkRemove = (LinkButton)sender;
        SqlConnectioncon = new SqlConnection(strConnString);
        SqlCommandcmd = new SqlCommand();
        cmd.CommandType = CommandType.Text;
        cmd.CommandText = "delete from  customers where "+
        "CustomerID=@CustomerID;"+
         "select CustomerID,ContactName,CompanyName from customers";
        cmd.Parameters.Add("@CustomerID", SqlDbType.VarChar).Value
            = lnkRemove.CommandArgument;
        GridView1.DataSource = GetData(cmd);
        GridView1.DataBind();
    }
    protected voidOnPaging(object sender, GridViewPageEventArgse)
    {
        BindData();
        GridView1.PageIndex = e.NewPageIndex;
        GridView1.DataBind();
    }
}
Tags: Asp.net, asp, mvc, gridview, vs 2013, visual studio, mfc, c#, vb.net
More about