簡體   English   中英

如何使用 c# 使用 datagridview 單元格和 datagridview 事件向數據庫中插入、刪除、選擇記錄?

[英]how to insert , delete , select records into database using datagridview cells and datagridview events using c#?

我設計了一個只有DataGridView控件的 Windows 窗體應用程序。 我以編程方式綁定數據庫中的數據。 我還編寫了從DataGridView單元格更新數據庫記錄的代碼。 但我不知道如何從這些Cell向數據庫中插入新記錄。 你能幫我嗎?

到目前為止,這是我的代碼:

    private void Form1_Load(object sender, EventArgs e)
    {
        try
        {
            con.ConnectionString = "Data Source=CHANDU-PC;Initial Catalog=Class;Integrated Security=true;MultipleActiveResultSets=true;";
            con.Open();
            SqlCommand cmd = new SqlCommand("select * from student1", con);
            da.SelectCommand = cmd;
            cmd.ExecuteNonQuery();
            DataSet ds = new DataSet();
            da.Fill(ds, "student1");
            dataGridView1.DataSource = ds.Tables[0];
        }
        catch (Exception ex)
        {
            MessageBox.Show("Exception caught : " + ex.Message.ToString());
        }
        finally
        {
            con.Close();
        }
    }

    string s;
    int x, y;
    private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
    {
        //s=dataGridView1.CurrentCell.ToString();
        //x = dataGridView1.CurrentCellAddress.X;
        //y = dataGridView1.CurrentCellAddress.Y;
    }

    private void dataGridView1_CancelRowEdit(object sender, QuestionEventArgs e)
    {
        x = -1;
        y = -1;
    }

    private void dataGridView1_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
    {
        x = dataGridView1.CurrentCellAddress.X;
        y = dataGridView1.CurrentCellAddress.Y;
    }

    private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
    {
        try
        {
            con.ConnectionString = "Data Source=CHANDU-PC;Initial Catalog=Class;Integrated Security=true;MultipleActiveResultSets=true;";
            con.Open();
            SqlCommand cmd;
            if (e.ColumnIndex == 0)
            {
                cmd = new SqlCommand("Select * from student1", con);
                da.SelectCommand = cmd;
                cmd.ExecuteNonQuery();
                MessageBox.Show("invalid column selected");
            }
            else
            {
                s = (string)dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value;
                int i = -1;
                i = (int)Convert.ToInt32(dataGridView1.Rows[e.RowIndex].Cells[0].Value);
                if (e.ColumnIndex == 1)
                    cmd = new SqlCommand("update student1 set name='" + s + "' where id='" + i + "'", con);
                else
                    cmd = new SqlCommand("update student1 set email='" + s + "' where id='" + i + "'", con);
                da.UpdateCommand = cmd;
                cmd.ExecuteNonQuery();
                MessageBox.Show("Information updated Successfully");
            }
            }
        catch (Exception ex)
        {
            MessageBox.Show("Exception caught : " + ex.Message.ToString());
        }
        finally
        {
            con.Close();
        }
    }

    private void dataGridView1_CellEnter(object sender, DataGridViewCellEventArgs e)
    {
        dataGridView1.Refresh();
    }

下面是一個很好的代碼示例,用於通過數據網格視圖向數據庫添加新記錄。 該方法略有不同,但應該有效:

http://www.codeguru.com/csharp/.net/net_data/datagrid/article.php/c13041/Add-Edit-and-Delete-in-DataGridView.htm

這里如何使用DataGridView insertupdatedelete數據希望它可以幫助

    private void dataGridView1_RowValidating(object sender, DataGridViewCellCancelEventArgs e) //or CellValidating Event
    {
        try
        {
            if (dataGridView1.IsCurrentRowDirty) //use IsCurrentCellDirty if you choose CellValidating Event
            {
                con.ConnectionString = "Data Source=CHANDU-PC;Initial Catalog=Class;Integrated Security=true;MultipleActiveResultSets=true;";
                con.Open();
                SqlCommand cmd;

                string studentId = dataGridView1[0, e.RowIndex].EditedFormattedValue.ToString();
                string lastname = dataGridView1[1, e.RowIndex].EditedFormattedValue.ToString();
                string firstname = dataGridView1[2, e.RowIndex].EditedFormattedValue.ToString();
                string myQry;
                //I use int.Parse to Convert the string to int, 
                if (int.Parse(studentId) == 0) //Get Primary key (hint null, 0, or -1 value to insert the data)
                {
                    //Insert
                    myQry = @"insert intro student1 (lastname, firstname) Values ('" + lastname + "', '" + firstname + "')";
                }
                else
                {
                    //Update
                    myQry = @"update student1 set lastname = '" + lastname + "', firstname = '" + firstname + "'" + " Where studentId = '" + studentId + "'";
                }
                cmd = new SqlCommand(myQry, con);
                da.SelectCommand = cmd;
                cmd.ExecuteNonQuery();
            }

        }
        catch (Exception ex)
        {
            MessageBox.Show("Exception caught : " + ex.Message.ToString());
        }
        finally
        {
            con.Close();
        }
    }

    private void dataGridView1_KeyUp(object sender, KeyEventArgs e)
    {
        if (e.KeyCode == Keys.Delete)
        {
            if (dataGridView1.SelectedRows.Count > 0)
            {
                con.ConnectionString = "Data Source=CHANDU-PC;Initial Catalog=Class;Integrated Security=true;MultipleActiveResultSets=true;";
                con.Open();
                SqlCommand cmd;
                foreach (var item in dataGridView1.Rows.Cast<DataGridViewRow>().Where(c => c.IsNewRow == false))
                {
                    string delQry = @"delete from student1 where studentId = '" + item.Cells[0].EditedFormattedValue.ToString() + "'";
                    cmd = new SqlCommand(delQry, con);
                    da.SelectCommand = cmd;
                    cmd.ExecuteNonQuery();
                }
                con.Close();
            }
        }
    }
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 datagridview
{
    public partial class Form1 : Form
    {
        SqlConnection con = new SqlConnection();
        SqlDataAdapter da = new SqlDataAdapter();




public Form1()
        {
            InitializeComponent();
        }




        private void btnshow_Click(object sender, EventArgs e)
        {
        try
            {
                con.ConnectionString = "Data Source=CHANDU-PC;Initial Catalog=Class;Integrated Security=true;MultipleActiveResultSets=true;";
                con.Open();
                SqlCommand cmd = new SqlCommand("select * from student1", con);
                da.SelectCommand = cmd;
                cmd.ExecuteNonQuery();
                DataSet ds = new DataSet();
                da.Fill(ds, "student1");
                dataGridView1.DataSource = ds.Tables[0];
            }
            catch (Exception ex)
            {
                MessageBox.Show("Exception caught : " + ex.Message.ToString());
            }
            finally
            {
                con.Close();
            }
        }



 private void Form1_Load(object sender, EventArgs e)
        {
            try
            {
                con.ConnectionString = "Data Source=CHANDU-PC;Initial Catalog=Class;Integrated Security=true;MultipleActiveResultSets=true;";
                con.Open();
                SqlCommand cmd = new SqlCommand("select * from student1", con);
                da.SelectCommand = cmd;
                cmd.ExecuteNonQuery();
                DataSet ds = new DataSet();
                da.Fill(ds, "student1");
                dataGridView1.DataSource = ds.Tables[0];
            }
            catch (Exception ex)
            {
                MessageBox.Show("Exception caught : " + ex.Message.ToString());
            }
            finally
            {
                con.Close();
            }
        }

        string s,s1,s2;
        int x, y;



        private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
        {
        }



        private void dataGridView1_CancelRowEdit(object sender, QuestionEventArgs e)
        {
            x = -1;
            y = -1;
        }



        private void dataGridView1_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
        {
            x = dataGridView1.CurrentCellAddress.X;
            y = dataGridView1.CurrentCellAddress.Y;
        }



        private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                con.ConnectionString = "Data Source=CHANDU-PC;Initial Catalog=Class;Integrated Security=true;MultipleActiveResultSets=true;";
                con.Open();
                SqlCommand cmd;
                int i = -1,j;
                if (e.ColumnIndex == 0)
                {
                    j = (int)Convert.ToInt32(dataGridView1.Rows[e.RowIndex].Cells[0].Value);
                    s1 = "";
                    s2 = "";
                    cmd = new SqlCommand("insert into student1 values('" +j+ "','" + s1 + "','" + s2 + "')", con);
                    da.InsertCommand = cmd;
                    cmd.ExecuteNonQuery();
                    MessageBox.Show("id inserted successfully");
                }
                else
                {
                    s = (string)dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value;
                    i = (int)Convert.ToInt32(dataGridView1.Rows[e.RowIndex].Cells[0].Value);
                    if (e.ColumnIndex == 1)
                        cmd = new SqlCommand("update student1 set name='" + s + "' where id='" + i + "'", con);
                    else
                        cmd = new SqlCommand("update student1 set email='" + s + "' where id='" + i + "'", con);
                    da.UpdateCommand = cmd;
                    cmd.ExecuteNonQuery();
                    MessageBox.Show("Information updated Successfully");
                }
                }
            catch (Exception ex)
            {
                MessageBox.Show("Exception caught : " + ex.Message.ToString());
            }
            finally
            {
                con.Close();
            }
        }



        private void dataGridView1_CellEnter(object sender, DataGridViewCellEventArgs e)
        {
            dataGridView1.Refresh();
        }



        private void dataGridView1_AllowUserToAddRowsChanged(object sender, EventArgs e)
        {

        }



        private void dataGridView1_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Delete)
            {
                    try
                    {
                        SqlConnection con2 = new SqlConnection();
                        SqlDataAdapter da2 = new SqlDataAdapter();
                        con2.ConnectionString = "Data Source=CHANDU-PC;Initial Catalog=Class;Integrated Security=true;MultipleActiveResultSets=true;";
                        con2.Open();
                        x = (int)Convert.ToInt32(dataGridView1.CurrentRow.Cells[0].Value);
                        SqlCommand cmd2 = new SqlCommand("delete student1 where id='" + x + "'", con2);
                        da2.DeleteCommand = cmd2;
                        cmd2.ExecuteNonQuery();
                        MessageBox.Show("Information deleted Successfully");
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("Exception caught : " + ex.Message.ToString());
                    }
                    finally
                    {
                        con.Close();
                    }
                }
            }



        private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {

        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM