I am trying to populate value from Database to Combobox
and when I run it I get this error:
Unable to cast object of type 'System.Byte' to type 'System.String'.'
Status
is of type 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:
byte dbValue = saReader.GetByte(0);
string name = dbValue.ToString();
ddlStatus.Items.Add(name);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.