在C#Windows编程中使用datagridview中的LINQ插入,更新,删除查询?

时间:2013-04-25 16:44:17

标签: linq c#-4.0 datagridview

场景:表格中有以下控件:
datagridview,textbox1,textbox2,按钮(保存,编辑,更新,删除)

1.点击“保存”按钮,数据应在运行时更新为datagridview 2.通过选择完整行并单击编辑按钮,数据应被检索到文本框中 3.点击“更新”按钮,即可更新该数据 4.通过选择一个完整的行,该行应该被删除。

1 个答案:

答案 0 :(得分:0)

这是我的代码。 我希望它会对你有所帮助

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 LINQ_Test
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        LINQtestDataContext dc = new LINQtestDataContext();

        public void show_data()
        {
            dataGridView1.DataSource = (from t in dc.LinqTests
                                        select t);

        }

        public void insert_data()
        {
            try
            {
                LinqTest tbl = new LinqTest
                {
                ID=Convert.ToInt32(textBox_id.Text),
                Name=textBox_name.Text
            };
                dc.LinqTests.InsertOnSubmit(tbl);
                dc.SubmitChanges();
                MessageBox.Show("Data Inserted!!!");
                show_data();

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        public void update_data()
        {
            try
            {
                LinqTest tbl = dc.LinqTests.Single(x=>x.ID==Convert.ToInt32(textBox_id.Text));
                tbl.Name = textBox_new_name.Text;
                dc.SubmitChanges();
                MessageBox.Show("Data Updated!!!");
                show_data();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        public void delete_data()
        {
            try
            {
                LinqTest tbl = dc.LinqTests.Single(x => x.ID == Convert.ToInt32(textBox_id.Text));
                dc.LinqTests.DeleteOnSubmit(tbl);
                dc.SubmitChanges();
                MessageBox.Show("Data Deleted!!!");
                show_data();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {

            show_data();
        }

        private void button_insert_Click(object sender, EventArgs e)
        {
            insert_data();
        }

        private void button_update_Click(object sender, EventArgs e)
        {
            update_data();
        }

        private void button_delete_Click(object sender, EventArgs e)
        {
            delete_data();
        }
    }
}