c# - Gridview 更新返回 null

标签 c# asp.net visual-studio-2010 gridview

我正在尝试使用 gridview 的更新方法,它只是返回 null

    protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        TextBox Currency = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("Currency"));
        GridView1.EditIndex = -1;

        if (!Page.IsPostBack)
        {
            FillTravelers();
        }
    }

有什么想法吗?当我按下更新时,它只是将该字段返回到其先前的值但不返回任何内容。

谢谢

最佳答案

由于您的 Gridview 是最简单的形式,在 gridview 中没有定义控件(因此在 GridView 中没有定义货币文本框),请检查 GridView1 的数据源,我假设它是一个数据表。 然后您需要确定数据表的哪一列是货币列。

例如,对于下面的数据表,它将是第 2 列。

  DataTable taskTable = new DataTable("AmountList");
  taskTable.Columns.Add("Id", typeof(int));
  taskTable.Columns.Add("Currency", typeof(string));
  taskTable.Columns.Add("Amount", typeof(decimal)); 

基于此,您可以使用以下代码检索更新后的货币值。

    protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        GridViewRow row = TaskGridView.Rows[e.RowIndex];
        GridView1.EditIndex = -1;
        TextBox txtCurrency = (TextBox)(row.Cells[2].Controls[0]);
        if (!Page.IsPostBack)
        {
            FillTravelers();
        }
        //... Rest of the code
    }

请注意,如果上面的 Currency 列不同,那么您也需要更改 rows.Cells[index].Controls[0] 的索引。例如,如果货币位于第 5 列,则 txtCurrency 定义变为:

 TextBox txtCurrency = (TextBox)(row.Cells[5].Controls[0]);

如果您无法轻松计算出数据表的列索引(或者如果您使用的是更复杂的数据源),那么假设 GridView1 没有太多列,我建议尝试增加 Cells逐步索引,直到在调试时在 Watch for row.Cells[index].Controls[0] 中看到更新的值。

编辑:(添加代码以检索货币列的列索引) 您可以将“Currency”作为字符串和 OracleDataReader 实例传递给以下方法,这应该为您提供列索引(如果 OracleDataReader 中没有 Currency 列,则它为您提供 -1)。

private int GetColumnIndexIfExists(OracleDataReader dr, string columnName)
{
    for (int i = 0; i < dr.FieldCount; i++)
    {
        if (dr.GetName(i).Equals(columnName))
        {
            return i;
        }
    }
    return -1;
}

然后在实际的代码中,可以如下修改单元格索引加1,因为单元格索引不像列索引那样从零开始。

TextBox txtCurrency = (TextBox)(row.Cells[i+1].Controls[0]);

关于c# - Gridview 更新返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7147378/

相关文章:

c# - 生成 Sonar 属性文件失败。无法完成 SonarQube 分析

c# - 读取图像文件元数据

c# - Asp.Net 在 json 中返回自定义对象

visual-studio-2010 - 如何使用 opencv 创建 cvSobel 函数

c# - .NET 中的验证框架,可以在字段之间进行编辑

c# - Fluent Migrator 单元测试 : Holding onto Connection

asp.net - 如何使用 ASP.NET 和 iframe 跨域对用户进行身份验证?

database - Visual Studio 2010 数据库项目部署到不同的环境

visual-studio-2010 - asp.net - 在调试和重建解决方案时维护 session ?

c# - 检测正在使用哪个网络接口(interface)