【问题标题】:How to add rows to Datagridview from class?如何从类中向 Datagridview 添加行?
【发布时间】:2014-12-16 06:32:41
【问题描述】:

我有一个 win 表单,它有一个 datagridview 和一个按钮。当我按下该按钮时,它会从Order 类调用viewOrderHistory() 方法。从那里我想向datagridview添加行。我的表单名称 orderHistory。这是我的viewOrderHistory 方法。

OrderHistory OH = new OrderHistory();
public void viewOrderHistory(int id){
DataGridView orderHistoryProductDataGrid = OH.dataGridView2;
try
{
int count = 0;
orderHistoryProductDataGrid.Rows.Clear();
orderHistoryProductDataGrid.Refresh();
DatabaseConnection();//Database connection
string ord = "SELECT * FROM Orders_Products WHERE ID='" + id + "'";
SqlCommand ordPro = new SqlCommand(ord, myCon);
SqlDataReader rdr = ordPro.ExecuteReader();
while (rdr.Read())
{
DataGridViewRow row = (DataGridViewRow)orderHistoryProductDataGrid.Rows[count].Clone();
row.Cells[0].Value = rdr["Code"].ToString();
row.Cells[1].Value = mainform.getProduct(rdr["Code"].ToString());
row.Cells[2].Value = rdr["Quantity"].ToString(); ;
orderHistoryProductDataGrid.Rows.Add(row);
count++;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Exception", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}`

从数据库中成功检索数据。但是行没有添加到我的数据网格视图中。请帮忙...

【问题讨论】:

  • 检查我的答案,如果有不清楚的地方告诉我!

标签: c# datagridview


【解决方案1】:
OrderHistory OH = new OrderHistory();
public void viewOrderHistory(int id)
{

    DataGridView orderHistoryProductDataGrid = OH.dataGridView2;
    try
    {
        DatabaseConnection();//Database connection
        string ord = "SELECT * FROM Orders_Products WHERE ID=@ID";
        SqlCommand ordPro = new SqlCommand(ord, myCon);
        ordPro.Parameters.AddWithValue("@ID", id);

        DataSet resultDst = new DataSet();
        using (SqlDataAdapter adapter = new SqlDataAdapter(cmd))
        {
            adapter.Fill(resultDst, "OrderProducts");
        }

        orderHistoryProductDataGrid.DataSource = resultDst.Tables[0]; 
     }
     catch (Exception ex)
     {
        MessageBox.Show(ex.Message, "Exception", MessageBoxButtons.OK, MessageBoxIcon.Error);
     }
}`

首先,您不应该在ID='" + id + "'" 上编写查询,因为您对 sql 注入持开放态度,您可以在 wikipedia 中阅读相关内容。这也会影响 sql server 的性能。始终在查询中使用命令参数。

其次,您可以使用SqlDataAdapterDataSet中的数据库中获取数据,然后将其作为DataSource放入Grid!你可以阅读SqlDataAdapter

第三,请注意您的格式非常纯粹,因此可能没有人回答您!争取在未来做得更好。也不要用'_'在数据库中写你的表。而Orders_Products 只写OrderProducts

另外更好的做法是在不同的层连接到数据库。我在其他问题中写了一个数据访问层:checking user name or user email already exists!在这个问题中,我详细解释了如何做到这一点,如果你想检查的话。 这将提高您的知识

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-10
    • 1970-01-01
    相关资源
    最近更新 更多