【问题标题】:Get original object from DataRow in GridView C#从 GridView C# 中的 DataRow 获取原始对象
【发布时间】:2014-04-13 14:28:39
【问题描述】:

我尝试显示对象的集合 (IEnumerable)(通过 Linq to Sql 生成)。因此,我将 Gridviews 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>

【问题讨论】:

  • 如果我没记错的话,在 Page_Load 之后转发器的 DataItem 将不再可用。因此,作为SelectedIndexChanged 事件的一部分,DataItem 将为空。不确定您是否可以对此做些什么(这就是为什么这是评论而不是答案)。一种选择是在初始 DataBind 期间构建要在本地保存的数据并在事件处理程序中使用它
  • 请参考这个Link可能会帮助你..!

标签: c# asp.net linq gridview


【解决方案1】:

在您的数据网格视图和列表之间使用绑定源。当进行选择时,datagridview 使用 bindingsource 的 Current 属性从列表中获取正确的项目。

【讨论】:

  • BindingSource 似乎是“WinForms”命名空间的一部分。我是否应该导入这个命名空间只是为了使用 BindingSource。难道没有办法利用 ASP.Net 的功能吗?
  • 此链接可能对您有所帮助。 forums.asp.net/t/…
  • 我发现的唯一方法是在 DataBaound 事件期间创建自己的集合。由于这对我来说不可行,我将坚持使用 BindingSource 解决方案。感谢您的帮助。
【解决方案2】:

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

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

您也可以在循环中使用它,然后它将是:

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

我希望这会有所帮助!

【讨论】:

  • 您好,感谢您的回答。但这对 ma 没有帮助,因为它只得到一个列 tex。我想要的是绑定到gridView的原始对象。
  • 客户 cust = row.DataBoundItem as Customer; if (cust != null) { cust.SendInvoice(); } 也许这会有所帮助。
  • GridViewRow 没有属性“DataBoundItem”。您确定您的目标是 ASP.Net gridView 而不是 WinForms DataGridView?
  • 我曾经使用过 WinForms。不知道ASP.Net GridView和WinForms Gridview有什么区别
猜你喜欢
  • 2010-11-21
  • 1970-01-01
  • 1970-01-01
  • 2021-05-01
  • 1970-01-01
  • 2013-04-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多