目录
1 数据库的操作
1.1 从数据库中读取数据的控制台程序示例
1.2 向数据库中插入记录
1.2.1 使用SqlSever管理器生成插入语句
1.2.2 数据增删改的操作源码:
2 DataGridView绑定和显示数据库的信息
2.1 [查询] 按钮的代码
2.2 DataGridView的 [ 编辑列 ] 操作
2.3 增删改操作【不推荐,拼接SQL语句比较繁琐,工程中多用存储过程】
2.4 使用行前标记的形式操作然后在更新到数据库
3 dataGridView控件使用细节及拓展
3.1 属性
3.2 事件【示例代码,旨在演示部分属性】
3.3 按钮获取当前单元格的文本
3.4 从数据库中获取性别,绑定combox
R 参考文献:
声明名称空间
using System.Data.SqlClient;
using System.Data;
思路:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Data;
namespace sqlServerDemo
{
class Program
{
static void Main(string[] args)
{
//------------1 声明一个链接SQL的字符串------------------
SqlConnectionStringBuilder scsb = new SqlConnectionStringBuilder();
scsb.DataSource = "";//数据库地址
scsb.UserID = "";//数据库登录名
scsb.Password = "";//数据库登录密码
scsb.InitialCatalog = "";//要连接的数据库表
//方法二
//string connStr = "";
//SqlConnection conn = new SqlConnection(connStr);
//-------------2 创建链接---------------------------------
//只需要实例化一次就可以;否则每次实例化都是一个新的链接,初始状态是处于关闭状态
SqlConnection conn = new SqlConnection(scsb.ToString());
while (true)
{
//--------2.1 打开链接-------
//判断是否已经有链接被打开
if (conn.State == ConnectionState.Closed)
{
conn.Open();
}
//--------2.2 创建要执行的SQL语句-------
Console.WriteLine("请输入一个学号(终止Q):");
string stu_no = Console.ReadLine();
if (stu_no == "Q")
{
break;
}
//注意stu_no的前后有''修饰
string sqlStr = "select * from students where 学号 = '" + stu_no + "'";
//--------2.3 创建用于执行SQL语句的对象----
//参数1:需要执行的sql指令;参数2:已打开的链接
SqlCommand comn = new SqlCommand(sqlStr, conn);
//--------2.4 执行SQL语句读取数据表的内容----
//只能从数据库中读取
SqlDataReader sdr = null;
try
{
sdr = comn.ExecuteReader();
while (sdr.Read())
{
//可以使用列名或者列索引查询
Console.WriteLine(sdr["姓名"].ToString());
Console.WriteLine(sdr["性别"].ToString());
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
conn.Close();
}
}
}
}
}
//添加用户逻辑
static void OperateSqlDataSet()
{
//声明数据初始化
string stu_no = string.Empty;
string class_name = string.Empty;
string stu_name = string.Empty;
string stu_sex = string.Empty;
int stu_age = 0;
string sqlStr = string.Empty;
SqlConnectionStringBuilder scsb = new SqlConnectionStringBuilder();
scsb.DataSource = "";
scsb.UserID = "";
scsb.Password = "";
scsb.InitialCatalog = "";
SqlConnection conn = new SqlConnection(scsb.ToString());
if (conn.State == ConnectionState.Closed)
{
conn.Open();
}
while (true)
{
string type = "请输入操作指令【添加(C)修改(U)删除(D)】:";
if (type == "C")
{
Console.WriteLine("请输入学号");
stu_no = Console.ReadLine();
Console.WriteLine("请输入班级");
class_name = Console.ReadLine();
if (ExistStu(conn, stu_no, class_name))
{
Console.WriteLine("输入的学员信息已经存在");
continue;
}
Console.WriteLine("请输入姓名");
stu_name = Console.ReadLine();
Console.WriteLine("请输入性别");
stu_sex = Console.ReadLine();
Console.WriteLine("请输入年龄");
string age = Console.ReadLine();
if (age != "")
{
stu_age = int.Parse(age);
}
string insertStr = "INSERT INTO [dbo].[students] ([学号], [班级], [姓名], [性别], [年龄]) VALUES ('"
+ stu_no + "', '" + class_name + "', '" + stu_name + "', '" + stu_sex + "'," + stu_age + ")";
}
else if (type == "U")
{
Console.WriteLine("请输入学号");
stu_no = Console.ReadLine();
Console.WriteLine("请输入班级");
class_name = Console.ReadLine();
if (false == ExistStu(conn, stu_no, class_name))
{
Console.WriteLine("输入的学员信息不存在,无法修改");
continue;
}
Console.WriteLine("请输入姓名");
stu_name = Console.ReadLine();
Console.WriteLine("请输入性别");
stu_sex = Console.ReadLine();
Console.WriteLine("请输入年龄");
string age = Console.ReadLine();
if (age != "")
{
stu_age = int.Parse(age);
}
string updateStr = "UPDATE [dbo].[students] set [姓名] = '" + stu_name + "',[性别] = '" + stu_sex + "', [年龄] = '" + stu_age + "' WHERE [学号] = '" + stu_no + "' AND [班级] = '" + class_name + "'";
}
else if (type == "D")
{
Console.WriteLine("请输入学号");
stu_no = Console.ReadLine();
Console.WriteLine("请输入班级");
class_name = Console.ReadLine();
if (false == ExistStu(conn, stu_no, class_name))
{
Console.WriteLine("输入的学员信息不存在,无法删除");
continue;
}
string deleteStr = "DELETE [dbo].[students] " + "WHERE [学号] = '" + stu_no + "' AND [班级] = '" + class_name + "'";
}
SqlCommand comn = new SqlCommand(sqlStr, conn);
try
{
int rows = comn.ExecuteNonQuery();
if (rows == 1)
{
Console.WriteLine("学员保存成功");
}
else
{
Console.WriteLine("学员保存失败");
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
//判断输入信息是否存在
static bool ExistStu(SqlConnection conn, string stu_no, string class_name)
{
string SqlStr = "SELECT * FROM [dbo].[students] " + "WHERE [学号] = '" + stu_no + "' AND [班级] = '" + class_name + "'"; ;
SqlCommand comn = new SqlCommand(SqlStr, conn);
SqlDataReader sdr = comn.ExecuteReader();
if (sdr.Read())
{
sdr.Close();
return true;
}
else
{
sdr.Close();
return false;
}
}
private void button1_Click(object sender, EventArgs e)
{
SqlConnectionStringBuilder scsb = new SqlConnectionStringBuilder();
scsb.DataSource = "";
scsb.UserID = "";
scsb.Password = "";
scsb.InitialCatalog = "";
SqlConnection conn = new SqlConnection(scsb.ToString());
if (conn.State == System.Data.ConnectionState.Closed)
{
conn.Open();
}
string strSql = "SELECT * FORM students WHERE stu_no LIKE '" + textBox1.Text.Trim() + "%'";//查询记录,模糊查询
//LIKE语法:前后加%,表示只要包含检索文本就满足;%在前,表示以检索文本结尾的就满足;%在后,表示以检索文本开始的就满足
//string strSql = "SELECT * FROM students";//整表查询
//string strSql = "SELECT * FROM students; SELECT * FROM grades";//多表查询
//执行查询整个数据表的多条语句
SqlDataAdapter sda = new SqlDataAdapter(strSql, conn);//参数1:T-SQL语句;参数2:数据库连接对象
DataSet ds = new System.Data.DataSet(); //表示数据在内存中的缓存;是表的集合,可以存储许多表
sda.Fill(ds, "students");//参数1:数据表;参数2:数据表的名称,可自定义不需要与查询的表明必须一致
//表的名称规则为系统自动添加数字后缀的格式,比如,如student,student1,student2,...
//绑定数据到dataGridView
//方法一
dataGridView1stu.DataSource = ds;
dataGridView1stu.DataMember = "students";//此处需与ds.Fille指定的名字一致
//方法二
//dataGridView1stu.DataSource = ds.Tables["students"];
//方法三
DataTable dt = ds.Tables["students"];
dataGridView1stu.DataSource = dt.DefaultView;
}
调整DataGridView的列头高度:设置为非AutoSize;数值18修改才有效
选中一行,按下delete,选中的行会被删除
private void buttonSave_Click(object sender, EventArgs e)
{
DataTable changeDT = dt.GetChanges();//存储自加载以来对数据表中所作的所有修改
//逐行循环执行操作
foreach (DataRow dr in changeDT.Rows)
{
string sqlStr = string.Empty;
//判断每行执行的是何种操作
//增加
if (dr.RowState == System.Data.DataRowState.Added)//获取与当前相关的当前状态--增加
{
//可使用SQL Sevser客户端生成语句,然后拼接【切记:一定要拼对】
sqlStr = @"INSERT INTO [dbo].[students] ([学号], [班级], [姓名], [性别], [年龄]) VALUES ('"
+ dr["stu_no"] + "', '" + dr["class_name"] + "', '"
+ dr["stu_name"] + "', '" + dr["stu_sex"] + "'," + Convert.ToInt32(dr["stu_age"]) + ")";
}
else if (dr.RowState == System.Data.DataRowState.Deleted)//获取与当前相关的当前状态--删除
{
//获取已经被标记为删除的行的数据
//DataRowVersion 获取删除之前的原始值
string stuNo = dr["stu_no", DataRowVersion.Original].ToString();//从原始值中取
string stuClass = dr["stu_class",DataRowVersion.Original].ToString();
sqlStr = @"DELETE FROM [dbo].[students] WHERE stu_no = '" + stuNo + "' AND stu_class = '" + stuClass + "'";
}
else if (dr.RowState == System.Data.DataRowState.Modified)//获取与当前相关的当前状态--修改
{
sqlStr = "UPDATE [dbo].[students] set [姓名] = '" + dr["stu_name"] + "',[性别] = '" + dr["stu_sex"] + "', [年龄] = '" + Convert.ToInt32(dr["stu_age"]) + "' WHERE [学号] = '" + dr["stu_no"] + "' AND [班级] = '" + dr["class_name"] + "'";
}
SqlCommand comm = new SqlCommand(sqlStr, conn);
comm.ExecuteNonQuery();
}
}
private void buttonAddRow_Click(object sender, EventArgs e)
{
dataGridView1stu.Rows.Add();//往最后一行去添加
int rc = dataGridView1stu.Rows.Count - 1;
dataGridView1stu.Rows[rc].HeaderCell.Value = "ADD";//加标记
}
private void buttonDeleteRow_Click(object sender, EventArgs e)
{
int index = dataGridView1stu.CurrentRow.Index;
if (dataGridView1stu.Rows[index].HeaderCell.Value != null
&& dataGridView1stu.Rows[index].HeaderCell.Value.ToString() == "ADD")
{
dataGridView1stu.Rows.RemoveAt(index);
}
else
{
dataGridView1stu.Rows[index].HeaderCell.Value = "DELETE";
}
}
本部分为示例代码,只展示实现的思路,忽略细节
主要思路:
private void buttonAddRow_Click(object sender, EventArgs e)
{
if (dt == null)
{
//没有绑定数据时添加行
dataGridView1stu.Rows.Add();//往最后一行去添加
int rc = dataGridView1stu.Rows.Count - 1;
dataGridView1stu.Rows[rc].HeaderCell.Value = "ADD";//加标记
}
else
{
//绑定数据后添加行
DataRow dr = dt.NewRow();//创建一个和当前绑定数据具有相同架构的行
//获取dataGridView显示的行数,如果为0,就在第0行后加入;否则在当前行之后加入
//
int index = (dataGridView1stu.RowCount == 1) ? 0 : (dataGridView1stu.CurrentRow.Index + 1);
dt.Rows.InsertAt(dr, index);
dataGridView1stu.Rows[index].HeaderCell.Value = "ADD";//在行头位置添加新增行标记
}
}
private void buttonDeleteRow_Click(object sender, EventArgs e)
{
//单行数据的操作
//int index = dataGridView1stu.CurrentRow.Index;
//if (dataGridView1stu.Rows[index].HeaderCell.Value != null
// && dataGridView1stu.Rows[index].HeaderCell.Value.ToString() == "ADD")
//{
// dataGridView1stu.Rows.RemoveAt(index);
//}
//else
//{
// dataGridView1stu.Rows[index].HeaderCell.Value = "DELETE";
//}
//同时对多行数据的操作,必须选中行头才有效
foreach (DataGridViewRow dr in dataGridView1stu.SelectedRows)
{
//int index = dataGridView1stu.CurrentRow.Index;
//点击dataGridView的左上角可以批量全选
if (dataGridView1stu.Rows[dr.Index].HeaderCell.Value == null)
{
dataGridView1stu.Rows[dr.Index].HeaderCell.Value = "DELETE";
}
else if (dataGridView1stu.Rows[dr.Index].HeaderCell.Value.ToString() == "ADD")
{
dataGridView1stu.Rows.RemoveAt(dr.Index);
}
else if (dataGridView1stu.Rows[dr.Index].HeaderCell.Value.ToString() == "UPDATE")
{
//dataGridView1stu.Rows.RemoveAt(dr.Index);
dataGridView1stu.Rows[dr.Index].HeaderCell.Value = "DELETE";
}
}
}
//此处逻辑比较混乱,删除该事件也可以
private void dataGridView1stu_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
//删除>修改>添加
//if (dataGridView1stu.RowCount > 0)
//{
// if (dataGridView1stu.Rows[e.RowIndex].HeaderCell.Value == null)
// {
// dataGridView1stu.Rows[e.RowIndex].HeaderCell.Value = "UPDATE";
// }
// else if (dataGridView1stu.Rows[e.RowIndex].HeaderCell.Value.ToString() == "ADD")
// {
// dataGridView1stu.Rows[e.RowIndex].HeaderCell.Value = "ADD";
// }
// else if (dataGridView1stu.Rows[e.RowIndex].HeaderCell.Value.ToString() == "DELETE")
// {
// dataGridView1stu.Rows[e.RowIndex].HeaderCell.Value = "DELETE";
// }
// //if (dataGridView1stu.Rows[e.RowIndex].HeaderCell.Value == null)
// //{
// // dataGridView1stu.Rows[e.RowIndex].HeaderCell.Value = "UPDATE";
// //}
// //else if (dataGridView1stu.Rows[e.RowIndex].HeaderCell.Value.ToString() != "DELETE")
// //{
// // dataGridView1stu.Rows[e.RowIndex].HeaderCell.Value = "UPDATE";
// //}
//}
}
string strOld = string.Empty;
private void dataGridView1stu_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
{
strOld = dataGridView1stu.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString();
}
private void dataGridView1stu_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
string strNew = dataGridView1stu.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString();
if (strOld != strNew)
{
if(dataGridView1stu.Rows[e.RowIndex].HeaderCell.Value == null)
{
dataGridView1stu.Rows[e.RowIndex].HeaderCell.Value = "U";
}
else if (dataGridView1stu.Rows[e.RowIndex].HeaderCell.Value.ToString() == "D")
{
dataGridView1stu.Rows[e.RowIndex].HeaderCell.Value = "U";
}
}
}
private void buttonSave2_Click(object sender, EventArgs e)
{
for (int i = 0; i < dataGridView1stu.RowCount; i++)
{
if (dataGridView1stu.Rows[i].HeaderCell.Value.ToString() == "N")
{
//取值
string stu_no = dataGridView1stu.Rows[i].Cells["stu_no"].Value.ToString();
stu_no = dataGridView1stu["stu_no", i].Value.ToString();
// insert into 语句
}
else if (dataGridView1stu.Rows[i].HeaderCell.Value.ToString() == "D")
{
//DELETE 语句
}
else if (dataGridView1stu.Rows[i].HeaderCell.Value.ToString() == "U")
{
//UPDATE 语句
}
//执行SQL语句
}
}
属性 | 描述 |
MultiSelect | 是否允许多个单元格或数据行(列)被选中 |
Readonly | 是否内容是只读的 |
SelectionMode | 指示如何选中单元格【整行、行头选择】 |
StandardTab | 用户单击Tab键后的行为【切换到下一个单元格还是下一个控件】 |
EditMode | 进入编辑模式的方式【常用EditOnEnter】 |
AlternatingRowsDefaultCellStyle | 设置奇数行颜色与偶数行不一致 |
private void dataGridView1stu_CellClick(object sender, DataGridViewCellEventArgs e)
{
//获取单元格的内容
string cellText = dataGridView1stu[e.RowIndex, e.ColumnIndex].Value.ToString();
//获取列的名称
string colName = dataGridView1stu.Columns[e.ColumnIndex].Name;
//获取列的标题
string colCaption = dataGridView1stu.Columns[e.ColumnIndex].HeaderText;
//给选中的行变更颜色[数据量大的情况下,不能这么干];通常的干法是在数据绑定之后,使用此段代码修改背景颜色
for (int i = 0; i < dataGridView1stu.RowCount; i++)
{
if (i == e.RowIndex)
{
dataGridView1stu.Rows[i].DefaultCellStyle.BackColor = Color.YellowGreen;
}
else
{
dataGridView1stu.Rows[i].DefaultCellStyle.ForeColor = Color.White;//设置前景色,即文字的颜色
}
}
//修改单元格的颜色
dataGridView1stu[e.RowIndex, e.ColumnIndex].Style.BackColor = Color.Yellow;
//嵌套循环取值[可以使用此循环遍历判断,识别非法数据]
for (int row = 0; row < dataGridView1stu.RowCount; row++)
{
for (int col = 0; col < dataGridView1stu.ColumnCount; col++)
{
string cellText1 = dataGridView1stu[col, row].Value.ToString();
}
}
}
private void buttonRead_Click(object sender, EventArgs e)
{
int rowIndex = dataGridView1stu.CurrentCell.RowIndex;
int colIndex = dataGridView1stu.CurrentCell.ColumnIndex;
//获取单元格的内容
string cellText = dataGridView1stu[colIndex, rowIndex].Value.ToString();
}
先绑定性别,再绑定数据表
C#超越菜鸟第十三课:DataGridView查询
C#超越菜鸟第十四课:DataGridView增删改
C#超越菜鸟第十六课:DataGridView拓展下集