Array
(
)

add e insert direto no datagridview windowsforms

Jorge Meneses
   - 03 dez 2012

Olá
Gostaria de um help
tenho um datagridview que ja carrega dados de uma tabela euxiliar
gostaria de atraves do datagridview ja add e alterar diretamente na tabela
se possivel usando combobox
qualquer exemplo é bem vindo pois nao faço a minima ideia
desde ja agradeço

André Moes
   - 10 dez 2012

Dá uma olhada nesses códigos, aqui uso um DetailsView em conjunto com um OjectDataSource!

O segredo é criar o comando INSERT, UPDATE e DELETE, além do SELECT na classe e ela passa tudo para o banco!

Detalhe: a conexão não foi fechada, após o ExecuteNonQuery criar o connection("cnn").Close();

Default.aspx

#Código

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

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:ObjectDataSource ID="ObjectDataSource1" runat="server" TypeName="Shipper" SelectMethod="GetAllShippers" InsertMethod="InsertShipper" DeleteMethod="DeleteShipper" UpdateMethod="UpdateShipper">
            <DeleteParameters>
                <asp:Parameter Name="shipperId" Type="Int32" />
            </DeleteParameters>
            <UpdateParameters>
                <asp:Parameter Name="ShipperID" Type="Int32" />
                <asp:Parameter Name="companyName" Type="String" />
                <asp:Parameter Name="phone" Type="String" />
            </UpdateParameters>
            <InsertParameters>
                <asp:Parameter Name="companyName" Type="String" />
                <asp:Parameter Name="phone" Type="String" />
            </InsertParameters>
        </asp:ObjectDataSource>
        <asp:DetailsView ID="DetailsView1" runat="server" AllowPaging="True" DataSourceID="ObjectDataSource1" AutoGenerateRows="False" Width="450px" DataKeyNames="ShipperID" >
            <Fields>
                <asp:BoundField DataField="ShipperID" HeaderText="ShipperId" ReadOnly="true" InsertVisible="false" />
                <asp:BoundField DataField="CompanyName" HeaderText="CompanyName" />
                <asp:BoundField DataField="Phone" HeaderText="Phone" />
                <asp:CommandField ShowInsertButton="True" ShowDeleteButton="True" ShowEditButton="True" />
            </Fields>
        </asp:DetailsView>
    </div>
    </form>
</body>
</html>


Classe Shipper

#Código
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;

/// <summary>
/// Summary description for Shipper
/// </summary>
[DataObject]
public static class Shipper
{
    private static string _cnnString = ConfigurationManager.ConnectionStrings["NorthWindConnectionString"].ToString();

    [DataObjectMethod(DataObjectMethodType.Select)]
    public static DataTable GetAllShippers()
    {
        SqlDataAdapter adp = new SqlDataAdapter("SELECT * FROM shippers", _cnnString);

        DataSet ds = new DataSet("shippers");
        adp.Fill(ds, "shippers");

        return ds.Tables["shippers"];
    }

    [DataObjectMethod(DataObjectMethodType.Insert)]
    public static void InsertShipper(string companyName, string phone)
    {
        SqlConnection cnn = new SqlConnection(_cnnString);
        SqlCommand cmd = new SqlCommand("INSERT INTO Shippers (CompanyName, Phone) values(@CompanyName, @Phone)", cnn);

        cmd.Parameters.Add("@CompanyName", SqlDbType.VarChar, 40).Value = companyName;
        cmd.Parameters.Add("@Phone", SqlDbType.VarChar, 24).Value = phone;

        cnn.Open();
        cmd.ExecuteNonQuery();
    }

    [DataObjectMethod(DataObjectMethodType.Update)]
    public static void UpdateShipper(int shipperId, string companyName, string phone)
    {
        SqlConnection cnn = new SqlConnection(_cnnString);
        SqlCommand cmd = new SqlCommand("UPDATE shippers SET CompanyName=@CompanyName, phone=@Phone " + "WHERE ShipperId=@ShipperId", cnn);

        cmd.Parameters.Add("@ShipperId", SqlDbType.Int, 0).Value = shipperId;
        cmd.Parameters.Add("@CompanyName", SqlDbType.VarChar, 40).Value = companyName;
        cmd.Parameters.Add("@Phone", SqlDbType.VarChar, 24).Value = phone;

        cnn.Open();
        cmd.ExecuteNonQuery();
    }

    [DataObjectMethod(DataObjectMethodType.Delete)]
    public static void DeleteShipper(int shipperId)
    {
        SqlConnection cnn = new SqlConnection(_cnnString);
        SqlCommand cmd = new SqlCommand("DELETE shippers WHERE ShipperId=@ShipperId", cnn);

        cmd.Parameters.Add("@ShipperId", SqlDbType.Int, 0).Value = shipperId;

        cnn.Open();
        cmd.ExecuteNonQuery();
    }
}


Web.config

#Código
<?xml version="1.0"?>
<!--
  For more information on how to configure your ASP.NET application, please visit
  http://go.microsoft.com/fwlink/?LinkId=169433
  -->
<configuration>
  <connectionStrings>
    <add name="NorthWindConnectionString" connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\NorthWind.mdf;Integrated Security=True" providerName="System.Data.SqlClient"/>
  </connectionStrings>
  <system.web>
    <compilation debug="true" targetFramework="4.5"/>
    <httpRuntime targetFramework="4.5"/>
  </system.web>
</configuration>