Search code examples
c#sql-serverdapper

load data from sql server table and populate textboxes using dapper


i pass selected ProductID as a string to retrieve data from row with the same 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);
        }
    }

then i try to load data and get it as a ProductModel to populate textboxes with it

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;
    }

i get error Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: "Cannot implicitly convert type object to SalesManager.Models.ProductModel

i tried before with a List and it seem to work, but then i dont know to to get objects and convert the to strings.


Solution

  • You need to use the generic overload of Query, eg

    output = connection.Query<ProductModel>(@"SELECT * FROM Products WHERE ProductID = @ProductID", new { ProductID = productId }).Single();