【问题标题】:Updating Records in Gridview Using EF使用 EF 更新 Gridview 中的记录
【发布时间】:2014-02-23 05:32:37
【问题描述】:

我有一个附加了 gridview 的网页。网格视图允许用户更新单个记录。网格视图如下所示:

JobSiteID         JobSite1
1                 13-03
2                 13-04
3                 13-06
4                 13-09
5                 13-15

我创建了以下记录更新事件处理程序:

protected void changeJobSiteRecordsGridView_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
    GridViewRow row = changeJobSiteRecordsGridView.Rows[e.RowIndex];
    TextBox txtJobSite = row.FindControl("txtJobSite") as TextBox;

    if (txtJobSite != null)
    {
        using (ABCEntities4 Context = new ABCEntities4())
        {
            int jobSiteID = Convert.ToInt32(changeJobSiteRecordsGridView.DataKeys[e.RowIndex].Value);
            JobSite obj = Context.JobSites.First(x => x.JobSiteID == jobSiteID);
            obj.JobSite1 = txtJobSite.Text;
            Context.SaveChanges();
            changeJobSiteRecordsGridView.EditIndex = -1;
            changeJobSiteRecordsGridView.DataSource = Context.JobSites;
            changeJobSiteRecordsGridView.DataBind(); 
        }
    }
}

这是我的问题:
当我在第一行选择更新(例如第 2 行)时,本地“行”变量表示 RowIndex == 1. 但是,在第二行中,我希望 txtJobSite 变量填充“13-04”,但 VS 将“null”分配给变量。 结果,代码流过下面的 if then 语句,这不是预期的。

任何帮助将不胜感激。

谢谢。

【问题讨论】:

    标签: c# asp.net entity-framework gridview


    【解决方案1】:

    像这样检查行的单元格属性:

    row.Cells[1].Controls[0]
    

    用于文本框。如果 '0' 索引不起作用,请尝试 1 索引。然后您的代码将如下所示:

    TextBox txtJobSite = (TextBox)row.Cells[1].Controls[1]
    

    我记得 FindControl 遇到过类似的问题。这样,您可以显式找到单元格,然后找到单元格中的控件。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-03-09
      • 1970-01-01
      • 2022-01-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多