
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Data.Common;
namespace DataGridViewDemo
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
string conStr = "server=localhost;database=db_EMS;integrated security=true";
SqlConnection conn;
SqlDataAdapter da;
DataSet ds;
private void Form1_Load(object sender, EventArgs e)
{
//禁止添加行
dataGridView1.AllowUserToAddRows = false;
//禁止刪除行
dataGridView1.AllowUserToDeleteRows = false;
conn = new SqlConnection(conStr);
da = new SqlDataAdapter("select * from tb_pdic", conn);
ds = new DataSet();
da.Fill(ds);
dataGridView1.DataSource = ds.Tables[0];
//禁止對列進行排序(這個要在賦值datasource後)
for (int i = 0; i < dataGridView1.Columns.Count; i++)
dataGridView1.Columns[i].SortMode = DataGridViewColumnSortMode.NotSortable;
//選中時選中整行
dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
//不同的行賦值不同的顏色
foreach(DataGridViewRow dgv in dataGridView1.Rows)
{
if(dgv.Index%2==0)
{
dataGridView1.Rows[dgv.Index].DefaultCellStyle.BackColor = Color.LightSalmon;
}
else
{
dataGridView1.Rows[dgv.Index].DefaultCellStyle.BackColor = Color.LightPink;
}
}
dataGridView1.ReadOnly = true;
//設置選中行的顏色
dataGridView1.DefaultCellStyle.SelectionBackColor = Color.LightSkyBlue;
}
private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
int id =(int) dataGridView1.Rows[e.RowIndex].Cells[0].Value;
conn = new SqlConnection(conStr);
da = new SqlDataAdapter("select * from tb_pdic where id=" + id, conn);
ds = new DataSet();
da.Fill(ds);
if (ds.Tables[0].Rows.Count > 0)
{
textBox1.Text = ds.Tables[0].Rows[0]["name"].ToString();
textBox2.Text = ds.Tables[0].Rows[0]["money"].ToString();
}
}
}
}

【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 使用C#创建一个MCP客户端
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 按钮权限的设计及实现