C# aspx中的for循环

C# aspx中的for循环,c#,asp.net,database,for-loop,webforms,C#,Asp.net,Database,For Loop,Webforms,当有用户id时,我有数据库; 我有一个for循环,我希望循环运行到最后一个ID 示例:for(i=0;i>something;i++) 我的问题是这应该是什么? 我还有代码的开头 using System; using System.Collections.Generic; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data; using System.Data.Ole

当有用户id时,我有数据库; 我有一个for循环,我希望循环运行到最后一个ID 示例:
for(i=0;i>something;i++)
我的问题是这应该是什么? 我还有代码的开头

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.OleDb;

public partial class _Default : System.Web.UI.Page
{
    public string strLname;
    public string strEmail;
    public string strFname;
    protected void Page_Load(object sender, EventArgs e)
    {

        string dbPath = Server.MapPath(@"App_Data") + "/my_site.mdb";
        string connectionString = @"Data Source='" + dbPath + "';Provider='Microsoft.Jet.OLEDB.4.0';";
        OleDbConnection con = new OleDbConnection(connectionString);
        con.Open();
        string QueryString = "SELECT * FROM tbl_users";
        OleDbCommand cmd = new OleDbCommand(QueryString, con);
        OleDbDataAdapter da = new OleDbDataAdapter(cmd);
        DataSet ds = new DataSet();
        da.Fill(ds, "tbl");
        con.Close();
        for (i=0; i < *something*; i++)

        }
    }
使用系统;
使用System.Collections.Generic;
使用System.Web;
使用System.Web.UI;
使用System.Web.UI.WebControl;
使用系统数据;
使用System.Data.OleDb;
公共部分类\u默认值:System.Web.UI.Page
{
公共字符串strLname;
公共字符串邮件;
公共字符串strFname;
受保护的无效页面加载(对象发送方、事件参数e)
{
字符串dbPath=Server.MapPath(@“App_Data”)+“/my_site.mdb”;
字符串连接字符串=@“数据源=”+dbPath+”;提供程序='Microsoft.Jet.OLEDB.4.0';“;
OLEDB连接con=新的OLEDB连接(connectionString);
con.Open();
string QueryString=“选择*来自tbl\U用户”;
OleDbCommand cmd=新的OleDbCommand(查询字符串,con);
OleDbDataAdapter da=新的OleDbDataAdapter(cmd);
数据集ds=新数据集();
da.填写(ds,“待定”);
con.Close();
对于(i=0;i<*某物*;i++)
}
}

foreach的
循环会更方便,不是吗

foreach(DataRow row in ds.Tables["tbl"].Rows) {
    // ...
}
ID将是每行中的
行[“ID”]
。(或者随便你怎么称呼它。)


如果您计划在
for
循环中使用
i
作为ID,请小心删除行。

您可以在索引0处使用表的
行计数或您拥有的任何索引

for (i=0; i < ds.Tables[0].Rows.Count; i++)
{

}
for(i=0;i
我认为如果使用foreach会更好。 类似于

foreach(DataRow dRow in ds.Table["Your Table Name"].Rows)
{
    //    dRow["id"] is your id column and you can access the value in that 
    //some sort of your operation code comparison or anything you want
}
我还注意到您的代码中有一些您没有使用故障保护的内容。
因此,请记住,在编写代码时,在处理数据库连接和相关工作时,请不要忘记使用try-catch。

小注释,您可能需要执行
i
,否则循环可能需要一段时间才能结束…;)是的,这是一个错误,但是你知道这应该是什么吗?对于DataTables,可以方便地执行foreach(DataRow-row-ds.Tables[“tbl”].Rows)
,因为你会得到
对象的实例,否则会很不方便…@Rene-Wolferink:啊,真的吗?谢谢(为什么?)如果不使用
var
,则
foreach
循环将自动将对象强制转换为指定类型。这里的更多信息:如果您查看底层IL代码,您会发现,如果请求的类型与编译时提供的类型不同,那么在获取下一个值后,它将添加一个强制转换:
castclass[System.Data]System.Data.DataRow
基本上是向后兼容的。它从一开始就实现了
ICollection
IEnumerable
(非泛型的)。我想他们从来没有费心在上面加上通用的枚举数。