HIỀN TÀI LÀ NGUYÊN KHÍ QUỐC GIA (THÂN NHÂN TRUNG)
Đăng nhập

HTML Markup

The HTML Markup consists of an ASP.Net GridView with three BoundField columns.
Below the GridView there’s a Form with two TextBoxes and a Button for adding row (data) to the GridView and the Database.
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" EmptyDataText="No records has been added." Width="450">
    <Columns>
        <asp:BoundField DataField="CustomerId" HeaderText="Customer Id" />
        <asp:BoundField DataField="Name" HeaderText="Name" />
        <asp:BoundField DataField="Country" HeaderText="Country" />
    </Columns>
</asp:GridView>
<table border="1" cellpadding="0" cellspacing="0" style="border-collapse: collapse;
    width: 450px">
    <tr>
        <td style="width: 150px">
            Name:<br />
            <asp:TextBox ID="txtName" runat="server" Width="140" />
        </td>
        <td style="width: 150px">
            Country:<br />
            <asp:TextBox ID="txtCountry" runat="server" Width="140" />
        </td>
        <td style="width: 150px">
            <asp:Button ID="btnAdd" runat="server" Text="Add" OnClick="Insert" />
        </td>
    </tr>
</table>
 
 
Namespaces
You will need to import the following namespaces.
C#
using System.Data;
using System.Configuration;
using System.Data.SqlClient;
 
VB.Net
Imports System.Data
Imports System.Configuration
Imports System.Data.SqlClient
 
 
Binding the GridView with records from SQL Database Table
The GridView is populated from the database inside the Page Load event of the page.
C#
protected void Page_Load(object sender, EventArgs e)
{
    if (!this.IsPostBack)
    {
        this.BindGrid();
    }
}
 
private void BindGrid()
{
    string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
    string query = "SELECT * FROM Customers";
    using (SqlConnection con = new SqlConnection(constr))
    {
        using (SqlDataAdapter sda = new SqlDataAdapter(query, con))
        {
            using (DataTable dt = new DataTable())
            {
                sda.Fill(dt);
                GridView1.DataSource = dt;
                GridView1.DataBind();
            }
        }
    }
}
 
VB.Net
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
    If Not Me.IsPostBack Then
        Me.BindGrid()
    End If
End Sub
 
Private Sub BindGrid()
    Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
    Dim query As String = "SELECT * FROM Customers"
    Using con As SqlConnection = New SqlConnection(constr)
        Using sda As SqlDataAdapter = New SqlDataAdapter(query, con)
            Using dt As DataTable = New DataTable()
                sda.Fill(dt)
                GridView1.DataSource = dt
                GridView1.DataBind()
            End Using
        End Using
    End Using
End Sub
 
 
Inserting records to GridView
The following event handler is executed when the Add Button is clicked. The Name and Country values are fetched from their respective TextBoxes and then passed to the SQL Query for inserting the record in the database.
Finally, the GridView is again populated with data by making call to the BindGrid method.
C#
protected void Insert(object sender, EventArgs e)
{
    string name = txtName.Text;
    string country = txtCountry.Text;
    txtName.Text = "";
    txtCountry.Text = "";
    string query = "INSERT INTO Customers VALUES(@Name, @Country)";
    string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
    using (SqlConnection con = new SqlConnection(constr))
    {
        using (SqlCommand cmd = new SqlCommand(query))
        {
            cmd.Parameters.AddWithValue("@Name", name);
            cmd.Parameters.AddWithValue("@Country", country);
            cmd.Connection = con;
            con.Open();
            cmd.ExecuteNonQuery();
            con.Close();
        }
    }
    this.BindGrid();
}
 
VB.Net
Protected Sub Insert(ByVal sender As Object, ByVal e As EventArgs)
    Dim name As String = txtName.Text
    Dim country As String = txtCountry.Text
    Dim query As String = "INSERT INTO Customers VALUES(@Name, @Country)"
    Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
    txtName.Text = ""
    txtCountry.Text = ""
    Using con As SqlConnection = New SqlConnection(constr)
        Using cmd As SqlCommand = New SqlCommand(query)
            cmd.Parameters.AddWithValue("@Name", name)
            cmd.Parameters.AddWithValue("@Country", country)
            cmd.Connection = con
            con.Open()
            cmd.ExecuteNonQuery()
            con.Close()
        End Using
    End Using
 
    Me.BindGrid()
End Sub
BÀI CÙNG CHUYÊN MỤC
12