使用 While() 结构时 Gridview 不会填充。 C# ASP.NET
我在使用此网格视图时遇到问题。我正在用查询填充它。但是,如果我使用 while(reader.Read()) 结构,它不会填充甚至不会出现。没有 while 结构,它工作得很好。但是,我需要访问两个特定字段。代码如下。
SqlDataReader myReader;
try
{
using (myConnection)
{
myConnection.Open();
ArrayList arrliGames = new ArrayList();
myReader = myCommand.ExecuteReader();
decimal decTicketCost = 0;
int intTicketCount = 0;
while (myReader.Read ())
{
decTicketCost = Convert .ToDecimal (myReader ["TicketCost"]);
intTicketCount =Convert .ToInt32 (myReader ["NumTickets"]);
}
//Binds listbox
grdEvents.DataSource = myReader ;
grdEvents.DataBind();
}
}
I am having problems with this grid view. I am populating it with a query. However, it will not populate or even appear if I use a while(reader.Read()) structure. Without the while structure, it works fine. However, I need to access two specific fields. The code is below.
SqlDataReader myReader;
try
{
using (myConnection)
{
myConnection.Open();
ArrayList arrliGames = new ArrayList();
myReader = myCommand.ExecuteReader();
decimal decTicketCost = 0;
int intTicketCount = 0;
while (myReader.Read ())
{
decTicketCost = Convert .ToDecimal (myReader ["TicketCost"]);
intTicketCount =Convert .ToInt32 (myReader ["NumTickets"]);
}
//Binds listbox
grdEvents.DataSource = myReader ;
grdEvents.DataBind();
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
SqlDataReader
是只向前的。当您第一次迭代行时,其中“没有剩下任何内容”可以稍后显示。我建议您使用阅读器在内存中填充强类型列表,然后将 GridView 绑定到该列表。示例:
上面的代码示例假设您有一个名为
TicketInfo
的类,定义为:如果您之前没有使用过泛型(例如示例中的
List
) ,我建议您阅读有关该主题的内容< /a>.The
SqlDataReader
is forward-only. When you first iterate over the rows, there is "nothing left" in it to display afterwards.I suggest that you use the reader to populate a strongly-typed list in memory, and then bind the GridView to the list instead. Example:
The code example above assumes that you have a class called
TicketInfo
defined as:If you haven't used generics (such as
List<TicketInfo>
in the example) before, I suggest you do some reading on the subject.创建一个具有两个属性的类
1. dec门票费用
2. intTicketCount
现在在 while 循环中创建实例并将值分配给对象属性
并将其添加到列表中。
最后绑定列表。
create a class with two properties
1. decTicketCost
2. intTicketCount
now in while loop create instance and assign the value to the object properties
and add it in a list.
Finally bind the list.
我猜您已将数据源设置为
myList
而不是myReader
编辑: 您需要在列表对象中添加其他列。
I guest you have set datasource to
myList
insteadmyReader
Edit: You need to add other column in your list object.
你可以替换
为
grdEvents.DataSource = myReader ;
grdEvents.DataBind();
然后 gridview 的一些值
希望这有帮助
You could replace
to
grdEvents.DataSource = myReader ;
grdEvents.DataBind();
And then the gridview for some values
hope this help
将以下行替换
为
replace the following line
with
这个怎么样:
How about this: