我正在尝试从组合框中加载数据库中的项目,但在代码中出现了意外错误,似乎没有明显的原因。请帮忙。 错误:参数1:无法从'string'转换为'int'。 在数据库中,'PortName'的数据类型是Varchar。
void FillCombo()
{
SqlConnection conn = new SqlConnection(global::flight_management.Properties.Settings.Default.conn);
string sql = "SELECT PortName FROM PORTS";
SqlCommand exesql = new SqlCommand(sql, conn);
SqlDataReader myReader;
try
{
conn.Open();
myReader = exesql.ExecuteReader();
while(myReader.Read())
{
string sName = myReader.GetString("PortName");
// ERORR HERE: Argument 1: Cannot convert from 'string' to 'int'
ComboFromA.Items.Add("sName");
}
}
catch (Exception ex) {lblError.Text = "Error Loading Airports: "+ ex.Message;}
finally {conn.Close();}
}
答案 0 :(得分:1)
从SqlDataReader
读取数据时,数据库类型很重要ColumnType是String GetString
ColumnType为int GetInt32
ColumnType为Double GetDouble
你可以用一个作为例子
我认为这是SqlDataReader
myReader.GetString(myReader.GetOrdinal("PortName"));
并替换
ComboFromA.Items.Add("sName") to ComboFromA.Items.Add(sName);
答案 1 :(得分:0)
尝试以下代码
void FillCombo()
{
SqlConnection conn = new SqlConnection(global::flight_management.Properties.Settings.Default.conn);
string sql = "SELECT PortName FROM PORTS";
SqlCommand exesql = new SqlCommand(sql, conn);
SqlDataReader myReader;
try
{
conn.Open();
myReader = exesql.ExecuteReader();
while(myReader.Read())
{
string sName = myReader.GetString(0);
//ust use the index 0 for first attribute in select list
ComboFromA.Items.Add("sName");
}
}
catch (Exception ex) {lblError.Text = "Error Loading Airports: "+ ex.Message;}
finally {conn.Close();}
}