【问题标题】:How to update a datasource dynamically C#?如何动态更新数据源 C#?
【发布时间】:2014-12-04 14:41:57
【问题描述】:

我有根据所选日期显示信息的日历。 是这样的:

string queryString = "SELECT * from events";
SqlCommand thisCommand = thisConnection.CreateCommand();
thisCommand.CommandText = queryString;
SqlDataReader reader = thisCommand.ExecuteReader();
if(true)
    queryString = "SELECT Text from events where repeat = 1";
else 
    queryString = "SELECT Text from events where repeat = 0";

GridView1.DataSource = reader ;
GridView1.Bind();

我得到的错误是“数据源不支持服务器端数据分页”

【问题讨论】:

  • 该代码无法编译... queryString 在此示例中未正确声明
  • 我修好了,我忘了粘贴初始声明。
  • 您的 UI 中是否需要 paging 行为?
  • 是的,但这不是一个很大的要求。

标签: c# sql asp.net datasource


【解决方案1】:

您应该使用 SqlDataAdapter 来填充 DataTable,然后将数据表用作您的 gridview 的数据源。 SqlReader 是用于快速访问 sql 数据的类,不适合作为数据源。

var adapter = new SqlDataAdapter(thisCommand);
var table = new DataTable();
adapter.Fill(table);

GridView1.DataSource = table;
GridView1.Bind();   

不过,您将在 Web 服务器上进行所有排序/分页 - 此操作最好直接在 SQL 服务器上处理。所以我建议使用 ObjectDataSource 或 LinqDataSource 并适当调整查询以处理 SQL 服务器级别的分页/排序。

【讨论】:

  • 当我更改日历的 selectedDates 时,我得到这个异常:“已经有一个打开的 DataReader 与此命令关联,必须先关闭”
猜你喜欢
  • 2015-07-17
  • 2013-01-07
  • 1970-01-01
  • 1970-01-01
  • 2021-05-26
  • 1970-01-01
  • 2015-06-14
  • 1970-01-01
  • 2011-09-10
相关资源
最近更新 更多