Buradaki kodları incelediğimizde listBox kontrolünün içi boş olmaması durumunda veritabanına ekleme işlemi Foreach döngüsü kullanılarak yapılıyor. Kayıt işlemi sonucunda bir mesaj ile kullanıcı bilgilendiriliyor.
Projemizi çalıştırıp kontrol edelim.
Kodlarımızın tamamı aşağıdaki gibi olacaktır.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.OleDb;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace listboxVeriGonder
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
if(textBox1.Text!="")
{
listBox1.Items.Add(textBox1.Text);
textBox1.Text = "";
}
}
OleDbConnection con;
OleDbCommand cmd;
private void button2_Click(object sender, EventArgs e)
{
if(listBox1.Items.Count!=0)
{
string sql = "INSERT INTO Kategori (ad) VALUES(@ad)";
con = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=vt.accdb");
foreach (string kategori in listBox1.Items)
{
cmd = new OleDbCommand(sql, con);
cmd.Parameters.AddWithValue("@ad", kategori);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
MessageBox.Show("Kayıt Eklendi");
}
else
{
MessageBox.Show("Listbox' ta Veri Yok");
}
}
}
}
|
Paylaş: