使用Datagridview更新数据库 [英] Updating Database Using Datagridview

查看:143
本文介绍了使用Datagridview更新数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以使用列表框添加,编辑,删除数据库。但是我想使用DatagridView做到这一点,我已经将其绑定到数据库。

I can add, edit, delete database using listbox. But I want to do it using DatagridView I already bind it to my database.

如何使用代码在datagridview中添加,编辑,删除更新我的数据库?

How do I add,edit,delete update my database in datagridview using codes?

这些是我的代码:

namespace Icabales.Homer
{
    public partial class Form1 : Form
{
    SqlConnection cn = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=c:\users\homer\documents\visual studio 2010\Projects\Icabales.Homer\Icabales.Homer\Database1.mdf;Integrated Security=True;User Instance=True");
    SqlCommand cmd = new SqlCommand();
    SqlDataReader dr;
    SqlDataAdapter da;
    DataTable dt = new DataTable();
    public Form1()
    {
        InitializeComponent();
    }
    private void bindgrid()
    {
        string command = "select * from info";
        da = new SqlDataAdapter(command, cn);
        da.Fill(dt);
        dataGridView1.DataSource = dt;
    }
    private void Form1_Load(object sender, EventArgs e)
    {
        // TODO: This line of code loads data into the 'database1DataSet.info' table. You can move, or remove it, as needed.
        this.infoTableAdapter.Fill(this.database1DataSet.info);
        cmd.Connection = cn;
        loadlist();
        bindgrid();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        if (txtid.Text != "" & txtname.Text != "")
        {
            cn.Open();
            cmd.CommandText = "insert into info (id,name) values ('" + txtid.Text + "' , '" + txtname.Text + "')";
            cmd.ExecuteNonQuery();
            cmd.Clone();
            MessageBox.Show("Record Inserted");
            cn.Close();
            txtid.Text = "";
            txtname.Text = "";
            loadlist();
        }
    }
    private 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 listBox2_SelectedIndexChanged(object sender, EventArgs e)
    {
        ListBox l = sender as ListBox;
        if (l.SelectedIndex != -1)
        {
            listBox1.SelectedIndex = l.SelectedIndex;
            listBox2.SelectedIndex = l.SelectedIndex;
            txtid.Text = listBox1.SelectedItem.ToString();
            txtname.Text = listBox2.SelectedItem.ToString();
        }

    }

    private void button2_Click(object sender, EventArgs e)
    {
        if (txtid.Text != "" & txtname.Text != "")
        {
            cn.Open();
            cmd.CommandText = "delete from info where id = '"+txtid.Text+"'and name = '"+txtname.Text+"'";
            cmd.ExecuteNonQuery();
            cn.Close();
            MessageBox.Show("Record Deleted");
            loadlist();
            txtid.Text = "";
            txtname.Text = "";
        }
    }

    private void button3_Click(object sender, EventArgs e)
    {
        if (txtid.Text != "" & txtname.Text != "" & listBox1.SelectedIndex != -1)
        {
            cn.Open();
            cmd.CommandText = "update info set id='"+txtid.Text+"',name='"+txtname.Text+"'where id='"+listBox1.SelectedItem.ToString()+"' and name='"+listBox2.SelectedItem.ToString()+"'";
            cmd.ExecuteNonQuery();
            cn.Close();
            MessageBox.Show("Record Updated");
            loadlist();
            txtid.Text = "";
            txtname.Text = "";
        }
    }
}

}

推荐答案

我在表单上有一个dataGridView和一个按钮。当我在dataGridView1中进行任何编辑,插入或删除操作时,下面的代码很神奇

I have a dataGridView and a button on a form. When I do any editing, insertion or deletion in the dataGridView1, the code below does the magic

public partial class EditPermit : Form
{
     OleDbCommand command;
     OleDbDataAdapter da;
     private BindingSource bindingSource = null;
     private OleDbCommandBuilder oleCommandBuilder = null;
     DataTable dataTable = new DataTable();

    public EditPermit()
    {
        InitializeComponent();
    }

    private void EditPermitPermit_Load(object sender, EventArgs e)
    {
        DataBind();                           
    }

    private void btnSv_Click(object sender, EventArgs e)
    {
         dataGridView1.EndEdit(); //very important step
         da.Update(dataTable);
         MessageBox.Show("Updated");        
         DataBind(); 
    }

    private void DataBind()
    {
        dataGridView1.DataSource = null;
        dataTable.Clear();

        String connectionString = MainWindow.GetConnectionString(); //use your connection string please
        String queryString1 = "SELECT * FROM TblPermitType"; // Use your table please

        OleDbConnection connection = new OleDbConnection(connectionString);
        connection.Open();
        OleDbCommand command = connection.CreateCommand();
        command.CommandText = queryString1;
        try
        {
            da = new OleDbDataAdapter(queryString1, connection);
            oleCommandBuilder = new OleDbCommandBuilder(da);
            da.Fill(dataTable);
            bindingSource = new BindingSource { DataSource = dataTable }; 
            dataGridView1.DataSource = bindingSource;
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }


    }

这篇关于使用Datagridview更新数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆