Warning: Parameter 1 to wp_default_scripts() expected to be a reference, value given in /var/www/techmind.dk/public_html/csharp/wp-includes/plugin.php on line 571

Warning: Parameter 1 to wp_default_styles() expected to be a reference, value given in /var/www/techmind.dk/public_html/csharp/wp-includes/plugin.php on line 571
C# » CRUD ado.net eksempel

CRUD ado.net eksempel

create + read + update + delete = CRUD

Dette er winforms eksempel på hvordan CRUD opsættes og bruges.

Eksemplet kan let overføres til feks ASP.NET, eller anden .NET ‘ting.


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using System.Data.SqlClient;

namespace DisconnectedCRUD
{
public partial class Form1 : Form
{
SqlDataAdapter adapter;
DataSet kunderDS;

public Form1()
{
InitializeComponent();
dataGridView1.MultiSelect = false;
dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;

LoadData();
}

public void LoadData()
{
string conString = @”Data Source=.\sqlexpress;Initial Catalog=KundeDB;”;
conString += “Integrated Security=True”;

string sqlString = “SELECT * FROM Kunder”;

SqlConnection con = new SqlConnection(conString);
SqlCommand cmd = new SqlCommand(sqlString, con);

adapter = new SqlDataAdapter(cmd);
SqlCommandBuilder cb = new SqlCommandBuilder(adapter);
kunderDS = new DataSet();

adapter.Fill(kunderDS, “Kunder”);

cbKunder.DataSource = kunderDS.Tables[“Kunder”];
cbKunder.DisplayMember = “Navn”;
cbKunder.ValueMember = “ID”;

this.dataGridView1.DataSource = kunderDS.Tables[“Kunder”];
}

private void btnInsert_Click(object sender, EventArgs e)
{
DataRow myRow = kunderDS.Tables[“Kunder”].NewRow();
myRow[“Navn”] = txtKundenavn.Text;
myRow[“Adresse”] = txtAdresse.Text;
kunderDS.Tables[“Kunder”].Rows.Add(myRow);
adapter.Update(kunderDS, “Kunder”);

LoadData();
}

private void btnUpdate_Click(object sender, EventArgs e)
{
int item = dataGridView1.SelectedRows[0].Index;
kunderDS.Tables[“Kunder”].Rows[item][“Navn”] = txtKundenavn.Text;
kunderDS.Tables[“Kunder”].Rows[item][“Adresse”] = txtAdresse.Text;
adapter.Update(kunderDS, “Kunder”);

LoadData();
}

private void btnDelete_Click(object sender, EventArgs e)
{
int item = dataGridView1.SelectedRows[0].Index;
kunderDS.Tables[“Kunder”].Rows[item].Delete();
adapter.Update(kunderDS, “Kunder”);

LoadData();
}
}
}

links og ressourcer

restore sql express tabeller i Visual studio 2010

← Previous

Tags: , ,

Skriv et svar

Din e-mailadresse vil ikke blive offentliggjort. Krævede felter er markeret med *