GridView - Exemplo de CRUD

<< Click to Display Table of Contents >>

Navigation:  ASP.NET > ASP Controls > GridView >

GridView - Exemplo de CRUD

Previous pageReturn to chapter overviewNext page

Default.aspx

 

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

 

<html xmlns="http://www.w3.org/1999/xhtml">

<head id="Head1" runat="server">

    <title></title>

</head>

<body>

    <form id="form1" runat="server">

    <div>

    

        <asp:Label ID="Label3" runat="server" Text="Id"></asp:Label>

        <asp:TextBox ID="txtId" runat="server" Width="40px"></asp:TextBox>        <br />

    

        <asp:Label ID="Label1" runat="server" Text="Nome"></asp:Label>

        <asp:TextBox ID="txtNome" runat="server" Width="179px"></asp:TextBox>     <br />

 

        <asp:Label ID="Label2" runat="server" Text="Status"></asp:Label>

        <asp:DropDownList ID="ddlStatus" runat="server">

            <asp:ListItem Selected="True" Value="A">Ativo</asp:ListItem>

            <asp:ListItem Value="I">Inativo</asp:ListItem>

        </asp:DropDownList>        <br />        <br />

 

        <asp:Button ID="GravarBtn" runat="server" Text="Gravar" 

            onclick="btnGravar_Click" />

 

        <asp:Button ID="btnAtualizar" runat="server" onclick="btnAtualizar_Click" 

            Text="Atualizar" />         <br />        <br />

 

        <asp:Button ID="btnBuscar" runat="server" onclick="BtnBuscar_Click" 

            Text="Buscar" />        <br />        <br />

 

        <asp:GridView ID="grvClientes" runat="server" AutoGenerateColumns="False" 

            BackColor="White" BorderColor="#999999" BorderStyle="Solid" BorderWidth="1px" 

            CellPadding="3" EnableModelValidation="True" ForeColor="Black" 

            GridLines="Vertical" onrowcommand="grvClientes_RowCommand">

            <AlternatingRowStyle BackColor="#CCCCCC" />

            <Columns>

                <asp:BoundField DataField="id" HeaderText="Código" />

                <asp:BoundField DataField="nome" HeaderText="Nome" />

                <asp:BoundField DataField="data" HeaderText="Data" />

                <asp:BoundField DataField="status" HeaderText="Status" />

                <asp:TemplateField>

                    <ItemTemplate>

                        <asp:LinkButton ID="lnkExcluir" CommandArgument='<%# DataBinder.Eval(Container.DataItem, "id") %>' runat="server" CommandName="Excluir">Excluir</asp:LinkButton>

                    </ItemTemplate>

                </asp:TemplateField>

                <asp:TemplateField>

                    <ItemTemplate>

                        <asp:LinkButton ID="lknEditar" CommandArgument='<%# Container.DataItemIndex %>' runat="server" CommandName="Editar">Editar</asp:LinkButton>

                    </ItemTemplate>

                </asp:TemplateField>

            </Columns>

            <FooterStyle BackColor="#CCCCCC" />

            <HeaderStyle BackColor="Black" Font-Bold="True" ForeColor="White" />

            <PagerStyle BackColor="#999999" ForeColor="Black" HorizontalAlign="Center" />

            <SelectedRowStyle BackColor="#000099" Font-Bold="True" ForeColor="White" />

        </asp:GridView>

    

    </div>

    </form>

</body>

</html>

 

Default.aspx.cs

 

using System;

using System.Web.UI.WebControls;

using MySql.Data.MySqlClient;

using System.Configuration;

using System.Data;

 

public partial class _Default : System.Web.UI.Page

{

  protected void Page_Load(object sender, EventArgs e)

   {

      if (!IsPostBack)

       {

           Buscar();

       }

   }

 

  public void Buscar()

   {

      MySqlConnection connection = new MySqlConnection(ConfigurationManager.ConnectionStrings["conn"].ToString());

      MySqlCommand command = new MySqlCommand("select * from tabela", connection);

      MySqlDataAdapter da = new MySqlDataAdapter(command);

      DataSet dataset = new DataSet("Cliente");

       da.Fill(dataset);

 

       grvClientes.DataSource = dataset;

       grvClientes.DataBind();

   }

 

  protected void btnGravar_Click(object sender, EventArgs e)

   {

      MySqlConnection connection = new MySqlConnection(ConfigurationManager.ConnectionStrings["conn"].ToString());

 

      // string sql = "insert into tabela (id, nome, data, status) values (@id, @nome, current_date, @status)";

      string sql = "insert into tabela (id, nome, data, status) values (@id, @nome, current_date, @status)";

 

      MySqlCommand command = new MySqlCommand(sql, connection);

       command.Parameters.AddWithValue("id", Int32.Parse(txtId.Text));

       command.Parameters.AddWithValue("nome", txtNome.Text);

       command.Parameters.AddWithValue("status", ddlStatus.SelectedValue);

 

       connection.Open();

       command.ExecuteNonQuery();

       connection.Close();

 

       Buscar();

   }

 

  protected void BtnBuscar_Click(object sender, EventArgs e)

   {

       Buscar();

   }

 

  protected void grvClientes_RowCommand(object sender, GridViewCommandEventArgs e)

   {

      if (e.CommandName == "Excluir")

       {

           Excluir(int.Parse(e.CommandArgument.ToString()));

          return;

       }

 

      if (e.CommandName == "Editar")

       {

 

          int idx = int.Parse(e.CommandArgument.ToString());

          GridViewRow row = grvClientes.Rows[idx];

 

           txtId.Text = row.Cells[0].Text;

           txtNome.Text = row.Cells[1].Text;

           ddlStatus.SelectedValue = row.Cells[3].Text;

           Atualizar();

       }

   }

 

  protected void Excluir(int id)

   {

      MySqlConnection connection = new MySqlConnection(ConfigurationManager.ConnectionStrings["conn"].ToString());

 

      string sql = "delete from tabela where id = @id";

 

      MySqlCommand command = new MySqlCommand(sql, connection);

       command.Parameters.AddWithValue("id", id);

 

       connection.Open();

       command.ExecuteNonQuery();

       connection.Close();

 

       Buscar();

   }

 

  protected void Atualizar()

   {

      MySqlConnection connection = new MySqlConnection(ConfigurationManager.ConnectionStrings["conn"].ToString());

 

      string sql = "update tabela set nome=@nome, status=@status where id = @id";

 

      MySqlCommand command = new MySqlCommand(sql, connection);

       command.Parameters.AddWithValue("id", int.Parse(txtId.Text));

       command.Parameters.AddWithValue("nome", txtNome.Text);

       command.Parameters.AddWithValue("status", ddlStatus.SelectedValue);

 

       connection.Open();

       command.ExecuteNonQuery();

       connection.Close();

 

       Buscar();

   }

 

  protected void btnAtualizar_Click(object sender, EventArgs e)

   {

       Atualizar();

   }

}

 

Web.config

 

   <connectionStrings>

      <add name="conn" connectionString="server=localhost;User Id=root;Password=123456; Persist Security Info=True;database=teste"/>

   </connectionStrings>

   <system.web>