【发布时间】:2019-01-24 03:01:41
【问题描述】:
我正在尝试用英里填充文本框。我有一个存储路线和里程的表,其中我有一个包含这些路线的下拉列表。当我尝试将里程读入文本框中时,我在以下代码中收到编译时错误“无法将'string'转换为'int'”(对于GetInt32 和GetDecimal)。
private void location_comboBox_SelectedIndexChanged(object sender, EventArgs e)
{
string conString = "****ConnectionString*****";
string query = "SELECT * FROM Location_Table WHERE Route = '" +
location_comboBox.Text + "';"; // simplified, actual code uses parametrized query
SqlConnection con = new SqlConnection(conString);
SqlCommand cmd = new SqlCommand(query, con);
con.Open();
SqlDataReader myReader = cmd.ExecuteReader();
while (myReader.Read())
{
String Miles = myReader.GetInt32("Miles").ToString();
mileage_textbox.Text = Miles;
}
}
String Miles = myReader.GetInt32("Miles").ToString(); 行出错
无法将“字符串”转换为“整数”
这是有道理的,因为SqlDataReader.GetInt32 需要某种索引(“从零开始的列序号。”),但我想使用列名
DB 中的列类型:
- 英里 - 十进制 (3,1)
- 路由 - varchar(50)
- id - nchar(10)(未在示例中使用)
【问题讨论】:
-
我试过 mileage_textbox.Text = myReader.GetString("Miles");但 io 仍然得到与以前相同的错误:(。我也摆脱了 .ToString()
-
此外,您永远不应该将数据粘合到字符串中以生成 SQL。它很容易出错、过时甚至危险。始终使用 SQL 参数
-
@WelcomeOverflow 我认为当前版本的帖子应该已经得到 OP 这个提示:)
标签: c# sql-server