【问题标题】:ASP.Net - constructing a Dataset from a single Grid RowASP.Net - 从单个网格行构造数据集
【发布时间】:2015-05-01 16:33:13
【问题描述】:

我正在制作一个 ASP.Net 网站。其中一个页面包含我要显示的用户的 GridView。每行代表一个用户。

当点击Search 按钮时,我想通过他们的名字找到一个特定的用户行(我已经实现了);然后,我想将只包含那一行的数据集传递给缓存(然后将更新并显示在 gridView 中)。

所以我做了这个:

protected void Search_Click(object 
        sender, EventArgs e)
    {
        GridViewRow myRow = findRow(UsersView, userSearched.Text, 0);
        if (myRow==null)//Pretty much a must-have since it's QD built.
        {
            ResponseLabel.ForeColor = System.Drawing.Color.Red;
            ResponseLabel.Text = "User not found.";
            return;
        }
        ResponseLabel.ForeColor = System.Drawing.Color.Green;
        ResponseLabel.Text = "There you go.";
        DataTable container = new DataTable(); // the problem starts here
        DataRow convertedForTable = container.NewRow();
        for (int i = 0; i < myRow.Cells.Count; i++)
        {
            convertedForTable.ItemArray[i] = myRow.Cells[i].Text;
        }

        Cache["Users"] = container;
        UpdateSource(); // puts a dataset in the gridView.
    }

我在数据行 itemArray 中得到一个 IndexOutOfBounds。 - 这是在许多不同的尝试以许多不同的方式做到这一点之后。我想知道如何才能完成这项工作,或者如果有更好的解决方案。

【问题讨论】:

  • 您不应该在访问 ItemArray 之前为新的 DataTable 定义列吗?
  • 你的代码有问题,你解决了吗?

标签: c# asp.net gridview dataset


【解决方案1】:

你的代码有问题

首先,如果你运行它,你会得到这个错误:

索引超出了数组的范围。

因此您可以通过 Cells.Count 创建一个行数组对象,然后将单元格项目文本设置为数组项目,之后您可以将其设置为 ItemArray,如下所示:

DataTable container = new DataTable(); 
DataRow convertedForTable = container.NewRow();
object[] rowArray = new object[myRow.Cells.Count];
for (int i = 0; i < myRow.Cells.Count; i++)
     {
            rowArray[i] = myRow.Cells[i].Text;
     }
convertedForTable.ItemArray = rowArray;

其次,但是通过运行上面的代码,你也会得到这个错误:

输入数组长于该表的列数。

您知道为什么,因为container 数据表单元格的数量必须等于 myRow 单元格,换句话说,containar 没有任何列!

所以我想myRow 有类似下面代码的列:

DataTable container= new DataTable();
container.Columns.Add(new DataColumn("UserName", typeof(string)));
container.Columns.Add(new DataColumn("Name", typeof(string)));
container.Columns.Add(new DataColumn("Family", typeof(string)));
DataRow convertedForTable = container.NewRow();
object[] rowArray = new object[myRow.Cells.Count];
for (int i = 0; i < myRow.Cells.Count; i++)
       rowArray[i] = myRow.Cells[i].Text;
convertedForTable.ItemArray = rowArray;
container.Rows.Add(convertedForTable);

上面的代码工作正常, 要解决您的问题,请查看DataRow and ItemArray 这个LinkASP.Net Caching Techniques and Best Practices 可以用于DataTable 缓存。

希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 2011-10-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-09-22
    • 1970-01-01
    • 2023-03-24
    相关资源
    最近更新 更多