从 sql 服务器 table 加载数据并使用 dapper 填充文本框
load data from sql server table and populate textboxes using dapper
我将选定的 ProductID 作为字符串传递,以从具有相同 ProductID 的行中检索数据
private void modifyButton_Click(object sender, EventArgs e)
{
if (productsTable.SelectedRows.Count > 0)
{
int selectedrowindex = productsTable.SelectedCells[0].RowIndex;
DataGridViewRow selectedRow = productsTable.Rows[selectedrowindex];
string ProductID = Convert.ToString(selectedRow.Cells["ProductID"].Value);
ProductModel product = db.LoadProduct(ProductID);
}
}
然后我尝试加载数据并将其作为 ProductModel 来填充文本框
public ProductModel LoadProduct(string productId)
{
ProductModel output;
using (IDbConnection connection = new System.Data.SqlClient.SqlConnection(CnnString(db)))
{
output = connection.Query
(@"SELECT * FROM Products WHERE ProductID = @ProductID", new { ProductID = productId }).Single();
}
return output;
}
我收到错误
Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: "无法将类型对象隐式转换为 SalesManager.Models.ProductModel
我之前尝试过使用列表,它似乎可以工作,但后来我不知道如何获取对象并将其转换为字符串。
您需要使用Query的泛型重载,例如
output = connection.Query<ProductModel>(@"SELECT * FROM Products WHERE ProductID = @ProductID", new { ProductID = productId }).Single();
我将选定的 ProductID 作为字符串传递,以从具有相同 ProductID 的行中检索数据
private void modifyButton_Click(object sender, EventArgs e)
{
if (productsTable.SelectedRows.Count > 0)
{
int selectedrowindex = productsTable.SelectedCells[0].RowIndex;
DataGridViewRow selectedRow = productsTable.Rows[selectedrowindex];
string ProductID = Convert.ToString(selectedRow.Cells["ProductID"].Value);
ProductModel product = db.LoadProduct(ProductID);
}
}
然后我尝试加载数据并将其作为 ProductModel 来填充文本框
public ProductModel LoadProduct(string productId)
{
ProductModel output;
using (IDbConnection connection = new System.Data.SqlClient.SqlConnection(CnnString(db)))
{
output = connection.Query
(@"SELECT * FROM Products WHERE ProductID = @ProductID", new { ProductID = productId }).Single();
}
return output;
}
我收到错误 Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: "无法将类型对象隐式转换为 SalesManager.Models.ProductModel
我之前尝试过使用列表,它似乎可以工作,但后来我不知道如何获取对象并将其转换为字符串。
您需要使用Query的泛型重载,例如
output = connection.Query<ProductModel>(@"SELECT * FROM Products WHERE ProductID = @ProductID", new { ProductID = productId }).Single();