System.IndexOutOfRangeException: 找不到表 0

本文关键字:找不到 IndexOutOfRangeException System | 更新日期: 2023-09-27 18:33:39

dal代码

 public DataSet selectlogin(string u_name, string u_password, string u_email, string action)
    {
        SqlConnection con = new SqlConnection(h);
        SqlCommand cmd = new SqlCommand("", con);
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.CommandText = "sp_login";
        cmd.Parameters.AddWithValue("@name", u_name);
        cmd.Parameters.AddWithValue("@email", u_email);
        cmd.Parameters.AddWithValue("@password", u_password);
        cmd.Parameters.AddWithValue("@action", action);
        con.Open();
        cmd.ExecuteNonQuery();
    DataSet ds = new DataSet();
    SqlDataAdapter ad = new SqlDataAdapter(cmd);
    ad.Fill(ds);
    return ds;
    con.Close();
}

巴尔代码

 public DataSet selectlogin(string u_name, string u_password, string u_email, string action)
    {
        DataSet ds = new DataSet();
        ds = obj.selectlogin(u_name, u_password, u_email, action);
        return ds;
    }

CS 代码

protected void Btn_log(object sender, EventArgs e)
    {
        DataSet ds = new DataSet();
        ds = obj.selectlogin("", TextBox1.Text, TextBox2.Text,"login");
        if (ds.Tables[0].Rows.Count > 0)
        {
            Response.Redirect("dashboard.aspx");
        }

    }

存储过程

if(@action='login')
select * from login where u_email=@email and u_pass=@password

System.IndexOutOfRangeException: 找不到表 0

问题可能就在这里:

if (ds.Tables[0].Rows.Count > 0)

首先检查索引为 0 的表是否存在,然后尝试访问属性...

if (ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0 )

这应该会有所帮助。或者至少它会告诉你返回的数据集是空的(里面没有表)。

试试这个

protected void Btn_log(object sender, EventArgs e)
    {
        DataSet ds = new DataSet();
        ds = obj.selectlogin("", TextBox1.Text, TextBox2.Text,"login");
    bool hasRows = ds.Tables.Cast<DataTable>()
                               .Any(table => table.Rows.Count != 0);
        if (hasRows)
        {
            Response.Redirect("dashboard.aspx");
        }
    }

或者试试看(使用 != 运算符而不是>运算符

if (ds.Tables[0].Rows.Count **!=** 0)
        {
            Response.Redirect("dashboard.aspx");
        }

CS 代码

protected void Btn_log(object sender, EventArgs e)
{
    DataSet ds = new DataSet();
    ds = obj.selectlogin("", TextBox1.Text, TextBox2.Text,"login");
    if (ds!=null && ds.Tables[0].Count > 0 && ds.Tables[0].Rows.Count > 0)
    {
        Response.Redirect("dashboard.aspx");
    }
}