2. Add Server-based Database - Database.mdf
3. Add new Table
Form1 class:
public partial class Form1 : Form
{
SqlConnection cn = new SqlConnection(@"Data Source=(LocalDB)\v11.0;AttachDbFilename=c:\users\zoljargal\documents\visual studio 2012\Projects\LocalDatabaseTutorial2\LocalDatabaseTutorial2\Database1.mdf;Integrated Security=True");
SqlCommand cmd = new SqlCommand();
SqlDataReader dr;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
if (textBox1.Text != "" && textBox2.Text != "")
{
cn.Open();
cmd.CommandText = "insert into Info(Id, Name) values('" + textBox1.Text +"', '" + textBox2.Text + "')";
cmd.ExecuteNonQuery();
cmd.Clone();
MessageBox.Show("Record inserted!");
textBox1.Text = "";
textBox2.Text = "";
cn.Close();
loadList();
}
}
public void loadList()
{
listBox1.Items.Clear();
listBox2.Items.Clear();
cn.Open();
cmd.CommandText = "select * from info";
dr = cmd.ExecuteReader();
if (dr.HasRows)
{
while (dr.Read())
{
listBox1.Items.Add(dr[0].ToString());
listBox2.Items.Add(dr[1].ToString());
}
}
cn.Close();
}
private void Form1_Load(object sender, EventArgs e)
{
cmd.Connection = cn;
loadList();
}
private void listBox2_SelectedIndexChanged(object sender, EventArgs e)
{
ListBox l = sender as ListBox;
if (l.SelectedIndex != -1)
{
listBox1.SelectedIndex = l.SelectedIndex;
listBox2.SelectedIndex = l.SelectedIndex;
textBox1.Text = listBox1.SelectedItem.ToString();
textBox2.Text = listBox2.SelectedItem.ToString();
}
}
private void button2_Click(object sender, EventArgs e)
{
if (textBox1.Text != "" && textBox2.Text != "")
{
cn.Open();
cmd.CommandText = "delete from info where Id ='" + textBox1.Text + "' and Name = '" + textBox2.Text + "'";
cmd.ExecuteNonQuery();
cmd.Clone();
MessageBox.Show("Record deleted!");
textBox1.Text = "";
textBox2.Text = "";
cn.Close();
loadList();
}
}
private void button3_Click(object sender, EventArgs e)
{
if (textBox1.Text != "" && textBox2.Text != "" && listBox1.SelectedIndex != -1)
{
cn.Open();
cmd.CommandText = "update info set Id = '" + textBox1.Text + "', Name = '" + textBox2.Text + "' where Id = '" + listBox1.SelectedItem.ToString() + "' and Name = '" + listBox2.SelectedItem.ToString() + "'";
cmd.ExecuteNonQuery();
cmd.Clone();
MessageBox.Show("Record Updated!");
textBox1.Text = "";
textBox2.Text = "";
cn.Close();
loadList();
}
}
}
}
Result:
No comments:
Post a Comment