🎬 HoRain云小助手:个人主页
🔥 个人专栏: 《Linux 系列教程》《c语言教程》
⛺️生活的理想,就是为了理想的生活!
⛳️ 推荐
前些天发现了一个超棒的服务器购买网站,性价比超高,大内存超划算!忍不住分享一下给大家。点击跳转到网站。
专栏介绍
专栏名称 | 专栏介绍 |
本专栏主要撰写C干货内容和编程技巧,让大家从底层了解C,把更多的知识由抽象到简单通俗易懂。 | |
本专栏主要是注重从底层来给大家一步步剖析网络协议的奥秘,一起解密网络协议在运行中协议的基本运行机制! | |
全面深入解析 docker 容器,从基础到进阶,涵盖原理、操作、实践案例,助您精通 docker。 | |
本专栏主要撰写Linux干货内容,从基础到进阶,知识由抽象到简单通俗易懂,帮你从新手小白到扫地僧。 | |
本专栏着重撰写Python相关的干货内容与编程技巧,助力大家从底层去认识Python,将更多复杂的知识由抽象转化为简单易懂的内容。 | |
本专栏主要是发布一些考试和练习题库(涵盖软考、HCIE、HRCE、CCNA等) |
目录
在WinForms中实现DataGridView与TextBox的交互扩展可以通过多种方式增强用户体验。以下是一个综合实现方案,包含数据展示、编辑、验证和过滤功能:
public partial class MainForm : Form
{
private BindingSource bindingSource = new BindingSource();
private DataTable dataTable = new DataTable();
public MainForm()
{
InitializeComponent();
InitializeData();
SetupDataBinding();
ConfigureControls();
}
private void InitializeData()
{
// 创建示例数据表
dataTable.Columns.Add("ID", typeof(int));
dataTable.Columns.Add("Name", typeof(string));
dataTable.Columns.Add("Price", typeof(decimal));
dataTable.Columns.Add("Stock", typeof(int));
// 添加示例数据
dataTable.Rows.Add(1, "商品A", 99.99m, 50);
dataTable.Rows.Add(2, "商品B", 199.50m, 30);
}
private void SetupDataBinding()
{
// 配置数据绑定
bindingSource.DataSource = dataTable;
dataGridView1.DataSource = bindingSource;
// 绑定TextBox到当前选中行
txtID.DataBindings.Add("Text", bindingSource, "ID", true);
txtName.DataBindings.Add("Text", bindingSource, "Name", true);
txtPrice.DataBindings.Add("Text", bindingSource, "Price", true);
txtStock.DataBindings.Add("Text", bindingSource, "Stock", true);
}
private void ConfigureControls()
{
// 配置DataGridView
dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
dataGridView1.CellValidating += DataGridView_CellValidating;
// 配置TextBox输入验证
txtPrice.Validating += NumericValidation;
txtStock.Validating += NumericValidation;
// 配置搜索框
txtSearch.TextChanged += (s, e) => FilterData(txtSearch.Text);
}
// 数据过滤功能
private void FilterData(string filterText)
{
try
{
bindingSource.Filter = string.Format(
"Name LIKE '%{0}%' OR CAST(ID AS varchar) LIKE '%{0}%'",
filterText.Replace("'", "''"));
}
catch (Exception ex)
{
MessageBox.Show($"过滤错误: {ex.Message}");
}
}
// 数字验证
private void NumericValidation(object sender, CancelEventArgs e)
{
var txtBox = sender as TextBox;
if (!decimal.TryParse(txtBox.Text, out _))
{
errorProvider.SetError(txtBox, "请输入有效数字");
e.Cancel = true;
}
else
{
errorProvider.SetError(txtBox, "");
}
}
// DataGridView单元格验证
private void DataGridView_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
{
if (dataGridView1.Columns[e.ColumnIndex].Name == "Price")
{
if (!decimal.TryParse(e.FormattedValue.ToString(), out _))
{
e.Cancel = true;
MessageBox.Show("价格必须为有效数字");
}
}
}
// 添加新记录
private void btnAdd_Click(object sender, EventArgs e)
{
var newRow = dataTable.NewRow();
newRow["ID"] = dataTable.Rows.Count + 1;
dataTable.Rows.Add(newRow);
bindingSource.MoveLast();
}
// 删除记录
private void btnDelete_Click(object sender, EventArgs e)
{
if (dataGridView1.CurrentRow != null && !dataGridView1.CurrentRow.IsNewRow)
{
dataGridView1.Rows.RemoveAt(dataGridView1.CurrentRow.Index);
}
}
}
关键功能说明:
- 双向数据绑定:
- 使用BindingSource实现数据源绑定
- TextBox与DataGridView自动同步数据
- 支持立即更新(DataSourceUpdateMode.OnPropertyChanged)
- 数据验证:
- TextBox的数字输入验证
- DataGridView单元格验证
- 错误提示使用ErrorProvider组件
- 增强交互功能:
- 实时搜索过滤(支持ID和名称搜索)
- 数据添加/删除操作
- 自动生成新ID
- 扩展功能建议:
// 添加批量导入功能(示例)
private void btnImport_Click(object sender, EventArgs e)
{
var lines = txtMultiLine.Lines.Where(l => !string.IsNullOrWhiteSpace(l));
foreach (var line in lines)
{
var parts = line.Split(',');
if (parts.Length == 3)
{
var newRow = dataTable.NewRow();
newRow["ID"] = dataTable.Rows.Count + 1;
newRow["Name"] = parts[0].Trim();
newRow["Price"] = decimal.Parse(parts[1].Trim());
newRow["Stock"] = int.Parse(parts[2].Trim());
dataTable.Rows.Add(newRow);
}
}
}
// 添加数据导出功能(示例)
private void btnExport_Click(object sender, EventArgs e)
{
var sb = new StringBuilder();
foreach (DataRow row in dataTable.Rows)
{
sb.AppendLine($"{row["ID"]}, {row["Name"]}, {row["Price"]}, {row["Stock"]}");
}
txtMultiLine.Text = sb.ToString();
}
// 添加单元格样式格式化(示例)
private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
if (dataGridView1.Columns[e.ColumnIndex].Name == "Price")
{
if (e.Value is decimal price)
{
e.CellStyle.BackColor = price > 100 ? Color.LightCoral : Color.LightGreen;
e.FormattingApplied = true;
}
}
}
扩展功能建议:
- 数据导入/导出:
- 支持从多行TextBox批量导入数据
- 支持导出数据到TextBox进行编辑
- 可视化增强:
- 根据数值范围改变单元格背景色
- 添加数据统计信息展示
- 用户体验优化:
- 添加键盘快捷键支持(Ctrl+S保存等)
- 实现数据撤销/恢复功能
- 添加数据排序支持
- 数据持久化:
- 集成数据库连接
- 支持XML/JSON格式的导入导出
注意要点:
- 使用BindingSource时要注意线程安全
- 数据验证要同时处理界面控件和DataGridView
- 大量数据操作时考虑使用虚拟模式
- 重要操作需要添加确认对话框
- 考虑添加数据修改的撤销功能
这种实现方式通过绑定机制保持数据一致性,同时通过扩展功能增强了基本的数据交互需求,可以根据具体业务需求进一步扩展验证规则和交互功能。
❤️❤️❤️本人水平有限,如有纰漏,欢迎各位大佬评论批评指正!😄😄😄
💘💘💘如果觉得这篇文对你有帮助的话,也请给个点赞、收藏下吧,非常感谢!👍 👍 👍
🔥🔥🔥Stay Hungry Stay Foolish 道阻且长,行则将至,让我们一起加油吧!🌙🌙🌙