访问数据库表记录时发生格式转换错误 [英] Format conversion error while accessing database table record

查看:125
本文介绍了访问数据库表记录时发生格式转换错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码在尝试检索表的记录时显示错误消息
在组合框中选择的valueMember属性值的基础上.

错误消息是:-输入字符串的格式不正确"

Following code shows error message while attempting to retrieve a table''s records
on the base of selected valueMember property''s value from combobox.

The error message is:- "input string was not in correct format"

comboBox2.DataSource = MainDataSet.Tables["Members"];
comboBox2.DisplayMember = "MemberName";
comboBox2.ValueMember = "MemID";  // int primary key of ''members'' table 

private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
    DataRow[] bkrow;
    int n=Convert.ToInt32(ComBox1.SelectedValue.ToString());//<--This line shows error
    bkrow = MainDataSet.Tables[0].Select("MemID = ''" + n + "''");   
    string QueryBookName = bkrow[0]["BookName"].ToString();
}



memid是Books表中的int主键.



where memid is int primary key in Books table. How to solve this error?

推荐答案

此错误与数据库无关.此错误来自Convert.ToInt32方法.更好的方法是int.Parse方法.您将需要检查ComBox1.SelectedValue.ToString()是否实际上只是一个包含数字的字符串,或者其中是否包含无效字符.有关有效的输入格式,请参见int.Parse上的MSDN注释:

http://msdn.microsoft.com/en-us/library/b3h1hf19.aspx [ ^ ]
This error is nothing to do with the database. This error is coming from the Convert.ToInt32 method. A better method to use would be int.Parse method. You will need to check whether ComBox1.SelectedValue.ToString() is actually a just a string containing a number or if it has invalid characters in it. See the MSDN coumentation on int.Parse for the valid input formats:

http://msdn.microsoft.com/en-us/library/b3h1hf19.aspx[^]


请像这样将您的代码片段拆开:

Please pull your code fragment apart like this:

comboBox2.DataSource = MainDataSet.Tables["Members"];
comboBox2.DisplayMember = "MemberName";
comboBox2.ValueMember = "MemID";  // int primary key of 'members' table

private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
    DataRow[] bkrow;
    String selectedValue = ComBox1.SelectedValue.ToString();
    if(!String.IsNullOrEmpty(selectedValue))
    {
        int n=Convert.ToInt32(selectedValue);//<--This line shows error
        bkrow = MainDataSet.Tables[0].Select("MemID = '" + n + "'");
        string QueryBookName = bkrow[0]["BookName"].ToString();
    }
}



现在,在带有if语句的行上放置一个断点,并检查变量slectedValue.该错误很可能是由无法转换为整数的值引起的.

最好的问候,

-MRB



Now place a breakpoint on the line with the if statement and inspect the variable slectedValue. The error is most likely caused by a value which cannot be converted to an integer.

Best regards,

-MRB


将此代码
comboBox2.DataSource = MainDataSet.Tables["Members"];

更改为

comboBox2.DataSource = MainDataSet.Tables["Members"].DefaultView;


这篇关于访问数据库表记录时发生格式转换错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆