首页 > 解决方案 > 设置datagridview的数据源后添加单元格值

问题描述

DataGridview从数据库中获得后DataSource,我尝试以两种方式添加列:设计TaxDiscount代码。但是当我运行这段代码时:

public void LoadGridView()
{
    GrdReceiptDetail.AutoGenerateColumns = false;
    GrdReceiptDetail.DataSource = SentoDB.usp_viewReceiptDetail(ReceiptId);
    foreach (DataGridViewColumn column in GrdReceiptDetail.Columns)
    {
        if (column.Name != "Check" && column.Name != "Tax" && column.Name != "Discount")
        {
            GrdReceiptDetail.Columns[column.Index].ReadOnly = true;
        }
    }
    foreach (DataGridViewRow row in GrdReceiptDetail.Rows)
    {
        if (row.Index != 0)
        {
            GrdReceiptDetail.Rows[row.Index].Cells["Discount"].Value = "10";
            GrdReceiptDetail.Rows[row.Index].Cells["Tax"].Value = "10";
        }
    }
}

在我加载表格后,第 2 列的单元格中的值DiscountTax空白的。我该如何解决?我认为当我使用 时DataSource,可能会DataGridview阻止我添加列和值。

标签: c#winformsdatagridview

解决方案


尝试这个..

if (row.Index != 0)
{
    //replace RowObject with the name of your underlying class that constitutes each 
    //row
    RowObject obj = (RowObject)row.DataBoundItem;

    //replace DiscountProperty and TaxProperty with the names of the properties on 
    //your RowObject that correspond to these values
    obj.DiscountProperty = "10";
    obj.TaxProperty = "10";
}    

希望这对你有用。这是一个类似问题的链接,详细说明了为什么在使用基础数据源修改 DataGridView 时应该以这种方式更新数据。 以编程方式在数据网格视图中设置单元格值


推荐阅读