c# - 错误 : Index was outside the bounds of the array in a data set C# and T-SQL

标签 c# sql-server tsql

目前我正在努力使用 Visual Studio 在 C# 中创建一个数据集,这最终将用于创建一个图表来显示用户对组的保留时间(就像一个时钟进出系统)

不幸的是,在调试时我注意到了一个错误

Index was outside the bounds of the array

下面是我创建数据集的代码,我想知道是否有人可以用这段代码发现我无法发现的任何小错误。

谢谢。

  {
        string connectionString = null;

        SqlConnection connection ;
        SqlCommand command ;

        SqlDataAdapter adapter = new SqlDataAdapter();
        DataSet RetDs = new DataSet();

        int Counter = 0;

        string Chrt_NamesSql = null;
        string Chrt_RetenSql = null;

        connectionString = @"Data Source = (LocalDB)\MSSQLLocalDB; AttachDbFilename = G:\NEA\GardenRegister\GardenRegister\bin\Debug\GardenRegister.mdf; Integrated Security = True";

        Chrt_NamesSql = "SELECT Name FROM Member";
        Chrt_RetenSql = "SELECT RetentionTime FROM Attendance";

        connection = new SqlConnection(connectionString);

        try
        {
            connection.Open();

            command = new SqlCommand(Chrt_NamesSql, connection);
            adapter.SelectCommand = command;
            adapter.Fill(RetDs, "Member");

            adapter.SelectCommand.CommandText = Chrt_RetenSql;
            adapter.Fill(RetDs, "Attendance");

            adapter.Dispose();
            command.Dispose();
            connection.Close();

            // retrieve first table data 
            for (Counter = 0; Counter <= RetDs.Tables[0].Rows.Count - 1; Counter++)
            {
                MessageBox.Show(RetDs.Tables[0].Rows[Counter].ItemArray[0] + " -- " + RetDs.Tables[0].Rows[Counter].ItemArray[1]);
            }

            // retrieve second table data 
            for (Counter = 0; Counter <= RetDs.Tables[1].Rows.Count - 1; Counter++)
            {
                MessageBox.Show(RetDs.Tables[1].Rows[Counter].ItemArray[0] + " -- " + RetDs.Tables[1].Rows[Counter].ItemArray[1]);
            }
        }

最佳答案

您只从每个表中选择一列,然后尝试访问 ItemArray[1]。您必须更改查询以包括您尝试检索的其他列。

例如,如果您想包含“成员”表的“Id”列,请使用:

SELECT Name, Id FROM Member

当然,“出勤”表也是如此。

关于c# - 错误 : Index was outside the bounds of the array in a data set C# and T-SQL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48851604/

相关文章:

sql-server - SQL Server : Insert Result of WHOAMI into Table

sql - 基于字段数据的行号

tsql - T-SQL 使用 CTE 初始化 View 内的变量

SQL 查找相同的组

c# - 从某些事件中取消表单关闭

c# - Unity currentActivity 在场景变化时会变化吗?

c# - 反序列化客户端 AJAX JSON 日期

c# - 如何为 Entity Framework 和 Windows 窗体加密 ConnectionString

sql - 字符串或二进制数据将被截断。在 SQL Server 中

sql-server - 工作 CREATE VIEW 在 IF NOT EXISTS 中给出语法错误