Sla*_*616 43 c# asp.net datatable
我知道我可以使用while(dr.Read()){...}
但是循环我桌子上的每个字段,我想从第一行中检索所有值,然后是第二行...依此类推.
假设我有一个这样的表格:
ID--------------Value1--------------Value2------------------Value3
1 hello hello2 hello3
2 hi1 hi2 hi3
Run Code Online (Sandbox Code Playgroud)
首先,我想,hello
,hello2
和hello3
,然后去到第二排,并得到所有的值.
有没有办法实现这个目标?我希望有人理解我的意思.
对不起,现在已经解决了.我只是没有正确编码......
是的,SqlDataReader.Read()方法做了它应该做的事情,再次错误是我的.
Ric*_*lly 69
这就是DataReader
它的工作方式,它旨在一次读取一个数据库行.
while(reader.Read())
{
var value1 = reader.GetValue(0); // On first iteration will be hello
var value2 = reader.GetValue(1); // On first iteration will be hello2
var value3 = reader.GetValue(2); // On first iteration will be hello3
}
Run Code Online (Sandbox Code Playgroud)
Mar*_*ell 31
int count = reader.FieldCount;
while(reader.Read()) {
for(int i = 0 ; i < count ; i++) {
Console.WriteLine(reader.GetValue(i));
}
}
Run Code Online (Sandbox Code Playgroud)
注意; 如果你有多个网格,那么:
do {
int count = reader.FieldCount;
while(reader.Read()) {
for(int i = 0 ; i < count ; i++) {
Console.WriteLine(reader.GetValue(i));
}
}
} while (reader.NextResult())
Run Code Online (Sandbox Code Playgroud)
Tud*_*dor 19
或者您可以尝试直接按名称访问列:
while(dr.Read())
{
string col1 = (string)dr["Value1"];
string col2 = (string)dr["Value2"];
string col3 = (string)dr["Value3"];
}
Run Code Online (Sandbox Code Playgroud)
无法立即获得"整行" - 您需要循环遍历行,并且对于每一行,您需要分别读取每一列:
using(SqlDataReader rdr = cmd.ExecuteReader())
{
while (rdr.Read())
{
string value1 = rdr.GetString(0);
string value2 = rdr.GetString(1);
string value3 = rdr.GetString(2);
}
}
Run Code Online (Sandbox Code Playgroud)
你对每行读取的字符串做什么完全取决于你 - 你可以把它们存储到你定义的类中,或者其他什么......