博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
datagridview的数据库设计与使用
阅读量:6978 次
发布时间:2019-06-27

本文共 1879 字,大约阅读时间需要 6 分钟。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace DataGridView
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            DataBind(); //调用数据绑定,初始化数据
        }
        protected void DataBind()
        {
            SqlConnection con = new SqlConnection("server=.;database=goodluck;uid=sa;pwd=;");
            SqlDataAdapter sda = new SqlDataAdapter();
            SqlCommand cmd = new SqlCommand("select * from persons where age>3 order by age asc", con);
            sda.SelectCommand = cmd;
            DataSet ds = new DataSet();
            sda.Fill(ds);
            this.dataGridView1.DataSource = ds.Tables[0]; //把第一个表设置为数据源
            //与ASP.NET里GridView控件不同的是这里的DataGridView不需要DataBind()
        }
    }
}
DataGridView里绑定了DataSet的数据,我们要想删除DataGridView里的某一行数据,怎么办?
假设DataGridView的第一列是id(int型)
int id =Convert.ToInt32(this.dataGridView1[0, dataGridView1.CurrentCell.RowIndex].Value); //获取行ID号
然后组织SQL语句就OK了。
用datagridview更新数据库 (2008-04-30 12:59:38) 标签:datagridview 数据库 更新 it   
基于单表datagridview可以用此方法更新,基于多表datagridview还是用sqlcommand的更新方法更新吧!呵呵!
private SqlDataAdapter adapter = new SqlDataAdapter(); //建立数据适配器
private DataTable customers = new DataTable(); //建立数据表
private void Form1_Load(object sender, EventArgs e)
{
  SqlConnection connection = new SqlConnection ("server=192.168.1.122;uid=sa;pwd=sa;database=goods");
  connection.Open();
  SqlCommand mycomm = new SqlCommand("select * from DepartMent", connection);     
  adapter.SelectCommand = mycomm; 
  adapter.Fill(customers);
  this.dataGridView1.DataSource = customers; //设置数据源
}
private void button1_Click(object sender, EventArgs e)
   SqlCommandBuilder mybuikder = new SqlCommandBuilder(adapter); 
   adapter.Update(customers);
}
注意键列信息,所更改的数据表必须有主键!否则无法更新.
更改列名为中文应该使用:
dataGridView1.Columns[0].HeaderText = "序号";  
 
本文转自 qianshao 51CTO博客,原文链接:http://blog.51cto.com/qianshao/201798,如需转载请自行联系原作者
你可能感兴趣的文章
JAVAEclipse:could not find the main class,program will exit!
查看>>
Provisioning Services 7.8 入门系列教程之十三 使用 Boot Device Management(BDM)
查看>>
Centos 6.4下MySQL备份及还原详情介绍
查看>>
sql server 表索引碎片处理
查看>>
ASP网络编程从入门到精通 下载
查看>>
集群概述及原理笔记(1)
查看>>
主动防病毒内容篇
查看>>
无准备,不编程——计算机达人成长之路(15)连载
查看>>
服务器监控--cacti中英文版安装全解
查看>>
Nginx+Tomcat实现反向代理与动静分离
查看>>
WSUS Troubleshooting guide
查看>>
在SQL中使用CRL函数示例
查看>>
ATLAS入门篇之CascadingDropDown控件编程
查看>>
《从零开始学Swift》学习笔记(Day 47)——final关键字
查看>>
linux下磁盘镜像软件DRBD的使用
查看>>
snort源码的详细分析
查看>>
揭开Annotation的面纱
查看>>
使用DPM2007备份还原Exchange2007邮箱数据库
查看>>
zabbix企业应用之监控oracle
查看>>
FOSCommentBundle功能包:设置Doctrine ODM映射
查看>>