[英]Unable to cast object of type 'System.Byte' to type 'System.String'.'
I am trying to populate value from Database to Combobox
and when I run it I get this error:我正在尝试将值从数据库填充到Combobox
,当我运行它时出现此错误:
Unable to cast object of type 'System.Byte' to type 'System.String'.'无法将“System.Byte”类型的 object 转换为“System.String”类型。
Status
is of type tinyint
. Status
是tinyint
类型。
public void FillStatus()
{
try
{
using (SqlConnection conn = new SqlConnection(@"Data Source=(LocalDb)\MSSQLLocalDB;Initial Catalog=DesignSaoOsig1;Integrated Security=True"))
{
conn.Open();
string query = "SELECT DISTINCT Status FROM tblZaposleni_AD";
SqlCommand cmd = new SqlCommand(query, conn);
using (SqlDataReader saReader = cmd.ExecuteReader())
{
while (saReader.Read())
{
string name = saReader.GetString(0);
ddlStatus.Items.Add(name);
}
}
}
}
catch (Exception)
{
throw;
}
}
I find where the error comes from.我找到了错误的来源。 Insted of代替于
string name = saReader.GetString(0);
I just replace this line to this one我只是将这一行替换为这一行
string name = saReader.GetByte(0).ToString();
As SQL Server tinyint
is converted to byte
in .NET, you need to read it as such, then convert to a string:由于 SQL Server tinyint
在 .NET 中被转为byte
,所以需要这样读取,然后转为字符串:
byte dbValue = saReader.GetByte(0);
string name = dbValue.ToString();
ddlStatus.Items.Add(name);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.