![](/img/trans.png)
[英]System.Collections.Generic.KeyNotFoundException: The given key was not present in the dictionary
[英]System.Collections.Generic.KeyNotFoundException: 'The given key was not present in the dictionary.' C# windows application
我正在处理 c# 项目,我将数据存储到本地服务器上托管的 MySql 数据库,表单将数据存储到数据库但是当我尝试在 datagridview 中从 MySql 中获取数据时,它显示错误
System.Collections.Generic.KeyNotFoundException: '字典中不存在给定的键。'
我的连接代码是
MySqlConnection connection = new MySqlConnection("Server = 192.168.0.xxx; Port = 3306; Database = databaset; User ID = xxx; Password = xxxx; CharSet = utf8;");
MySqlCommand command;
MySqlDataAdapter adapter;
DataTable table;
当我将服务器 ip 更改为 localhost 时,它开始工作。 所以我认为连接字符串有问题,但无法弄清楚。 在 datagridview 中显示数据的代码是
string Query = "SELECT id AS 'ID',driver_name AS 'Driver Name',driver_license_no AS 'License No',driver_cnic_no AS 'Driver CNIC No' FROM table_name ORDER BY ID Desc";
command = new MySqlCommand(Query, connection);
adapter = new MySqlDataAdapter(command);
table = new DataTable();
adapter.Fill(table);
dataGridView1.DataSource = table;
你的代码对我来说很好。 请检查您是否使用最新的MySQL.Data库。
我通过使用MySql.Data.Dll 版本 6.3.6.0参考解决了这个问题,现在工作正常。
看起来连接字符串有额外的空格符号:
Server=192.168.0.xxx;Port=3306;Database=databaset;User ID=xxx;Password=xxxx;CharSet=utf8;
这可能是另一台服务器上的排序规则问题,请尝试不使用字符集并查看:
Server=192.168.0.xxx;Port=3306;Database=databaset;User ID=xxx;Password=xxxx;
在服务器数据库上检查每列的“排序规则”值是否与列数据类型相同。 它们之间的差异可能会引发此类错误。
可以通过为表中的所有列选择“排序规则”选项中的“表默认”值来解决此错误。
此页面上有一个解决方案可能会有所帮助: 在 MySQL 中克服“字典中不存在给定键”异常
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.