如何更正此类错误“指定的转换无效". [英] how to correct this kind off error ''Specified cast is not valid.''

查看:73
本文介绍了如何更正此类错误“指定的转换无效".的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                SqlCommand cmd = new SqlCommand("select * from buy where numero='" + comboBox1.Text + "'", con);
                con.Close();
                con.Open();
                SqlDataReader rdr = cmd.ExecuteReader();
                if (rdr.Read())
                {
                    //DateTime date = System.Convert.ToDateTime(dateTimePicker1.Text);   
                    //date.DateTime.Parse(rdr[0].ToString());
                    
                    //Convert.ToDateTime(rdr[0].ToString());
                    DateTime date = (DateTime)rdr[0];
                    date.ToShortDateString();
                    comboBoxPrt.Text = rdr[1].ToString();
                    comboBoxCliNo.Text = rdr[2].ToString();
                    txtQty.Text = rdr[3].ToString();
                    txtUprice.Text = rdr[4].ToString();
                    txtTax.Text = rdr[5].ToString();
                    txtTotP.Text = rdr[6].ToString();
                    txtBalnc.Text = rdr[7].ToString();
                    txtAmtpd.Text = rdr[8].ToString();
                    
                }
                con.Close();
            }
            catch (Exception mn)
            {
                MessageBox.Show(mn.Message);
            }
        }

推荐答案

DataReader以您在SQL Management Studio中获得的顺序返回字段.根据您提供的模式,第一个字段将是您命名为 numero 的字段,witch的类型为integer.因此rdr [0]将返回一个不能转换为DateTime的整数.您可以使用字符串索引器 [ GetDateTime [
DataReader is returning fields in the order that you would get in SQL Management Studio for example. According to the schema you provided, the first field would be the one you named numero, witch is of type integer. Thus rdr[0] will return an integer that can not be casted to DateTime. You can use the string indexer[^], to avoid field order problems. But you better use the GetDateTime[^] method.


这篇关于如何更正此类错误“指定的转换无效".的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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