使用for循环将数据绑定到gridview [英] bind data into gridview using for loop

查看:83
本文介绍了使用for循环将数据绑定到gridview的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个gridview,我想从循环中绑定它,其中循环包含来自数据库的数据,并且gridview仅显示最后一条记录.我想显示所有记录,这些数据根据查询.


我在for循环中查询......

i have a gridview and i want to bind it from the loop in which loop contain data from database and gridview displays only last record. i want to display all records which data is according to query.


my query in for loop like...

for (int k = 0; k < intArray.Length; k++)
{

string xxxx = "select title from document where id in(''"+intArray[k]+"'')";
ad1 = new SqlDataAdapter(xxxx, c.getcon());
ds1 = new DataSet();
ad1.Fill(ds1);

if (ds.Tables[0].Rows.Count != 0)
{
GridView1.DataSource = ds1;
GridView1.DataBind();
}

推荐答案

为什么需要循环?

试试这个解决方案,我刚刚删除了循环.
Why do you need for loop?

Try this solution, i have just removed for loop.
string xxxx = "select title from document";
ad1 = new SqlDataAdapter(xxxx, c.getcon());
ds1 = new DataSet();
ad1.Fill(ds1);

if (ds1.Tables[0].Rows.Count != 0)
{
GridView1.DataSource = ds1;
GridView1.DataBind();
}


这不是正确的方法.
实际上,您在循环的每次迭代中都覆盖了gridview源.

试试类似的东西
This is not quite the correct approach.
You are actually overriding the gridview source in every iteration of the loop.

Try something similar to this
string xxxx = "select title from document where id in(''";
for (int k = 0; k < intArray.Length; k++)
{
xxxx+=intArray[k]+"'',"
}
xxxx=xxxx.SubString(0,xxxx.length-1) + ")";
 
ad1 = new SqlDataAdapter(xxxx, c.getcon());
ds1 = new DataSet();
ad1.Fill(ds1);
 
if (ds.Tables[0].Rows.Count != 0)
{
GridView1.DataSource = ds1;
GridView1.DataBind();
}


仅当您获得所需的解决方案时,才对where条件进行for循环.

Make the for loop for the where condition only when you will get the desired solution.

string xxxx;
for (int k = 0; k < intArray.Length; k++)
{
    xxxx += "'" + intArray[k] + "'," ;
}

xxxx = xxxx.Substring(0, xxxx.Length - 1);
SqlCommand cmd = new SqlCommand("select title from document where id in " + xxxx + ")", cn);
ad1 = new SqlDataAdapter(xxxx, c.getcon());
ds1 = new DataSet();
ad1.Fill(ds1);

if (ds1.Tables[0].Rows.Count != 0)
{
GridView1.DataSource = ds1;
GridView1.DataBind();
}


这篇关于使用for循环将数据绑定到gridview的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆