带有错误的数据绑定winform代码“;InvalidCastException未处理“;
本文关键字:InvalidCastException 未处理 代码 winform 有错误 数据绑定 | 更新日期: 2023-09-27 18:25:03
我正在用C#进行数据绑定winform,以连接Northwind数据库目标是在winform gridview中提供数据,当我单击每个单元格时,数据将显示在相应的文本框中。
class Connection
{
String connectionstring = "Data Source=ECHREIPCPC0671''SQLEXPRESS;Initial Catalog=Northwind;Integrated Security=True";
public ArrayList GetAllProduct(int ProductID)
{
using (var connection = new SqlConnection(connectionstring)) {
connection.Open();
String query = "SELECT * FROM Products WHERE ProductID = " + ProductID;
using (var command = new SqlCommand(query, connection))
{
var reader = command.ExecuteReader();
var list = new ArrayList();
while (reader.Read())
{
String productname = reader.GetString(1);
String quantityperunit = reader.GetString(2);
Decimal unitprice = reader.GetDecimal(3);
list.Add(productname);
list.Add(quantityperunit);
list.Add(unitprice);
}
connection.Close();
reader.Close();
return list;
}
这是我添加的新类,用于读取和获取winform中的数据。在这里,当我执行代码时,总是会出现错误
"无法将"System.Int32"类型的对象强制转换为"System.String"类型。
代码之后:`String quantityperunit=reader。GetString(2);
我应该如何更正我的代码?有人能帮我吗?
附言:在form1.cs中,我添加了函数来使用这个类中的成员。
private void FillTextfield(int ProductID)
{
list = sqlCon.GetAllProduct(ProductID);
textProductName.Text = list[0].ToString();
textQuantityPerUnit.Text = list[1].ToString();
textUnitPrice.Text = list[2].ToString();
}
private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
var currentRowIndex = dataGridView1.SelectedCells[0].RowIndex;
int currentIndex = (int)dataGridView1.Rows[currentRowIndex].Cells[0].Value;
FillTextfield(currentIndex);
}
}
我不认为quantityperunit是int类型,因为这个单元格中的数据类似于"12oz瓶",依此类推
尝试
String quantityperunit=reader.GetString(2).ToString();
reader.GetString(2)
正在获取一些整数数据,而您正试图将这些数据放入字符串变量中,这将引发异常。
quantityperunit是一个整数类型。
int quantityperunit = int.Parse(reader.GetString(2).ToString());
"无法将类型为System.Int32的对象强制转换为类型为System.String"
你可以试试这个。。
String quantityperunit=reader.GetInt32(2).ToString();