datagridview使用mysql_datagridview的数据库设计与使用

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 = "序号";

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值