从gridviewc#中的DataRow获取原始对象

本文关键字:原始 对象 获取 DataRow gridviewc# 中的 | 更新日期: 2023-09-27 17:49:30

我尝试显示对象的集合(IEnumerable)(通过Linq to Sql生成)。因此,我将Gridview s DataSource属性绑定到我的Linq to SQL方法生成的输出。在GridViewSelectedIndexChanged事件中,我尝试将选定的行DataItem转换回我的原始对象,但最终使用null值代替。

下面是我的代码:
protected void Page_Load(object sender, EventArgs e)
{
    RlDataContext dc = new RlDataContext();
    this.dgvReports.DataSource = dc.GetReports(1);
    this.dgvReports.DataBind();
}
protected void dgvReports_SelectedIndexChanged(object sender, EventArgs e)
{
    if (this.dgvReports.SelectedIndex >= 0)
    {
        Report rpt = (Report)this.dgvReports.SelectedRow.DataItem;
    }
}

GetReports返回类型为ISingleResult<Report>

从gridviewc#中的DataRow获取原始对象

在你的datagridview和列表之间使用一个bindingsource。当一个选择是由datagridview使用bindingsource的Current属性从列表中获得正确的项

这就是我总是从datagridview获取信息的方式

    string variabel = yourDataGridView["Columnname"].ToString();

你也可以在循环中使用它,那么它将是:

    string variabel = yourDataGridView["RowNumber"].Cells["Columnname"].Value.ToString();

我希望这对你有帮助!