将SqlDataReader值复制到数组 [英] Copy SqlDataReader values to an Array

查看:80
本文介绍了将SqlDataReader值复制到数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将SqlDataReader值复制到数组.我在SqlDataReader上有qno.有人可以帮我吗?

I need to copy SqlDataReader values to an Array. I have qno''s on SqlDataReader. Can some one help me?

protected void Page_Load(object sender, EventArgs e)
   {
       SqlCommand cmd = new SqlCommand("select qno from QUIZ1 where applicationname = @appname", con);
       cmd.Parameters.AddWithValue("@appname", "MFDL");
       con.Open();

       SqlDataReader sdr = cmd.ExecuteReader();
       while (sdr.Read())
       {
           string[] numb;
           numb = new string[sdr.FieldCount];
           for (int i = 0; i < sdr.FieldCount; i++)
           {
               numb[i] = sdr[i].ToString();

           }
           Label1.Text = numb[0].ToString();

       }

推荐答案

从您的代码中,我想您正在尝试获取所有行的所有列.
为此,取一个包含对象ArraysArrayList,它们是DataReader行.
From your code, I guess you are trying to get all the columns of all the rows.

For that, take one ArrayList containing object Arrays, which are DataReader rows.
ArrayList al = new ArrayList();

while(sdr.Read()) {
    Object[] numb = new Object[sdr.FieldCount];
    
    // Get the Row with all its column values..
    sdr.GetValues(values);
    
    // Add this Row to ArrayList.
    al.Add(values);
}

// Now the ArrayList is having all the Rows and their respective column values.
// Do whatever you want to do now. Below is the code to write all the values.

dr.Close();
con.Close();

// Writing all the Column values of all the Rows.
foreach(Object[] row in al) {
    foreach(object column in row) {
        Response.Write(column.ToString() + "<br>");
    }
}


显然在代码中有问题...

clearly there is problem in code ...

while (sdr.Read())
{
string[] numb;




每次numb数组都会重新初始化..因此,请将此数组保留在循环之外,然后应该可以正常工作




everytime numb array will reinitialize .... so keep this array outside the loop then it should work fine


您只需选择qno,因此while循环内不需要for循环.试试这个代码
You select only qno, so there is not need of the for loop inside the while loop. Try this code
SqlDataReader sdr = cmd.ExecuteReader();
List<string> numb = new List<string>();
while (sdr.Read())
{
numb.Add(sdr[0].ToString());
}


这篇关于将SqlDataReader值复制到数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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