DataGridView是一个非常强大的控件,用法很多。这里介绍一个简单的增删改例子。

贴效果图

右侧输入学生信息点击新增,将数据增加到数据库,并且加载到datagridview中,点击选择某条数据修改,将选择的数据加载到右侧的编辑框内,修改后点击修改即可,也可直接删除。

贴代码

 public partial class Form1 : Form
{ private static string strConn = "Data Source=210.26.*.*;Initial Catalog=Test;User ID=sa;Password=****";
private SqlConnection conn = new SqlConnection(strConn);
private string sqlId = "";
private SqlCommand cmd = null;
private SqlDataAdapter da = null; public Form1()
{
InitializeComponent();
} private void Form1_Load(object sender, EventArgs e)
{
//SqlDataReader studentlist = cmd.ExecuteReader();
//bindingSource1.DataSource = studentlist;
//dataGridView1.DataSource = bindingSource1;
BindData();
}
private void BindData()
{
if (conn.State == ConnectionState.Closed)
{
conn.Open();
}
sqlId = "select * from [Student] ";
cmd = new SqlCommand(sqlId, conn);
da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds, "student");
dataGridView1.AutoGenerateColumns = false;//此行指定不需要自动绑定数据列,数据列在dataGridView的属性items集合里指定,必须放在绑定数据之前哦,放到后面是没用的
//dataGridView1.DataSource=ds.Tables["Student"];此处直接用DataTalbe绑定,与下面两行代码的效果是一样的
dataGridView1.DataSource = ds;//使用Dataset,单必须指定DataMember,因为DataSet是DataTable的集合,而datagridview只能绑定一个datatable
dataGridView1.DataMember = "Student";
if (conn.State == ConnectionState.Open)
{
conn.Close();
}
} private void btnAdd_Click(object sender, EventArgs e)
{
try
{
string username = textBox1.Text;
string homeaddress = textBox2.Text;
string info = textBox3.Text;
conn.Open();
//准备一个SQL语句,其中以@开头的在这里只表示一种变量,一种参数。
sqlId = "Insert into Student(StudenTnAME, HomeAddress, Content)values(@StudenTnAME,@HomeAddress,@Content)";
//创建一个参数数组,并且用花括号里面的值来初始化数组
SqlParameter[] parameters = new[]
{
//这里也有个初始化的过程,将name复制给@name,下面的是一样的
new SqlParameter("@StudenTnAME",username),//而小括号右边的name就是程序一开始我们得到的用户输入的值
new SqlParameter("@HomeAddress",homeaddress),
new SqlParameter("@Content",info)
};
cmd=conn.CreateCommand();
//利用对象的属性,把sql字符串放进命令(设置要对数据源执行的SQL语句)
cmd.CommandText = sqlId;
//先利用对象的Parameters属性获取参数集,再将参数集的值附加到后面
cmd.Parameters.AddRange(parameters);
int x=cmd.ExecuteNonQuery();
if (x ==)
{
//如果添加成功,那么给用户提示一下
MessageBox.Show("添加成功");
textBox1.Text = "";
textBox2.Text = "";
textBox3.Text = "";
} }
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
} //点击选中行,将内容放到编辑框内
private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
textBox1.Text = dataGridView1.Rows[e.RowIndex].Cells["studentname"].Value.ToString();
textBox2.Text = dataGridView1.Rows[e.RowIndex].Cells["homeaddress"].Value.ToString();
textBox3.Text = dataGridView1.Rows[e.RowIndex].Cells["info"].Value.ToString();
} //对修改该内容进行保存
private void btnUpdate_Click(object sender, EventArgs e)
{
try
{
conn.Open();
//准备一个SQL语句,拼接一个sql串,这里有别于ADD里面传参
sqlId = "update Student set StudenTnAME='" + textBox1.Text + "',HomeAddress='" + textBox2.Text + "',Content='" + textBox3.Text + "' where ID=" + Convert.ToInt32(dataGridView1.CurrentRow.Cells[].Value.ToString()); cmd = conn.CreateCommand();
//利用对象的属性,把sql字符串放进命令(设置要对数据源执行的SQL语句)
cmd.CommandText = sqlId; int x = cmd.ExecuteNonQuery();
if (x == )
{
//如果添加成功,那么给用户提示一下
MessageBox.Show("修改成功");
textBox1.Text = "";
textBox2.Text = "";
textBox3.Text = "";
BindData();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
}
//删除选中行
private void btnDel_Click(object sender, EventArgs e)
{
try
{
conn.Open();
//准备一个SQL语句,拼接一个sql串,这里有别于ADD里面传参
sqlId = " delete from Student where ID=" +Convert.ToInt32(dataGridView1.CurrentRow.Cells[].Value.ToString()); cmd = conn.CreateCommand();
//利用对象的属性,把sql字符串放进命令(设置要对数据源执行的SQL语句)
cmd.CommandText = sqlId; int x = cmd.ExecuteNonQuery();
if (x == )
{
//如果添加成功,那么给用户提示一下
MessageBox.Show("删除成功");
textBox1.Text = "";
textBox2.Text = "";
textBox3.Text = "";
BindData();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
} }

就是这么简单,但是我们可以看到数据的操作是比较繁琐的,后面的博文会封装一个数据库操作类,进行操作。

Winform开发之DataGridView的增删改的更多相关文章

  1. Winform开发之DataGridView事件和属性

    DataDridView的事件和属性非常多,一一介绍还是不现实,这里借鉴一下园友和MSDN上的介绍吧 1.C#中 DataGridView 属性说明(转载) 2.MSDN上DataGridView事件 ...

  2. 安卓开发之sql语句增删改查2(利用谷歌封装好的API进行增删改查)

    <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android=&quo ...

  3. 安卓开发之sql语句增删改查

    package com.lidaochen.phonecall; import android.content.Context; import android.database.sqlite.SQLi ...

  4. 使用DataGridView进行增删改查,并同步到数据库

    DataGridView控件具有极高的可配置性和可扩展性.它提供有大量的属性.方法和事件,能够用来对该控件的外观和行为进行自己定义.以下通过一个小样例来展示DataGridView进行增删改查,并同步 ...

  5. 浅谈dataGridView使用,以及画面布局使用属性,对datagridview进行增删改查操作,以及委托使用技巧

        通过几天的努力后,对datagridview使用作一些简要的介绍,该实例主要运用与通过对datagridview操作.对数据进行增删改查操作时,进行逻辑判断执行相关操作.简单的使用委托功能,实 ...

  6. Winform开发之SqlCommand常用属性和方法

    SqlCommand类表示要对 SQL Server 数据库执行的一个 Transact-SQL 语句或存储过程,有若干个属性和若干个方法,具体的各类方法使用可以从msdn上找到. 这里介绍几个常用东 ...

  7. winform开发之UI系列

    1.如何构造一个漂亮的主窗体 主要讲述如何对一个新建窗体的美化过程,涉及到经常需要用到的几个属性我会着重强调它的用法,并不断更新它,因为楼主也正在探索中.... 步骤如下: vs新建一个winform ...

  8. winform 开发之Control.InvokeRequired

    Control.InvokeRequired 获取一个值,该值指示调用方在对控件进行方法调用时是否必须调用 Invoke 方法,因为调用方位于创建控件所在的线程以外的线程中. InvokeRequir ...

  9. 对datagridview进行增删改(B)

    create DATABASE stu ON ( name='stu.mdf', filename='F:\胡浴东\数据库\stu数据库\stu.mdf', size=, filegrowth= ) ...

随机推荐

  1. springboot的相关信息

    Maven的配置:zzp_settings.xml <?xml version="1.0" encoding="UTF-8"?> <setti ...

  2. Ajax保留浏览器历史的两种解决方案(Hash&Pjax)

    总是在github down点东西,github整个界面做的不错,体验也很好~对于其中的源代码滑动的特效最为喜欢了~刚开始以为这个只是普通的ajax请求效果,但是发现这个特效能够导致浏览器地址栏跟随变 ...

  3. 使用scikit-learn 估计器分类

    本章的几个概念: 估计器(estimator) 用于分类.聚类和回归分析          转换器(transformer):用于数据预处理回来数据转换          流水线(pipeline): ...

  4. 后台管理系统-使用AdminLTE搭建前端

    返回总目录<ABP项目实战-后台管理系统-目录> 安装AdminLte 我们通过Nuget包管理器安装AdminLte 引用三方组件 因为AdminLte使用到了很多三方的组件,所以我们需 ...

  5. 3.2 Templates -- The Application Template

    1. 当你的应用程序启动时application模板是默认被渲染的的模板. 2. 你应该把你的header, footer和其他任何的装饰内容放到这里.此外,你应该有至少一个{{outlet}}:它是 ...

  6. 排序问题Java

    package zhuzhuangtu; import java.util.*; import java.io.*; public class Main{ public static void mai ...

  7. FFmpeg 入门(7):Seeking

    本文转自:FFmpeg 入门(7):Seeking | www.samirchen.com 处理 seek 命令 我们将为播放器添加 seek 的能力.这个过程中,我们会看到 av_seek_fram ...

  8. HUE配置文件hue.ini 的zookeeper模块详解(图文详解)(分HA集群)

    不多说,直接上干货! 我的集群机器情况是 bigdatamaster(192.168.80.10).bigdataslave1(192.168.80.11)和bigdataslave2(192.168 ...

  9. 蜻蜓FM下载文件名还原

    从蜻蜓FM手机版可以下载音频文件,目的是可以使用普通的播放器进行音频的播放(只是缓存,还用蜻蜓fm播放的请路过),但问题来了,下载下来的音频文件不是在界面中我们看到的文件名称了.于是,我们要进行一项非 ...

  10. POJ 1014 Dividing(多重背包+二进制优化)

    http://poj.org/problem?id=1014 题意:6个物品,每个物品都有其价值和数量,判断是否能价值平分. 思路: 多重背包.利用二进制来转化成0-1背包求解. #include&l ...